/
opt
/
alt
/
alt-nodejs10
/
root
/
usr
/
share
/
doc
/
alt-nodejs10-nodejs-10.24.1
/
html
/
api
/
Upload Filee
HOME
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Node.js v10.24.1 Documentation</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic"> <link rel="stylesheet" href="assets/style.css"> <link rel="stylesheet" href="assets/sh.css"> <link rel="canonical" href="https://nodejs.org/api/all.html"> </head> <body class="alt apidoc" id="api-section-all"> <div id="content" class="clearfix"> <div id="column2" class="interior"> <div id="intro" class="interior"> <a href="/" title="Go back to the home page"> Node.js </a> </div> <ul> <li><a href="documentation.html" class="nav-documentation">About these Docs</a></li> <li><a href="synopsis.html" class="nav-synopsis">Usage & Example</a></li> </ul> <div class="line"></div> <ul> <li><a href="assert.html" class="nav-assert">Assertion Testing</a></li> <li><a href="async_hooks.html" class="nav-async_hooks">Async Hooks</a></li> <li><a href="buffer.html" class="nav-buffer">Buffer</a></li> <li><a href="addons.html" class="nav-addons">C++ Addons</a></li> <li><a href="n-api.html" class="nav-n-api">C/C++ Addons - N-API</a></li> <li><a href="child_process.html" class="nav-child_process">Child Processes</a></li> <li><a href="cluster.html" class="nav-cluster">Cluster</a></li> <li><a href="cli.html" class="nav-cli">Command Line Options</a></li> <li><a href="console.html" class="nav-console">Console</a></li> <li><a href="crypto.html" class="nav-crypto">Crypto</a></li> <li><a href="debugger.html" class="nav-debugger">Debugger</a></li> <li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li> <li><a href="dns.html" class="nav-dns">DNS</a></li> <li><a href="domain.html" class="nav-domain">Domain</a></li> <li><a href="esm.html" class="nav-esm">ECMAScript Modules</a></li> <li><a href="errors.html" class="nav-errors">Errors</a></li> <li><a href="events.html" class="nav-events">Events</a></li> <li><a href="fs.html" class="nav-fs">File System</a></li> <li><a href="globals.html" class="nav-globals">Globals</a></li> <li><a href="http.html" class="nav-http">HTTP</a></li> <li><a href="http2.html" class="nav-http2">HTTP/2</a></li> <li><a href="https.html" class="nav-https">HTTPS</a></li> <li><a href="inspector.html" class="nav-inspector">Inspector</a></li> <li><a href="intl.html" class="nav-intl">Internationalization</a></li> <li><a href="modules.html" class="nav-modules">Modules</a></li> <li><a href="net.html" class="nav-net">Net</a></li> <li><a href="os.html" class="nav-os">OS</a></li> <li><a href="path.html" class="nav-path">Path</a></li> <li><a href="perf_hooks.html" class="nav-perf_hooks">Performance Hooks</a></li> <li><a href="process.html" class="nav-process">Process</a></li> <li><a href="punycode.html" class="nav-punycode">Punycode</a></li> <li><a href="querystring.html" class="nav-querystring">Query Strings</a></li> <li><a href="readline.html" class="nav-readline">Readline</a></li> <li><a href="repl.html" class="nav-repl">REPL</a></li> <li><a href="stream.html" class="nav-stream">Stream</a></li> <li><a href="string_decoder.html" class="nav-string_decoder">String Decoder</a></li> <li><a href="timers.html" class="nav-timers">Timers</a></li> <li><a href="tls.html" class="nav-tls">TLS/SSL</a></li> <li><a href="tracing.html" class="nav-tracing">Trace Events</a></li> <li><a href="tty.html" class="nav-tty">TTY</a></li> <li><a href="dgram.html" class="nav-dgram">UDP/Datagram</a></li> <li><a href="url.html" class="nav-url">URL</a></li> <li><a href="util.html" class="nav-util">Utilities</a></li> <li><a href="v8.html" class="nav-v8">V8</a></li> <li><a href="vm.html" class="nav-vm">VM</a></li> <li><a href="worker_threads.html" class="nav-worker_threads">Worker Threads</a></li> <li><a href="zlib.html" class="nav-zlib">Zlib</a></li> </ul> <div class="line"></div> <ul> <li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">GitHub Repo & Issue Tracker</a></li> </ul> </div> <div id="column1" data-id="all" class="interior"> <header> <h1>Node.js v10.24.1 Documentation</h1> <div id="gtoc"> <ul> <li> <a href="index.html" name="toc">Index</a> </li> <li> <a href="all.html">View on single page</a> </li> <li> <a href="all.json">View as JSON</a> </li> <li class="version-picker"> <a href="#">View another version <span>▼</span></a> <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v15.x/api/all.html">15.x</a></li> <li><a href="https://nodejs.org/docs/latest-v14.x/api/all.html">14.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v13.x/api/all.html">13.x</a></li> <li><a href="https://nodejs.org/docs/latest-v12.x/api/all.html">12.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v11.x/api/all.html">11.x</a></li> <li><a href="https://nodejs.org/docs/latest-v10.x/api/all.html">10.x <b>LTS</b></a></li> <li><a href="https://nodejs.org/docs/latest-v9.x/api/all.html">9.x</a></li> <li><a href="https://nodejs.org/docs/latest-v8.x/api/all.html">8.x</a></li> <li><a href="https://nodejs.org/docs/latest-v7.x/api/all.html">7.x</a></li> <li><a href="https://nodejs.org/docs/latest-v6.x/api/all.html">6.x</a></li> <li><a href="https://nodejs.org/docs/latest-v5.x/api/all.html">5.x</a></li> <li><a href="https://nodejs.org/docs/latest-v4.x/api/all.html">4.x</a></li> <li><a href="https://nodejs.org/docs/latest-v0.12.x/api/all.html">0.12.x</a></li> <li><a href="https://nodejs.org/docs/latest-v0.10.x/api/all.html">0.10.x</a></li></ol> </li> </ul> </div> <hr> </header> <div id="toc"> <h2>Table of Contents</h2> <ul> <li> <p><a href="#documentation_about_this_documentation">About this Documentation</a></p> <ul> <li><a href="#documentation_contributing">Contributing</a></li> <li><a href="#documentation_stability_index">Stability Index</a></li> <li><span class="stability_1"><a href="#documentation_json_output">JSON Output</a></span></li> <li><a href="#documentation_syscalls_and_man_pages">Syscalls and man pages</a></li> </ul> </li> <li> <p><a href="#synopsis_usage">Usage</a></p> <ul> <li><a href="#synopsis_example">Example</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#assert_assert">Assert</a></span></p> <ul> <li> <p><a href="#assert_class_assert_assertionerror">Class: assert.AssertionError</a></p> <ul> <li><a href="#assert_new_assert_assertionerror_options">new assert.AssertionError(options)</a></li> </ul> </li> <li><a href="#assert_strict_mode">Strict mode</a></li> <li><a href="#assert_legacy_mode">Legacy mode</a></li> <li><a href="#assert_assert_value_message">assert(value[, message])</a></li> <li><a href="#assert_assert_deepequal_actual_expected_message">assert.deepEqual(actual, expected[, message])</a></li> <li> <p><a href="#assert_assert_deepstrictequal_actual_expected_message">assert.deepStrictEqual(actual, expected[, message])</a></p> <ul> <li><a href="#assert_comparison_details">Comparison details</a></li> </ul> </li> <li><a href="#assert_assert_doesnotreject_asyncfn_error_message">assert.doesNotReject(asyncFn[, error][, message])</a></li> <li><a href="#assert_assert_doesnotthrow_fn_error_message">assert.doesNotThrow(fn[, error][, message])</a></li> <li><a href="#assert_assert_equal_actual_expected_message">assert.equal(actual, expected[, message])</a></li> <li><a href="#assert_assert_fail_message">assert.fail([message])</a></li> <li><span class="stability_0"><a href="#assert_assert_fail_actual_expected_message_operator_stackstartfn">assert.fail(actual, expected[, message[, operator[, stackStartFn]]])</a></span></li> <li><a href="#assert_assert_iferror_value">assert.ifError(value)</a></li> <li><a href="#assert_assert_notdeepequal_actual_expected_message">assert.notDeepEqual(actual, expected[, message])</a></li> <li><a href="#assert_assert_notdeepstrictequal_actual_expected_message">assert.notDeepStrictEqual(actual, expected[, message])</a></li> <li><a href="#assert_assert_notequal_actual_expected_message">assert.notEqual(actual, expected[, message])</a></li> <li><a href="#assert_assert_notstrictequal_actual_expected_message">assert.notStrictEqual(actual, expected[, message])</a></li> <li><a href="#assert_assert_ok_value_message">assert.ok(value[, message])</a></li> <li><a href="#assert_assert_rejects_asyncfn_error_message">assert.rejects(asyncFn[, error][, message])</a></li> <li><a href="#assert_assert_strictequal_actual_expected_message">assert.strictEqual(actual, expected[, message])</a></li> <li><a href="#assert_assert_throws_fn_error_message">assert.throws(fn[, error][, message])</a></li> </ul> </li> <li> <p><span class="stability_1"><a href="#async_hooks_async_hooks">Async Hooks</a></span></p> <ul> <li><a href="#async_hooks_terminology">Terminology</a></li> <li> <p><a href="#async_hooks_public_api">Public API</a></p> <ul> <li> <p><a href="#async_hooks_overview">Overview</a></p> <ul> <li> <p><a href="#async_hooks_async_hooks_createhook_callbacks">async_hooks.createHook(callbacks)</a></p> <ul> <li><a href="#async_hooks_error_handling">Error Handling</a></li> <li><a href="#async_hooks_printing_in_asynchooks_callbacks">Printing in AsyncHooks callbacks</a></li> </ul> </li> <li><a href="#async_hooks_asynchook_enable">asyncHook.enable()</a></li> <li><a href="#async_hooks_asynchook_disable">asyncHook.disable()</a></li> <li> <p><a href="#async_hooks_hook_callbacks">Hook Callbacks</a></p> <ul> <li> <p><a href="#async_hooks_init_asyncid_type_triggerasyncid_resource">init(asyncId, type, triggerAsyncId, resource)</a></p> <ul> <li><a href="#async_hooks_type"><code>type</code></a></li> <li><a href="#async_hooks_triggerasyncid"><code>triggerAsyncId</code></a></li> <li><a href="#async_hooks_resource"><code>resource</code></a></li> <li><a href="#async_hooks_asynchronous_context_example">Asynchronous context example</a></li> </ul> </li> <li><a href="#async_hooks_before_asyncid">before(asyncId)</a></li> <li><a href="#async_hooks_after_asyncid">after(asyncId)</a></li> <li><a href="#async_hooks_destroy_asyncid">destroy(asyncId)</a></li> <li><a href="#async_hooks_promiseresolve_asyncid">promiseResolve(asyncId)</a></li> </ul> </li> <li><a href="#async_hooks_async_hooks_executionasyncid">async_hooks.executionAsyncId()</a></li> <li><a href="#async_hooks_async_hooks_triggerasyncid">async_hooks.triggerAsyncId()</a></li> </ul> </li> </ul> </li> <li><a href="#async_hooks_promise_execution_tracking">Promise execution tracking</a></li> <li> <p><a href="#async_hooks_javascript_embedder_api">JavaScript Embedder API</a></p> <ul> <li> <p><a href="#async_hooks_class_asyncresource">Class: AsyncResource</a></p> <ul> <li><a href="#async_hooks_new_asyncresource_type_options">new AsyncResource(type[, options])</a></li> <li><a href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args">asyncResource.runInAsyncScope(fn[, thisArg, ...args])</a></li> <li><span class="stability_0"><a href="#async_hooks_asyncresource_emitbefore">asyncResource.emitBefore()</a></span></li> <li><span class="stability_0"><a href="#async_hooks_asyncresource_emitafter">asyncResource.emitAfter()</a></span></li> <li><a href="#async_hooks_asyncresource_emitdestroy">asyncResource.emitDestroy()</a></li> <li><a href="#async_hooks_asyncresource_asyncid">asyncResource.asyncId()</a></li> <li><a href="#async_hooks_asyncresource_triggerasyncid">asyncResource.triggerAsyncId()</a></li> </ul> </li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#buffer_buffer">Buffer</a></span></p> <ul> <li> <p><a href="#buffer_buffer_from_buffer_alloc_and_buffer_allocunsafe"><code>Buffer.from()</code>, <code>Buffer.alloc()</code>, and <code>Buffer.allocUnsafe()</code></a></p> <ul> <li><a href="#buffer_the_zero_fill_buffers_command_line_option">The <code>--zero-fill-buffers</code> command line option</a></li> <li><a href="#buffer_what_makes_buffer_allocunsafe_and_buffer_allocunsafeslow_unsafe">What makes <code>Buffer.allocUnsafe()</code> and <code>Buffer.allocUnsafeSlow()</code> "unsafe"?</a></li> </ul> </li> <li><a href="#buffer_buffers_and_character_encodings">Buffers and Character Encodings</a></li> <li><a href="#buffer_buffers_and_typedarray">Buffers and TypedArray</a></li> <li><a href="#buffer_buffers_and_iteration">Buffers and iteration</a></li> <li> <p><a href="#buffer_class_buffer">Class: Buffer</a></p> <ul> <li><span class="stability_0"><a href="#buffer_new_buffer_array">new Buffer(array)</a></span></li> <li><span class="stability_0"><a href="#buffer_new_buffer_arraybuffer_byteoffset_length">new Buffer(arrayBuffer[, byteOffset[, length]])</a></span></li> <li><span class="stability_0"><a href="#buffer_new_buffer_buffer">new Buffer(buffer)</a></span></li> <li><span class="stability_0"><a href="#buffer_new_buffer_size">new Buffer(size)</a></span></li> <li><span class="stability_0"><a href="#buffer_new_buffer_string_encoding">new Buffer(string[, encoding])</a></span></li> <li><a href="#buffer_class_method_buffer_alloc_size_fill_encoding">Class Method: Buffer.alloc(size[, fill[, encoding]])</a></li> <li><a href="#buffer_class_method_buffer_allocunsafe_size">Class Method: Buffer.allocUnsafe(size)</a></li> <li><a href="#buffer_class_method_buffer_allocunsafeslow_size">Class Method: Buffer.allocUnsafeSlow(size)</a></li> <li><a href="#buffer_class_method_buffer_bytelength_string_encoding">Class Method: Buffer.byteLength(string[, encoding])</a></li> <li><a href="#buffer_class_method_buffer_compare_buf1_buf2">Class Method: Buffer.compare(buf1, buf2)</a></li> <li><a href="#buffer_class_method_buffer_concat_list_totallength">Class Method: Buffer.concat(list[, totalLength])</a></li> <li><a href="#buffer_class_method_buffer_from_array">Class Method: Buffer.from(array)</a></li> <li><a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length">Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])</a></li> <li><a href="#buffer_class_method_buffer_from_buffer">Class Method: Buffer.from(buffer)</a></li> <li><a href="#buffer_class_method_buffer_from_object_offsetorencoding_length">Class Method: Buffer.from(object[, offsetOrEncoding[, length]])</a></li> <li><a href="#buffer_class_method_buffer_from_string_encoding">Class Method: Buffer.from(string[, encoding])</a></li> <li><a href="#buffer_class_method_buffer_isbuffer_obj">Class Method: Buffer.isBuffer(obj)</a></li> <li><a href="#buffer_class_method_buffer_isencoding_encoding">Class Method: Buffer.isEncoding(encoding)</a></li> <li><a href="#buffer_class_property_buffer_poolsize">Class Property: Buffer.poolSize</a></li> <li><a href="#buffer_buf_index">buf[index]</a></li> <li><a href="#buffer_buf_buffer">buf.buffer</a></li> <li><a href="#buffer_buf_byteoffset">buf.byteOffset</a></li> <li><a href="#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend">buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])</a></li> <li><a href="#buffer_buf_copy_target_targetstart_sourcestart_sourceend">buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])</a></li> <li><a href="#buffer_buf_entries">buf.entries()</a></li> <li><a href="#buffer_buf_equals_otherbuffer">buf.equals(otherBuffer)</a></li> <li><a href="#buffer_buf_fill_value_offset_end_encoding">buf.fill(value[, offset[, end]][, encoding])</a></li> <li><a href="#buffer_buf_includes_value_byteoffset_encoding">buf.includes(value[, byteOffset][, encoding])</a></li> <li><a href="#buffer_buf_indexof_value_byteoffset_encoding">buf.indexOf(value[, byteOffset][, encoding])</a></li> <li><a href="#buffer_buf_keys">buf.keys()</a></li> <li><a href="#buffer_buf_lastindexof_value_byteoffset_encoding">buf.lastIndexOf(value[, byteOffset][, encoding])</a></li> <li><a href="#buffer_buf_length">buf.length</a></li> <li><span class="stability_0"><a href="#buffer_buf_parent">buf.parent</a></span></li> <li><a href="#buffer_buf_readbigint64be_offset">buf.readBigInt64BE(offset)</a></li> <li><a href="#buffer_buf_readbigint64le_offset">buf.readBigInt64LE(offset)</a></li> <li><a href="#buffer_buf_readbiguint64be_offset">buf.readBigUInt64BE(offset)</a></li> <li><a href="#buffer_buf_readbiguint64le_offset">buf.readBigUInt64LE(offset)</a></li> <li><a href="#buffer_buf_readdoublebe_offset">buf.readDoubleBE(offset)</a></li> <li><a href="#buffer_buf_readdoublele_offset">buf.readDoubleLE(offset)</a></li> <li><a href="#buffer_buf_readfloatbe_offset">buf.readFloatBE(offset)</a></li> <li><a href="#buffer_buf_readfloatle_offset">buf.readFloatLE(offset)</a></li> <li><a href="#buffer_buf_readint8_offset">buf.readInt8(offset)</a></li> <li><a href="#buffer_buf_readint16be_offset">buf.readInt16BE(offset)</a></li> <li><a href="#buffer_buf_readint16le_offset">buf.readInt16LE(offset)</a></li> <li><a href="#buffer_buf_readint32be_offset">buf.readInt32BE(offset)</a></li> <li><a href="#buffer_buf_readint32le_offset">buf.readInt32LE(offset)</a></li> <li><a href="#buffer_buf_readintbe_offset_bytelength">buf.readIntBE(offset, byteLength)</a></li> <li><a href="#buffer_buf_readintle_offset_bytelength">buf.readIntLE(offset, byteLength)</a></li> <li><a href="#buffer_buf_readuint8_offset">buf.readUInt8(offset)</a></li> <li><a href="#buffer_buf_readuint16be_offset">buf.readUInt16BE(offset)</a></li> <li><a href="#buffer_buf_readuint16le_offset">buf.readUInt16LE(offset)</a></li> <li><a href="#buffer_buf_readuint32be_offset">buf.readUInt32BE(offset)</a></li> <li><a href="#buffer_buf_readuint32le_offset">buf.readUInt32LE(offset)</a></li> <li><a href="#buffer_buf_readuintbe_offset_bytelength">buf.readUIntBE(offset, byteLength)</a></li> <li><a href="#buffer_buf_readuintle_offset_bytelength">buf.readUIntLE(offset, byteLength)</a></li> <li><a href="#buffer_buf_slice_start_end">buf.slice([start[, end]])</a></li> <li><a href="#buffer_buf_swap16">buf.swap16()</a></li> <li><a href="#buffer_buf_swap32">buf.swap32()</a></li> <li><a href="#buffer_buf_swap64">buf.swap64()</a></li> <li><a href="#buffer_buf_tojson">buf.toJSON()</a></li> <li><a href="#buffer_buf_tostring_encoding_start_end">buf.toString([encoding[, start[, end]]])</a></li> <li><a href="#buffer_buf_values">buf.values()</a></li> <li><a href="#buffer_buf_write_string_offset_length_encoding">buf.write(string[, offset[, length]][, encoding])</a></li> <li><a href="#buffer_buf_writebigint64be_value_offset">buf.writeBigInt64BE(value, offset)</a></li> <li><a href="#buffer_buf_writebigint64le_value_offset">buf.writeBigInt64LE(value, offset)</a></li> <li><a href="#buffer_buf_writebiguint64be_value_offset">buf.writeBigUInt64BE(value, offset)</a></li> <li><a href="#buffer_buf_writebiguint64le_value_offset">buf.writeBigUInt64LE(value, offset)</a></li> <li><a href="#buffer_buf_writedoublebe_value_offset">buf.writeDoubleBE(value, offset)</a></li> <li><a href="#buffer_buf_writedoublele_value_offset">buf.writeDoubleLE(value, offset)</a></li> <li><a href="#buffer_buf_writefloatbe_value_offset">buf.writeFloatBE(value, offset)</a></li> <li><a href="#buffer_buf_writefloatle_value_offset">buf.writeFloatLE(value, offset)</a></li> <li><a href="#buffer_buf_writeint8_value_offset">buf.writeInt8(value, offset)</a></li> <li><a href="#buffer_buf_writeint16be_value_offset">buf.writeInt16BE(value, offset)</a></li> <li><a href="#buffer_buf_writeint16le_value_offset">buf.writeInt16LE(value, offset)</a></li> <li><a href="#buffer_buf_writeint32be_value_offset">buf.writeInt32BE(value, offset)</a></li> <li><a href="#buffer_buf_writeint32le_value_offset">buf.writeInt32LE(value, offset)</a></li> <li><a href="#buffer_buf_writeintbe_value_offset_bytelength">buf.writeIntBE(value, offset, byteLength)</a></li> <li><a href="#buffer_buf_writeintle_value_offset_bytelength">buf.writeIntLE(value, offset, byteLength)</a></li> <li><a href="#buffer_buf_writeuint8_value_offset">buf.writeUInt8(value, offset)</a></li> <li><a href="#buffer_buf_writeuint16be_value_offset">buf.writeUInt16BE(value, offset)</a></li> <li><a href="#buffer_buf_writeuint16le_value_offset">buf.writeUInt16LE(value, offset)</a></li> <li><a href="#buffer_buf_writeuint32be_value_offset">buf.writeUInt32BE(value, offset)</a></li> <li><a href="#buffer_buf_writeuint32le_value_offset">buf.writeUInt32LE(value, offset)</a></li> <li><a href="#buffer_buf_writeuintbe_value_offset_bytelength">buf.writeUIntBE(value, offset, byteLength)</a></li> <li><a href="#buffer_buf_writeuintle_value_offset_bytelength">buf.writeUIntLE(value, offset, byteLength)</a></li> </ul> </li> <li><a href="#buffer_buffer_inspect_max_bytes">buffer.INSPECT_MAX_BYTES</a></li> <li><a href="#buffer_buffer_kmaxlength">buffer.kMaxLength</a></li> <li><a href="#buffer_buffer_transcode_source_fromenc_toenc">buffer.transcode(source, fromEnc, toEnc)</a></li> <li> <p><span class="stability_0"><a href="#buffer_class_slowbuffer">Class: SlowBuffer</a></span></p> <ul> <li><span class="stability_0"><a href="#buffer_new_slowbuffer_size">new SlowBuffer(size)</a></span></li> </ul> </li> <li> <p><a href="#buffer_buffer_constants">Buffer Constants</a></p> <ul> <li><a href="#buffer_buffer_constants_max_length">buffer.constants.MAX_LENGTH</a></li> <li><a href="#buffer_buffer_constants_max_string_length">buffer.constants.MAX_STRING_LENGTH</a></li> </ul> </li> </ul> </li> <li> <p><a href="#addons_c_addons">C++ Addons</a></p> <ul> <li> <p><a href="#addons_hello_world">Hello world</a></p> <ul> <li><a href="#addons_context_aware_addons">Context-aware addons</a></li> <li><a href="#addons_building">Building</a></li> <li><a href="#addons_linking_to_node_js_own_dependencies">Linking to Node.js' own dependencies</a></li> <li><a href="#addons_loading_addons_using_require">Loading Addons using require()</a></li> </ul> </li> <li><a href="#addons_native_abstractions_for_node_js">Native Abstractions for Node.js</a></li> <li><a href="#addons_n_api">N-API</a></li> <li> <p><a href="#addons_addon_examples">Addon examples</a></p> <ul> <li><a href="#addons_function_arguments">Function arguments</a></li> <li><a href="#addons_callbacks">Callbacks</a></li> <li><a href="#addons_object_factory">Object factory</a></li> <li><a href="#addons_function_factory">Function factory</a></li> <li><a href="#addons_wrapping_c_objects">Wrapping C++ objects</a></li> <li><a href="#addons_factory_of_wrapped_objects">Factory of wrapped objects</a></li> <li><a href="#addons_passing_wrapped_objects_around">Passing wrapped objects around</a></li> <li> <p><a href="#addons_atexit_hooks">AtExit hooks</a></p> <ul> <li><a href="#addons_void_atexit_callback_args">void AtExit(callback, args)</a></li> </ul> </li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#n_api_n_api">N-API</a></span></p> <ul> <li><a href="#n_api_implications_of_abi_stability">Implications of ABI Stability</a></li> <li><a href="#n_api_usage">Usage</a></li> <li><a href="#n_api_n_api_version_matrix">N-API Version Matrix</a></li> <li> <p><a href="#n_api_environment_life_cycle_apis">Environment Life Cycle APIs</a></p> <ul> <li><a href="#n_api_napi_set_instance_data">napi_set_instance_data</a></li> <li><a href="#n_api_napi_get_instance_data">napi_get_instance_data</a></li> </ul> </li> <li> <p><a href="#n_api_basic_n_api_data_types">Basic N-API Data Types</a></p> <ul> <li><a href="#n_api_napi_status">napi_status</a></li> <li><a href="#n_api_napi_extended_error_info">napi_extended_error_info</a></li> <li><a href="#n_api_napi_env">napi_env</a></li> <li><a href="#n_api_napi_value">napi_value</a></li> <li><a href="#n_api_napi_threadsafe_function">napi_threadsafe_function</a></li> <li><a href="#n_api_napi_threadsafe_function_release_mode">napi_threadsafe_function_release_mode</a></li> <li><a href="#n_api_napi_threadsafe_function_call_mode">napi_threadsafe_function_call_mode</a></li> <li> <p><a href="#n_api_n_api_memory_management_types">N-API Memory Management types</a></p> <ul> <li><a href="#n_api_napi_handle_scope">napi_handle_scope</a></li> <li><a href="#n_api_napi_escapable_handle_scope">napi_escapable_handle_scope</a></li> <li><a href="#n_api_napi_ref">napi_ref</a></li> </ul> </li> <li> <p><a href="#n_api_n_api_callback_types">N-API Callback types</a></p> <ul> <li><a href="#n_api_napi_callback_info">napi_callback_info</a></li> <li><a href="#n_api_napi_callback">napi_callback</a></li> <li><a href="#n_api_napi_finalize">napi_finalize</a></li> <li><a href="#n_api_napi_async_execute_callback">napi_async_execute_callback</a></li> <li><a href="#n_api_napi_async_complete_callback">napi_async_complete_callback</a></li> <li><a href="#n_api_napi_threadsafe_function_call_js">napi_threadsafe_function_call_js</a></li> </ul> </li> </ul> </li> <li> <p><a href="#n_api_error_handling">Error Handling</a></p> <ul> <li> <p><a href="#n_api_return_values">Return values</a></p> <ul> <li><a href="#n_api_napi_get_last_error_info">napi_get_last_error_info</a></li> </ul> </li> <li> <p><a href="#n_api_exceptions">Exceptions</a></p> <ul> <li><a href="#n_api_napi_throw">napi_throw</a></li> <li><a href="#n_api_napi_throw_error">napi_throw_error</a></li> <li><a href="#n_api_napi_throw_type_error">napi_throw_type_error</a></li> <li><a href="#n_api_napi_throw_range_error">napi_throw_range_error</a></li> <li><a href="#n_api_napi_is_error">napi_is_error</a></li> <li><a href="#n_api_napi_create_error">napi_create_error</a></li> <li><a href="#n_api_napi_create_type_error">napi_create_type_error</a></li> <li><a href="#n_api_napi_create_range_error">napi_create_range_error</a></li> <li><a href="#n_api_napi_get_and_clear_last_exception">napi_get_and_clear_last_exception</a></li> <li><a href="#n_api_napi_is_exception_pending">napi_is_exception_pending</a></li> <li><a href="#n_api_napi_fatal_exception">napi_fatal_exception</a></li> </ul> </li> <li> <p><a href="#n_api_fatal_errors">Fatal Errors</a></p> <ul> <li><a href="#n_api_napi_fatal_error">napi_fatal_error</a></li> </ul> </li> </ul> </li> <li> <p><a href="#n_api_object_lifetime_management">Object Lifetime management</a></p> <ul> <li> <p><a href="#n_api_making_handle_lifespan_shorter_than_that_of_the_native_method">Making handle lifespan shorter than that of the native method</a></p> <ul> <li><a href="#n_api_napi_open_handle_scope">napi_open_handle_scope</a></li> <li><a href="#n_api_napi_close_handle_scope">napi_close_handle_scope</a></li> <li><a href="#n_api_napi_open_escapable_handle_scope">napi_open_escapable_handle_scope</a></li> <li><a href="#n_api_napi_close_escapable_handle_scope">napi_close_escapable_handle_scope</a></li> <li><a href="#n_api_napi_escape_handle">napi_escape_handle</a></li> </ul> </li> <li> <p><a href="#n_api_references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method">References to objects with a lifespan longer than that of the native method</a></p> <ul> <li><a href="#n_api_napi_create_reference">napi_create_reference</a></li> <li><a href="#n_api_napi_delete_reference">napi_delete_reference</a></li> <li><a href="#n_api_napi_reference_ref">napi_reference_ref</a></li> <li><a href="#n_api_napi_reference_unref">napi_reference_unref</a></li> <li><a href="#n_api_napi_get_reference_value">napi_get_reference_value</a></li> </ul> </li> <li> <p><a href="#n_api_cleanup_on_exit_of_the_current_node_js_instance">Cleanup on exit of the current Node.js instance</a></p> <ul> <li><a href="#n_api_napi_add_env_cleanup_hook">napi_add_env_cleanup_hook</a></li> <li><a href="#n_api_napi_remove_env_cleanup_hook">napi_remove_env_cleanup_hook</a></li> </ul> </li> </ul> </li> <li><a href="#n_api_module_registration">Module registration</a></li> <li> <p><a href="#n_api_working_with_javascript_values">Working with JavaScript Values</a></p> <ul> <li> <p><a href="#n_api_enum_types">Enum types</a></p> <ul> <li><a href="#n_api_napi_key_collection_mode">napi_key_collection_mode</a></li> <li><a href="#n_api_napi_key_filter">napi_key_filter</a></li> <li><a href="#n_api_napi_key_conversion">napi_key_conversion</a></li> <li><a href="#n_api_napi_valuetype">napi_valuetype</a></li> <li><a href="#n_api_napi_typedarray_type">napi_typedarray_type</a></li> </ul> </li> <li> <p><a href="#n_api_object_creation_functions">Object Creation Functions</a></p> <ul> <li><a href="#n_api_napi_create_array">napi_create_array</a></li> <li><a href="#n_api_napi_create_array_with_length">napi_create_array_with_length</a></li> <li><a href="#n_api_napi_create_arraybuffer">napi_create_arraybuffer</a></li> <li><a href="#n_api_napi_create_buffer">napi_create_buffer</a></li> <li><a href="#n_api_napi_create_buffer_copy">napi_create_buffer_copy</a></li> <li><a href="#n_api_napi_create_date">napi_create_date</a></li> <li><a href="#n_api_napi_create_external">napi_create_external</a></li> <li><a href="#n_api_napi_create_external_arraybuffer">napi_create_external_arraybuffer</a></li> <li><a href="#n_api_napi_create_external_buffer">napi_create_external_buffer</a></li> <li><a href="#n_api_napi_create_object">napi_create_object</a></li> <li><a href="#n_api_napi_create_symbol">napi_create_symbol</a></li> <li><a href="#n_api_napi_create_typedarray">napi_create_typedarray</a></li> <li><a href="#n_api_napi_create_dataview">napi_create_dataview</a></li> </ul> </li> <li> <p><a href="#n_api_functions_to_convert_from_c_types_to_n_api">Functions to convert from C types to N-API</a></p> <ul> <li><a href="#n_api_napi_create_int32">napi_create_int32</a></li> <li><a href="#n_api_napi_create_uint32">napi_create_uint32</a></li> <li><a href="#n_api_napi_create_int64">napi_create_int64</a></li> <li><a href="#n_api_napi_create_double">napi_create_double</a></li> <li><a href="#n_api_napi_create_bigint_int64">napi_create_bigint_int64</a></li> <li><a href="#n_api_napi_create_bigint_uint64">napi_create_bigint_uint64</a></li> <li><a href="#n_api_napi_create_bigint_words">napi_create_bigint_words</a></li> <li><a href="#n_api_napi_create_string_latin1">napi_create_string_latin1</a></li> <li><a href="#n_api_napi_create_string_utf16">napi_create_string_utf16</a></li> <li><a href="#n_api_napi_create_string_utf8">napi_create_string_utf8</a></li> </ul> </li> <li> <p><a href="#n_api_functions_to_convert_from_n_api_to_c_types">Functions to convert from N-API to C types</a></p> <ul> <li><a href="#n_api_napi_get_array_length">napi_get_array_length</a></li> <li><a href="#n_api_napi_get_arraybuffer_info">napi_get_arraybuffer_info</a></li> <li><a href="#n_api_napi_get_buffer_info">napi_get_buffer_info</a></li> <li><a href="#n_api_napi_get_prototype">napi_get_prototype</a></li> <li><a href="#n_api_napi_get_typedarray_info">napi_get_typedarray_info</a></li> <li><a href="#n_api_napi_get_dataview_info">napi_get_dataview_info</a></li> <li><a href="#n_api_napi_get_date_value">napi_get_date_value</a></li> <li><a href="#n_api_napi_get_value_bool">napi_get_value_bool</a></li> <li><a href="#n_api_napi_get_value_double">napi_get_value_double</a></li> <li><a href="#n_api_napi_get_value_bigint_int64">napi_get_value_bigint_int64</a></li> <li><a href="#n_api_napi_get_value_bigint_uint64">napi_get_value_bigint_uint64</a></li> <li><a href="#n_api_napi_get_value_bigint_words">napi_get_value_bigint_words</a></li> <li><a href="#n_api_napi_get_value_external">napi_get_value_external</a></li> <li><a href="#n_api_napi_get_value_int32">napi_get_value_int32</a></li> <li><a href="#n_api_napi_get_value_int64">napi_get_value_int64</a></li> <li><a href="#n_api_napi_get_value_string_latin1">napi_get_value_string_latin1</a></li> <li><a href="#n_api_napi_get_value_string_utf8">napi_get_value_string_utf8</a></li> <li><a href="#n_api_napi_get_value_string_utf16">napi_get_value_string_utf16</a></li> <li><a href="#n_api_napi_get_value_uint32">napi_get_value_uint32</a></li> </ul> </li> <li> <p><a href="#n_api_functions_to_get_global_instances">Functions to get global instances</a></p> <ul> <li><a href="#n_api_napi_get_boolean">napi_get_boolean</a></li> <li><a href="#n_api_napi_get_global">napi_get_global</a></li> <li><a href="#n_api_napi_get_null">napi_get_null</a></li> <li><a href="#n_api_napi_get_undefined">napi_get_undefined</a></li> </ul> </li> </ul> </li> <li> <p><a href="#n_api_working_with_javascript_values_abstract_operations">Working with JavaScript Values - Abstract Operations</a></p> <ul> <li><a href="#n_api_napi_coerce_to_bool">napi_coerce_to_bool</a></li> <li><a href="#n_api_napi_coerce_to_number">napi_coerce_to_number</a></li> <li><a href="#n_api_napi_coerce_to_object">napi_coerce_to_object</a></li> <li><a href="#n_api_napi_coerce_to_string">napi_coerce_to_string</a></li> <li><a href="#n_api_napi_typeof">napi_typeof</a></li> <li><a href="#n_api_napi_instanceof">napi_instanceof</a></li> <li><a href="#n_api_napi_is_array">napi_is_array</a></li> <li><a href="#n_api_napi_is_arraybuffer">napi_is_arraybuffer</a></li> <li><a href="#n_api_napi_is_buffer">napi_is_buffer</a></li> <li><a href="#n_api_napi_is_date">napi_is_date</a></li> <li><a href="#n_api_napi_is_error_1">napi_is_error</a></li> <li><a href="#n_api_napi_is_typedarray">napi_is_typedarray</a></li> <li><a href="#n_api_napi_is_dataview">napi_is_dataview</a></li> <li><a href="#n_api_napi_strict_equals">napi_strict_equals</a></li> <li><a href="#n_api_napi_detach_arraybuffer">napi_detach_arraybuffer</a></li> <li><a href="#n_api_napi_is_detached_arraybuffer">napi_is_detached_arraybuffer</a></li> </ul> </li> <li> <p><a href="#n_api_working_with_javascript_properties">Working with JavaScript Properties</a></p> <ul> <li> <p><a href="#n_api_structures">Structures</a></p> <ul> <li><a href="#n_api_napi_property_attributes">napi_property_attributes</a></li> <li><a href="#n_api_napi_property_descriptor">napi_property_descriptor</a></li> </ul> </li> <li> <p><a href="#n_api_functions">Functions</a></p> <ul> <li><a href="#n_api_napi_get_property_names">napi_get_property_names</a></li> <li><a href="#n_api_napi_get_all_property_names">napi_get_all_property_names</a></li> <li><a href="#n_api_napi_set_property">napi_set_property</a></li> <li><a href="#n_api_napi_get_property">napi_get_property</a></li> <li><a href="#n_api_napi_has_property">napi_has_property</a></li> <li><a href="#n_api_napi_delete_property">napi_delete_property</a></li> <li><a href="#n_api_napi_has_own_property">napi_has_own_property</a></li> <li><a href="#n_api_napi_set_named_property">napi_set_named_property</a></li> <li><a href="#n_api_napi_get_named_property">napi_get_named_property</a></li> <li><a href="#n_api_napi_has_named_property">napi_has_named_property</a></li> <li><a href="#n_api_napi_set_element">napi_set_element</a></li> <li><a href="#n_api_napi_get_element">napi_get_element</a></li> <li><a href="#n_api_napi_has_element">napi_has_element</a></li> <li><a href="#n_api_napi_delete_element">napi_delete_element</a></li> <li><a href="#n_api_napi_define_properties">napi_define_properties</a></li> </ul> </li> </ul> </li> <li> <p><a href="#n_api_working_with_javascript_functions">Working with JavaScript Functions</a></p> <ul> <li><a href="#n_api_napi_call_function">napi_call_function</a></li> <li><a href="#n_api_napi_create_function">napi_create_function</a></li> <li><a href="#n_api_napi_get_cb_info">napi_get_cb_info</a></li> <li><a href="#n_api_napi_get_new_target">napi_get_new_target</a></li> <li><a href="#n_api_napi_new_instance">napi_new_instance</a></li> </ul> </li> <li> <p><a href="#n_api_object_wrap">Object Wrap</a></p> <ul> <li><a href="#n_api_napi_define_class">napi_define_class</a></li> <li><a href="#n_api_napi_wrap">napi_wrap</a></li> <li><a href="#n_api_napi_unwrap">napi_unwrap</a></li> <li><a href="#n_api_napi_remove_wrap">napi_remove_wrap</a></li> <li><a href="#n_api_napi_add_finalizer">napi_add_finalizer</a></li> </ul> </li> <li> <p><a href="#n_api_simple_asynchronous_operations">Simple Asynchronous Operations</a></p> <ul> <li><a href="#n_api_napi_create_async_work">napi_create_async_work</a></li> <li><a href="#n_api_napi_delete_async_work">napi_delete_async_work</a></li> <li><a href="#n_api_napi_queue_async_work">napi_queue_async_work</a></li> <li><a href="#n_api_napi_cancel_async_work">napi_cancel_async_work</a></li> </ul> </li> <li> <p><a href="#n_api_custom_asynchronous_operations">Custom Asynchronous Operations</a></p> <ul> <li><a href="#n_api_napi_async_init">napi_async_init</a></li> <li><a href="#n_api_napi_async_destroy">napi_async_destroy</a></li> <li><a href="#n_api_napi_make_callback">napi_make_callback</a></li> <li><a href="#n_api_napi_open_callback_scope">napi_open_callback_scope</a></li> <li><a href="#n_api_napi_close_callback_scope">napi_close_callback_scope</a></li> </ul> </li> <li> <p><a href="#n_api_version_management">Version Management</a></p> <ul> <li><a href="#n_api_napi_get_node_version">napi_get_node_version</a></li> <li><a href="#n_api_napi_get_version">napi_get_version</a></li> </ul> </li> <li> <p><a href="#n_api_memory_management">Memory Management</a></p> <ul> <li><a href="#n_api_napi_adjust_external_memory">napi_adjust_external_memory</a></li> </ul> </li> <li> <p><a href="#n_api_promises">Promises</a></p> <ul> <li><a href="#n_api_napi_create_promise">napi_create_promise</a></li> <li><a href="#n_api_napi_resolve_deferred">napi_resolve_deferred</a></li> <li><a href="#n_api_napi_reject_deferred">napi_reject_deferred</a></li> <li><a href="#n_api_napi_is_promise">napi_is_promise</a></li> </ul> </li> <li> <p><a href="#n_api_script_execution">Script execution</a></p> <ul> <li><a href="#n_api_napi_run_script">napi_run_script</a></li> </ul> </li> <li> <p><a href="#n_api_libuv_event_loop">libuv event loop</a></p> <ul> <li><a href="#n_api_napi_get_uv_event_loop">napi_get_uv_event_loop</a></li> </ul> </li> <li> <p><a href="#n_api_asynchronous_thread_safe_function_calls">Asynchronous Thread-safe Function Calls</a></p> <ul> <li><a href="#n_api_napi_create_threadsafe_function">napi_create_threadsafe_function</a></li> <li><a href="#n_api_napi_get_threadsafe_function_context">napi_get_threadsafe_function_context</a></li> <li><a href="#n_api_napi_call_threadsafe_function">napi_call_threadsafe_function</a></li> <li><a href="#n_api_napi_acquire_threadsafe_function">napi_acquire_threadsafe_function</a></li> <li><a href="#n_api_napi_release_threadsafe_function">napi_release_threadsafe_function</a></li> <li><a href="#n_api_napi_ref_threadsafe_function">napi_ref_threadsafe_function</a></li> <li><a href="#n_api_napi_unref_threadsafe_function">napi_unref_threadsafe_function</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#child_process_child_process">Child Process</a></span></p> <ul> <li> <p><a href="#child_process_asynchronous_process_creation">Asynchronous Process Creation</a></p> <ul> <li><a href="#child_process_spawning_bat_and_cmd_files_on_windows">Spawning <code>.bat</code> and <code>.cmd</code> files on Windows</a></li> <li><a href="#child_process_child_process_exec_command_options_callback">child_process.exec(command[, options][, callback])</a></li> <li><a href="#child_process_child_process_execfile_file_args_options_callback">child_process.execFile(file[, args][, options][, callback])</a></li> <li><a href="#child_process_child_process_fork_modulepath_args_options">child_process.fork(modulePath[, args][, options])</a></li> <li> <p><a href="#child_process_child_process_spawn_command_args_options">child_process.spawn(command[, args][, options])</a></p> <ul> <li><a href="#child_process_options_detached">options.detached</a></li> <li><a href="#child_process_options_stdio">options.stdio</a></li> </ul> </li> </ul> </li> <li> <p><a href="#child_process_synchronous_process_creation">Synchronous Process Creation</a></p> <ul> <li><a href="#child_process_child_process_execfilesync_file_args_options">child_process.execFileSync(file[, args][, options])</a></li> <li><a href="#child_process_child_process_execsync_command_options">child_process.execSync(command[, options])</a></li> <li><a href="#child_process_child_process_spawnsync_command_args_options">child_process.spawnSync(command[, args][, options])</a></li> </ul> </li> <li> <p><a href="#child_process_class_childprocess">Class: ChildProcess</a></p> <ul> <li><a href="#child_process_event_close">Event: 'close'</a></li> <li><a href="#child_process_event_disconnect">Event: 'disconnect'</a></li> <li><a href="#child_process_event_error">Event: 'error'</a></li> <li><a href="#child_process_event_exit">Event: 'exit'</a></li> <li><a href="#child_process_event_message">Event: 'message'</a></li> <li><a href="#child_process_subprocess_channel">subprocess.channel</a></li> <li><a href="#child_process_subprocess_connected">subprocess.connected</a></li> <li><a href="#child_process_subprocess_disconnect">subprocess.disconnect()</a></li> <li><a href="#child_process_subprocess_kill_signal">subprocess.kill([signal])</a></li> <li><a href="#child_process_subprocess_killed">subprocess.killed</a></li> <li><a href="#child_process_subprocess_pid">subprocess.pid</a></li> <li><a href="#child_process_subprocess_ref">subprocess.ref()</a></li> <li> <p><a href="#child_process_subprocess_send_message_sendhandle_options_callback">subprocess.send(message[, sendHandle[, options]][, callback])</a></p> <ul> <li><a href="#child_process_example_sending_a_server_object">Example: sending a server object</a></li> <li><a href="#child_process_example_sending_a_socket_object">Example: sending a socket object</a></li> </ul> </li> <li><a href="#child_process_subprocess_stderr">subprocess.stderr</a></li> <li><a href="#child_process_subprocess_stdin">subprocess.stdin</a></li> <li><a href="#child_process_subprocess_stdio">subprocess.stdio</a></li> <li><a href="#child_process_subprocess_stdout">subprocess.stdout</a></li> <li><a href="#child_process_subprocess_unref">subprocess.unref()</a></li> </ul> </li> <li><a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a></li> <li><a href="#child_process_shell_requirements">Shell Requirements</a></li> <li><a href="#child_process_default_windows_shell">Default Windows Shell</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#cluster_cluster">Cluster</a></span></p> <ul> <li><a href="#cluster_how_it_works">How It Works</a></li> <li> <p><a href="#cluster_class_worker">Class: Worker</a></p> <ul> <li><a href="#cluster_event_disconnect">Event: 'disconnect'</a></li> <li><a href="#cluster_event_error">Event: 'error'</a></li> <li><a href="#cluster_event_exit">Event: 'exit'</a></li> <li><a href="#cluster_event_listening">Event: 'listening'</a></li> <li><a href="#cluster_event_message">Event: 'message'</a></li> <li><a href="#cluster_event_online">Event: 'online'</a></li> <li><a href="#cluster_worker_disconnect">worker.disconnect()</a></li> <li><a href="#cluster_worker_exitedafterdisconnect">worker.exitedAfterDisconnect</a></li> <li><a href="#cluster_worker_id">worker.id</a></li> <li><a href="#cluster_worker_isconnected">worker.isConnected()</a></li> <li><a href="#cluster_worker_isdead">worker.isDead()</a></li> <li><a href="#cluster_worker_kill_signal_sigterm">worker.kill([signal='SIGTERM'])</a></li> <li><a href="#cluster_worker_process">worker.process</a></li> <li><a href="#cluster_worker_send_message_sendhandle_callback">worker.send(message[, sendHandle][, callback])</a></li> </ul> </li> <li><a href="#cluster_event_disconnect_1">Event: 'disconnect'</a></li> <li><a href="#cluster_event_exit_1">Event: 'exit'</a></li> <li><a href="#cluster_event_fork">Event: 'fork'</a></li> <li><a href="#cluster_event_listening_1">Event: 'listening'</a></li> <li><a href="#cluster_event_message_1">Event: 'message'</a></li> <li><a href="#cluster_event_online_1">Event: 'online'</a></li> <li><a href="#cluster_event_setup">Event: 'setup'</a></li> <li><a href="#cluster_cluster_disconnect_callback">cluster.disconnect([callback])</a></li> <li><a href="#cluster_cluster_fork_env">cluster.fork([env])</a></li> <li><a href="#cluster_cluster_ismaster">cluster.isMaster</a></li> <li><a href="#cluster_cluster_isworker">cluster.isWorker</a></li> <li><a href="#cluster_cluster_schedulingpolicy">cluster.schedulingPolicy</a></li> <li><a href="#cluster_cluster_settings">cluster.settings</a></li> <li><a href="#cluster_cluster_setupmaster_settings">cluster.setupMaster([settings])</a></li> <li><a href="#cluster_cluster_worker">cluster.worker</a></li> <li><a href="#cluster_cluster_workers">cluster.workers</a></li> </ul> </li> <li> <p><a href="#cli_command_line_options">Command Line Options</a></p> <ul> <li><a href="#cli_synopsis">Synopsis</a></li> <li> <p><a href="#cli_options">Options</a></p> <ul> <li><a href="#cli"><code>-</code></a></li> <li><a href="#cli_1"><code>--</code></a></li> <li><a href="#cli_abort_on_uncaught_exception"><code>--abort-on-uncaught-exception</code></a></li> <li><a href="#cli_completion_bash"><code>--completion-bash</code></a></li> <li><a href="#cli_enable_fips"><code>--enable-fips</code></a></li> <li><a href="#cli_experimental_modules"><code>--experimental-modules</code></a></li> <li><a href="#cli_experimental_repl_await"><code>--experimental-repl-await</code></a></li> <li><a href="#cli_experimental_vm_modules"><code>--experimental-vm-modules</code></a></li> <li><a href="#cli_experimental_worker"><code>--experimental-worker</code></a></li> <li><a href="#cli_force_fips"><code>--force-fips</code></a></li> <li><a href="#cli_icu_data_dir_file"><code>--icu-data-dir=file</code></a></li> <li><a href="#cli_inspect_brk_host_port"><code>--inspect-brk[=[host:]port]</code></a></li> <li><a href="#cli_inspect_port_host_port"><code>--inspect-port=[host:]port</code></a></li> <li> <p><a href="#cli_inspect_host_port"><code>--inspect[=[host:]port]</code></a></p> <ul> <li><a href="#cli_warning_binding_inspector_to_a_public_ip_port_combination_is_insecure">Warning: binding inspector to a public IP:port combination is insecure</a></li> </ul> </li> <li><a href="#cli_loader_file"><code>--loader=file</code></a></li> <li><a href="#cli_insecure_http_parser"><code>--insecure-http-parser</code></a></li> <li><a href="#cli_max_http_header_size_size"><code>--max-http-header-size=size</code></a></li> <li><a href="#cli_napi_modules"><code>--napi-modules</code></a></li> <li><a href="#cli_no_deprecation"><code>--no-deprecation</code></a></li> <li><a href="#cli_no_force_async_hooks_checks"><code>--no-force-async-hooks-checks</code></a></li> <li><a href="#cli_no_warnings"><code>--no-warnings</code></a></li> <li><a href="#cli_openssl_config_file"><code>--openssl-config=file</code></a></li> <li><a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a></li> <li><a href="#cli_preserve_symlinks"><code>--preserve-symlinks</code></a></li> <li><a href="#cli_preserve_symlinks_main"><code>--preserve-symlinks-main</code></a></li> <li><a href="#cli_prof"><code>--prof</code></a></li> <li><a href="#cli_prof_process"><code>--prof-process</code></a></li> <li><a href="#cli_redirect_warnings_file"><code>--redirect-warnings=file</code></a></li> <li><a href="#cli_throw_deprecation"><code>--throw-deprecation</code></a></li> <li><a href="#cli_title_title"><code>--title=title</code></a></li> <li><a href="#cli_tls_cipher_list_list"><code>--tls-cipher-list=list</code></a></li> <li><a href="#cli_tls_max_v1_2"><code>--tls-max-v1.2</code></a></li> <li><a href="#cli_tls_min_v1_0"><code>--tls-min-v1.0</code></a></li> <li><a href="#cli_tls_min_v1_1"><code>--tls-min-v1.1</code></a></li> <li><a href="#cli_tls_min_v1_2"><code>--tls-min-v1.2</code></a></li> <li><a href="#cli_trace_deprecation"><code>--trace-deprecation</code></a></li> <li><a href="#cli_trace_event_categories"><code>--trace-event-categories</code></a></li> <li><a href="#cli_trace_event_file_pattern"><code>--trace-event-file-pattern</code></a></li> <li><a href="#cli_trace_events_enabled"><code>--trace-events-enabled</code></a></li> <li><a href="#cli_trace_sync_io"><code>--trace-sync-io</code></a></li> <li><a href="#cli_trace_warnings"><code>--trace-warnings</code></a></li> <li><a href="#cli_track_heap_objects"><code>--track-heap-objects</code></a></li> <li><a href="#cli_unhandled_rejections_mode"><code>--unhandled-rejections=mode</code></a></li> <li><a href="#cli_use_bundled_ca_use_openssl_ca"><code>--use-bundled-ca</code>, <code>--use-openssl-ca</code></a></li> <li><a href="#cli_v8_options"><code>--v8-options</code></a></li> <li><a href="#cli_v8_pool_size_num"><code>--v8-pool-size=num</code></a></li> <li><a href="#cli_zero_fill_buffers"><code>--zero-fill-buffers</code></a></li> <li><a href="#cli_c_check"><code>-c</code>, <code>--check</code></a></li> <li><a href="#cli_e_eval_script"><code>-e</code>, <code>--eval "script"</code></a></li> <li><a href="#cli_h_help"><code>-h</code>, <code>--help</code></a></li> <li><a href="#cli_i_interactive"><code>-i</code>, <code>--interactive</code></a></li> <li><a href="#cli_p_print_script"><code>-p</code>, <code>--print "script"</code></a></li> <li><a href="#cli_r_require_module"><code>-r</code>, <code>--require module</code></a></li> <li><a href="#cli_v_version"><code>-v</code>, <code>--version</code></a></li> </ul> </li> <li> <p><a href="#cli_environment_variables">Environment Variables</a></p> <ul> <li><a href="#cli_node_debug_module"><code>NODE_DEBUG=module[,…]</code></a></li> <li><a href="#cli_node_debug_native_module"><code>NODE_DEBUG_NATIVE=module[,…]</code></a></li> <li><a href="#cli_node_disable_colors_1"><code>NODE_DISABLE_COLORS=1</code></a></li> <li><a href="#cli_node_extra_ca_certs_file"><code>NODE_EXTRA_CA_CERTS=file</code></a></li> <li><a href="#cli_node_icu_data_file"><code>NODE_ICU_DATA=file</code></a></li> <li><a href="#cli_node_no_warnings_1"><code>NODE_NO_WARNINGS=1</code></a></li> <li><a href="#cli_node_options_options"><code>NODE_OPTIONS=options...</code></a></li> <li><a href="#cli_node_path_path"><code>NODE_PATH=path[:…]</code></a></li> <li><a href="#cli_node_pending_deprecation_1"><code>NODE_PENDING_DEPRECATION=1</code></a></li> <li><a href="#cli_node_preserve_symlinks_1"><code>NODE_PRESERVE_SYMLINKS=1</code></a></li> <li><a href="#cli_node_redirect_warnings_file"><code>NODE_REDIRECT_WARNINGS=file</code></a></li> <li><a href="#cli_node_repl_history_file"><code>NODE_REPL_HISTORY=file</code></a></li> <li><a href="#cli_node_tls_reject_unauthorized_value"><code>NODE_TLS_REJECT_UNAUTHORIZED=value</code></a></li> <li><a href="#cli_node_v8_coverage_dir"><code>NODE_V8_COVERAGE=dir</code></a></li> <li><a href="#cli_openssl_conf_file"><code>OPENSSL_CONF=file</code></a></li> <li><a href="#cli_ssl_cert_dir_dir"><code>SSL_CERT_DIR=dir</code></a></li> <li><a href="#cli_ssl_cert_file_file"><code>SSL_CERT_FILE=file</code></a></li> <li><a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE=size</code></a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#console_console">Console</a></span></p> <ul> <li> <p><a href="#console_class_console">Class: Console</a></p> <ul> <li><a href="#console_new_console_stdout_stderr_ignoreerrors">new Console(stdout[, stderr][, ignoreErrors])</a></li> <li><a href="#console_new_console_options">new Console(options)</a></li> <li><a href="#console_console_assert_value_message">console.assert(value[, ...message])</a></li> <li><a href="#console_console_clear">console.clear()</a></li> <li><a href="#console_console_count_label">console.count([label])</a></li> <li><a href="#console_console_countreset_label">console.countReset([label])</a></li> <li><a href="#console_console_debug_data_args">console.debug(data[, ...args])</a></li> <li><a href="#console_console_dir_obj_options">console.dir(obj[, options])</a></li> <li><a href="#console_console_dirxml_data">console.dirxml(...data)</a></li> <li><a href="#console_console_error_data_args">console.error([data][, ...args])</a></li> <li><a href="#console_console_group_label">console.group([...label])</a></li> <li><a href="#console_console_groupcollapsed">console.groupCollapsed()</a></li> <li><a href="#console_console_groupend">console.groupEnd()</a></li> <li><a href="#console_console_info_data_args">console.info([data][, ...args])</a></li> <li><a href="#console_console_log_data_args">console.log([data][, ...args])</a></li> <li><a href="#console_console_table_tabulardata_properties">console.table(tabularData[, properties])</a></li> <li><a href="#console_console_time_label">console.time([label])</a></li> <li><a href="#console_console_timeend_label">console.timeEnd([label])</a></li> <li><a href="#console_console_timelog_label_data">console.timeLog([label][, ...data])</a></li> <li><a href="#console_console_trace_message_args">console.trace([message][, ...args])</a></li> <li><a href="#console_console_warn_data_args">console.warn([data][, ...args])</a></li> </ul> </li> <li> <p><a href="#console_inspector_only_methods">Inspector only methods</a></p> <ul> <li><a href="#console_console_marktimeline_label">console.markTimeline([label])</a></li> <li><a href="#console_console_profile_label">console.profile([label])</a></li> <li><a href="#console_console_profileend_label">console.profileEnd([label])</a></li> <li><a href="#console_console_timestamp_label">console.timeStamp([label])</a></li> <li><a href="#console_console_timeline_label">console.timeline([label])</a></li> <li><a href="#console_console_timelineend_label">console.timelineEnd([label])</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#crypto_crypto">Crypto</a></span></p> <ul> <li><a href="#crypto_determining_if_crypto_support_is_unavailable">Determining if crypto support is unavailable</a></li> <li> <p><a href="#crypto_class_certificate">Class: Certificate</a></p> <ul> <li><a href="#crypto_certificate_exportchallenge_spkac">Certificate.exportChallenge(spkac)</a></li> <li><a href="#crypto_certificate_exportpublickey_spkac_encoding">Certificate.exportPublicKey(spkac[, encoding])</a></li> <li><a href="#crypto_certificate_verifyspkac_spkac">Certificate.verifySpkac(spkac)</a></li> <li> <p><a href="#crypto_legacy_api">Legacy API</a></p> <ul> <li><a href="#crypto_new_crypto_certificate">new crypto.Certificate()</a></li> <li><a href="#crypto_certificate_exportchallenge_spkac_1">certificate.exportChallenge(spkac)</a></li> <li><a href="#crypto_certificate_exportpublickey_spkac">certificate.exportPublicKey(spkac)</a></li> <li><a href="#crypto_certificate_verifyspkac_spkac_1">certificate.verifySpkac(spkac)</a></li> </ul> </li> </ul> </li> <li> <p><a href="#crypto_class_cipher">Class: Cipher</a></p> <ul> <li><a href="#crypto_cipher_final_outputencoding">cipher.final([outputEncoding])</a></li> <li><a href="#crypto_cipher_setaad_buffer_options">cipher.setAAD(buffer[, options])</a></li> <li><a href="#crypto_cipher_getauthtag">cipher.getAuthTag()</a></li> <li><a href="#crypto_cipher_setautopadding_autopadding">cipher.setAutoPadding([autoPadding])</a></li> <li><a href="#crypto_cipher_update_data_inputencoding_outputencoding">cipher.update(data[, inputEncoding][, outputEncoding])</a></li> </ul> </li> <li> <p><a href="#crypto_class_decipher">Class: Decipher</a></p> <ul> <li><a href="#crypto_decipher_final_outputencoding">decipher.final([outputEncoding])</a></li> <li><a href="#crypto_decipher_setaad_buffer_options">decipher.setAAD(buffer[, options])</a></li> <li><a href="#crypto_decipher_setauthtag_buffer">decipher.setAuthTag(buffer)</a></li> <li><a href="#crypto_decipher_setautopadding_autopadding">decipher.setAutoPadding([autoPadding])</a></li> <li><a href="#crypto_decipher_update_data_inputencoding_outputencoding">decipher.update(data[, inputEncoding][, outputEncoding])</a></li> </ul> </li> <li> <p><a href="#crypto_class_diffiehellman">Class: DiffieHellman</a></p> <ul> <li><a href="#crypto_diffiehellman_computesecret_otherpublickey_inputencoding_outputencoding">diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</a></li> <li><a href="#crypto_diffiehellman_generatekeys_encoding">diffieHellman.generateKeys([encoding])</a></li> <li><a href="#crypto_diffiehellman_getgenerator_encoding">diffieHellman.getGenerator([encoding])</a></li> <li><a href="#crypto_diffiehellman_getprime_encoding">diffieHellman.getPrime([encoding])</a></li> <li><a href="#crypto_diffiehellman_getprivatekey_encoding">diffieHellman.getPrivateKey([encoding])</a></li> <li><a href="#crypto_diffiehellman_getpublickey_encoding">diffieHellman.getPublicKey([encoding])</a></li> <li><a href="#crypto_diffiehellman_setprivatekey_privatekey_encoding">diffieHellman.setPrivateKey(privateKey[, encoding])</a></li> <li><a href="#crypto_diffiehellman_setpublickey_publickey_encoding">diffieHellman.setPublicKey(publicKey[, encoding])</a></li> <li><a href="#crypto_diffiehellman_verifyerror">diffieHellman.verifyError</a></li> </ul> </li> <li> <p><a href="#crypto_class_ecdh">Class: ECDH</a></p> <ul> <li><a href="#crypto_class_method_ecdh_convertkey_key_curve_inputencoding_outputencoding_format">Class Method: ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])</a></li> <li><a href="#crypto_ecdh_computesecret_otherpublickey_inputencoding_outputencoding">ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</a></li> <li><a href="#crypto_ecdh_generatekeys_encoding_format">ecdh.generateKeys([encoding[, format]])</a></li> <li><a href="#crypto_ecdh_getprivatekey_encoding">ecdh.getPrivateKey([encoding])</a></li> <li><a href="#crypto_ecdh_getpublickey_encoding_format">ecdh.getPublicKey([encoding][, format])</a></li> <li><a href="#crypto_ecdh_setprivatekey_privatekey_encoding">ecdh.setPrivateKey(privateKey[, encoding])</a></li> <li><span class="stability_0"><a href="#crypto_ecdh_setpublickey_publickey_encoding">ecdh.setPublicKey(publicKey[, encoding])</a></span></li> </ul> </li> <li> <p><a href="#crypto_class_hash">Class: Hash</a></p> <ul> <li><a href="#crypto_hash_digest_encoding">hash.digest([encoding])</a></li> <li><a href="#crypto_hash_update_data_inputencoding">hash.update(data[, inputEncoding])</a></li> </ul> </li> <li> <p><a href="#crypto_class_hmac">Class: Hmac</a></p> <ul> <li><a href="#crypto_hmac_digest_encoding">hmac.digest([encoding])</a></li> <li><a href="#crypto_hmac_update_data_inputencoding">hmac.update(data[, inputEncoding])</a></li> </ul> </li> <li> <p><a href="#crypto_class_sign">Class: Sign</a></p> <ul> <li><a href="#crypto_sign_sign_privatekey_outputencoding">sign.sign(privateKey[, outputEncoding])</a></li> <li><a href="#crypto_sign_update_data_inputencoding">sign.update(data[, inputEncoding])</a></li> </ul> </li> <li> <p><a href="#crypto_class_verify">Class: Verify</a></p> <ul> <li><a href="#crypto_verify_update_data_inputencoding">verify.update(data[, inputEncoding])</a></li> <li><a href="#crypto_verify_verify_object_signature_signatureencoding">verify.verify(object, signature[, signatureEncoding])</a></li> </ul> </li> <li> <p><a href="#crypto_crypto_module_methods_and_properties"><code>crypto</code> module methods and properties</a></p> <ul> <li><a href="#crypto_crypto_constants">crypto.constants</a></li> <li><span class="stability_0"><a href="#crypto_crypto_default_encoding">crypto.DEFAULT_ENCODING</a></span></li> <li><span class="stability_0"><a href="#crypto_crypto_fips">crypto.fips</a></span></li> <li><span class="stability_0"><a href="#crypto_crypto_createcipher_algorithm_password_options">crypto.createCipher(algorithm, password[, options])</a></span></li> <li><a href="#crypto_crypto_createcipheriv_algorithm_key_iv_options">crypto.createCipheriv(algorithm, key, iv[, options])</a></li> <li><span class="stability_0"><a href="#crypto_crypto_createcredentials_details">crypto.createCredentials(details)</a></span></li> <li><span class="stability_0"><a href="#crypto_crypto_createdecipher_algorithm_password_options">crypto.createDecipher(algorithm, password[, options])</a></span></li> <li><a href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options">crypto.createDecipheriv(algorithm, key, iv[, options])</a></li> <li><a href="#crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding">crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])</a></li> <li><a href="#crypto_crypto_creatediffiehellman_primelength_generator">crypto.createDiffieHellman(primeLength[, generator])</a></li> <li><a href="#crypto_crypto_createecdh_curvename">crypto.createECDH(curveName)</a></li> <li><a href="#crypto_crypto_createhash_algorithm_options">crypto.createHash(algorithm[, options])</a></li> <li><a href="#crypto_crypto_createhmac_algorithm_key_options">crypto.createHmac(algorithm, key[, options])</a></li> <li><a href="#crypto_crypto_createsign_algorithm_options">crypto.createSign(algorithm[, options])</a></li> <li><a href="#crypto_crypto_createverify_algorithm_options">crypto.createVerify(algorithm[, options])</a></li> <li><a href="#crypto_crypto_generatekeypair_type_options_callback">crypto.generateKeyPair(type, options, callback)</a></li> <li><a href="#crypto_crypto_generatekeypairsync_type_options">crypto.generateKeyPairSync(type, options)</a></li> <li><a href="#crypto_crypto_getciphers">crypto.getCiphers()</a></li> <li><a href="#crypto_crypto_getcurves">crypto.getCurves()</a></li> <li><a href="#crypto_crypto_getdiffiehellman_groupname">crypto.getDiffieHellman(groupName)</a></li> <li><a href="#crypto_crypto_getfips">crypto.getFips()</a></li> <li><a href="#crypto_crypto_gethashes">crypto.getHashes()</a></li> <li><a href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback">crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)</a></li> <li><a href="#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest">crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)</a></li> <li><a href="#crypto_crypto_privatedecrypt_privatekey_buffer">crypto.privateDecrypt(privateKey, buffer)</a></li> <li><a href="#crypto_crypto_privateencrypt_privatekey_buffer">crypto.privateEncrypt(privateKey, buffer)</a></li> <li><a href="#crypto_crypto_publicdecrypt_key_buffer">crypto.publicDecrypt(key, buffer)</a></li> <li><a href="#crypto_crypto_publicencrypt_key_buffer">crypto.publicEncrypt(key, buffer)</a></li> <li><a href="#crypto_crypto_randombytes_size_callback">crypto.randomBytes(size[, callback])</a></li> <li><a href="#crypto_crypto_randomfillsync_buffer_offset_size">crypto.randomFillSync(buffer[, offset][, size])</a></li> <li><a href="#crypto_crypto_randomfill_buffer_offset_size_callback">crypto.randomFill(buffer[, offset][, size], callback)</a></li> <li><a href="#crypto_crypto_scrypt_password_salt_keylen_options_callback">crypto.scrypt(password, salt, keylen[, options], callback)</a></li> <li><a href="#crypto_crypto_scryptsync_password_salt_keylen_options">crypto.scryptSync(password, salt, keylen[, options])</a></li> <li><a href="#crypto_crypto_setengine_engine_flags">crypto.setEngine(engine[, flags])</a></li> <li><a href="#crypto_crypto_setfips_bool">crypto.setFips(bool)</a></li> <li><a href="#crypto_crypto_timingsafeequal_a_b">crypto.timingSafeEqual(a, b)</a></li> </ul> </li> <li> <p><a href="#crypto_notes">Notes</a></p> <ul> <li><a href="#crypto_legacy_streams_api_pre_node_js_v0_10">Legacy Streams API (pre Node.js v0.10)</a></li> <li><a href="#crypto_recent_ecdh_changes">Recent ECDH Changes</a></li> <li><a href="#crypto_support_for_weak_or_compromised_algorithms">Support for weak or compromised algorithms</a></li> <li><a href="#crypto_ccm_mode">CCM mode</a></li> </ul> </li> <li> <p><a href="#crypto_crypto_constants_1">Crypto Constants</a></p> <ul> <li><a href="#crypto_openssl_options">OpenSSL Options</a></li> <li><a href="#crypto_openssl_engine_constants">OpenSSL Engine Constants</a></li> <li><a href="#crypto_other_openssl_constants">Other OpenSSL Constants</a></li> <li><a href="#crypto_node_js_crypto_constants">Node.js Crypto Constants</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#debugger_debugger">Debugger</a></span></p> <ul> <li><a href="#debugger_watchers">Watchers</a></li> <li> <p><a href="#debugger_command_reference">Command reference</a></p> <ul> <li><a href="#debugger_stepping">Stepping</a></li> <li><a href="#debugger_breakpoints">Breakpoints</a></li> <li><a href="#debugger_information">Information</a></li> <li><a href="#debugger_execution_control">Execution control</a></li> <li><a href="#debugger_various">Various</a></li> </ul> </li> <li> <p><a href="#debugger_advanced_usage">Advanced Usage</a></p> <ul> <li><a href="#debugger_v8_inspector_integration_for_node_js">V8 Inspector Integration for Node.js</a></li> </ul> </li> </ul> </li> <li> <p><a href="#deprecations_deprecated_apis">Deprecated APIs</a></p> <ul> <li><a href="#deprecations_revoking_deprecations">Revoking deprecations</a></li> <li> <p><a href="#deprecations_list_of_deprecated_apis">List of Deprecated APIs</a></p> <ul> <li><a href="#deprecations_dep0001_http_outgoingmessage_prototype_flush">DEP0001: http.OutgoingMessage.prototype.flush</a></li> <li><a href="#deprecations_dep0002_require_linklist">DEP0002: require('_linklist')</a></li> <li><a href="#deprecations_dep0003_writablestate_buffer">DEP0003: _writableState.buffer</a></li> <li><a href="#deprecations_dep0004_cryptostream_prototype_readystate">DEP0004: CryptoStream.prototype.readyState</a></li> <li><a href="#deprecations_dep0005_buffer_constructor">DEP0005: Buffer() constructor</a></li> <li><a href="#deprecations_dep0006_child_process_options_customfds">DEP0006: child_process options.customFds</a></li> <li><a href="#deprecations_dep0007_replace_cluster_worker_suicide_with_worker_exitedafterdisconnect">DEP0007: Replace cluster worker.suicide with worker.exitedAfterDisconnect</a></li> <li><a href="#deprecations_dep0008_require_constants">DEP0008: require('constants')</a></li> <li><a href="#deprecations_dep0009_crypto_pbkdf2_without_digest">DEP0009: crypto.pbkdf2 without digest</a></li> <li><a href="#deprecations_dep0010_crypto_createcredentials">DEP0010: crypto.createCredentials</a></li> <li><a href="#deprecations_dep0011_crypto_credentials">DEP0011: crypto.Credentials</a></li> <li><a href="#deprecations_dep0012_domain_dispose">DEP0012: Domain.dispose</a></li> <li><a href="#deprecations_dep0013_fs_asynchronous_function_without_callback">DEP0013: fs asynchronous function without callback</a></li> <li><a href="#deprecations_dep0014_fs_read_legacy_string_interface">DEP0014: fs.read legacy String interface</a></li> <li><a href="#deprecations_dep0015_fs_readsync_legacy_string_interface">DEP0015: fs.readSync legacy String interface</a></li> <li><a href="#deprecations_dep0016_global_root">DEP0016: GLOBAL/root</a></li> <li><a href="#deprecations_dep0017_intl_v8breakiterator">DEP0017: Intl.v8BreakIterator</a></li> <li><a href="#deprecations_dep0018_unhandled_promise_rejections">DEP0018: Unhandled promise rejections</a></li> <li><a href="#deprecations_dep0019_require_resolved_outside_directory">DEP0019: require('.') resolved outside directory</a></li> <li><a href="#deprecations_dep0020_server_connections">DEP0020: Server.connections</a></li> <li><a href="#deprecations_dep0021_server_listenfd">DEP0021: Server.listenFD</a></li> <li><a href="#deprecations_dep0022_os_tmpdir">DEP0022: os.tmpDir()</a></li> <li><a href="#deprecations_dep0023_os_getnetworkinterfaces">DEP0023: os.getNetworkInterfaces()</a></li> <li><a href="#deprecations_dep0024_replserver_prototype_converttocontext">DEP0024: REPLServer.prototype.convertToContext()</a></li> <li><a href="#deprecations_dep0025_require_sys">DEP0025: require('sys')</a></li> <li><a href="#deprecations_dep0026_util_print">DEP0026: util.print()</a></li> <li><a href="#deprecations_dep0027_util_puts">DEP0027: util.puts()</a></li> <li><a href="#deprecations_dep0028_util_debug">DEP0028: util.debug()</a></li> <li><a href="#deprecations_dep0029_util_error">DEP0029: util.error()</a></li> <li><a href="#deprecations_dep0030_slowbuffer">DEP0030: SlowBuffer</a></li> <li><a href="#deprecations_dep0031_ecdh_setpublickey">DEP0031: ecdh.setPublicKey()</a></li> <li><a href="#deprecations_dep0032_domain_module">DEP0032: domain module</a></li> <li><a href="#deprecations_dep0033_eventemitter_listenercount">DEP0033: EventEmitter.listenerCount()</a></li> <li><a href="#deprecations_dep0034_fs_exists_path_callback">DEP0034: fs.exists(path, callback)</a></li> <li><a href="#deprecations_dep0035_fs_lchmod_path_mode_callback">DEP0035: fs.lchmod(path, mode, callback)</a></li> <li><a href="#deprecations_dep0036_fs_lchmodsync_path_mode">DEP0036: fs.lchmodSync(path, mode)</a></li> <li><a href="#deprecations_dep0037_fs_lchown_path_uid_gid_callback">DEP0037: fs.lchown(path, uid, gid, callback)</a></li> <li><a href="#deprecations_dep0038_fs_lchownsync_path_uid_gid">DEP0038: fs.lchownSync(path, uid, gid)</a></li> <li><a href="#deprecations_dep0039_require_extensions">DEP0039: require.extensions</a></li> <li><a href="#deprecations_dep0040_punycode_module">DEP0040: punycode module</a></li> <li><a href="#deprecations_dep0041_node_repl_history_file_environment_variable">DEP0041: NODE_REPL_HISTORY_FILE environment variable</a></li> <li><a href="#deprecations_dep0042_tls_cryptostream">DEP0042: tls.CryptoStream</a></li> <li><a href="#deprecations_dep0043_tls_securepair">DEP0043: tls.SecurePair</a></li> <li><a href="#deprecations_dep0044_util_isarray">DEP0044: util.isArray()</a></li> <li><a href="#deprecations_dep0045_util_isboolean">DEP0045: util.isBoolean()</a></li> <li><a href="#deprecations_dep0046_util_isbuffer">DEP0046: util.isBuffer()</a></li> <li><a href="#deprecations_dep0047_util_isdate">DEP0047: util.isDate()</a></li> <li><a href="#deprecations_dep0048_util_iserror">DEP0048: util.isError()</a></li> <li><a href="#deprecations_dep0049_util_isfunction">DEP0049: util.isFunction()</a></li> <li><a href="#deprecations_dep0050_util_isnull">DEP0050: util.isNull()</a></li> <li><a href="#deprecations_dep0051_util_isnullorundefined">DEP0051: util.isNullOrUndefined()</a></li> <li><a href="#deprecations_dep0052_util_isnumber">DEP0052: util.isNumber()</a></li> <li><a href="#deprecations_dep0053_util_isobject">DEP0053 util.isObject()</a></li> <li><a href="#deprecations_dep0054_util_isprimitive">DEP0054: util.isPrimitive()</a></li> <li><a href="#deprecations_dep0055_util_isregexp">DEP0055: util.isRegExp()</a></li> <li><a href="#deprecations_dep0056_util_isstring">DEP0056: util.isString()</a></li> <li><a href="#deprecations_dep0057_util_issymbol">DEP0057: util.isSymbol()</a></li> <li><a href="#deprecations_dep0058_util_isundefined">DEP0058: util.isUndefined()</a></li> <li><a href="#deprecations_dep0059_util_log">DEP0059: util.log()</a></li> <li><a href="#deprecations_dep0060_util_extend">DEP0060: util._extend()</a></li> <li><a href="#deprecations_dep0061_fs_syncwritestream">DEP0061: fs.SyncWriteStream</a></li> <li><a href="#deprecations_dep0062_node_debug">DEP0062: node --debug</a></li> <li><a href="#deprecations_dep0063_serverresponse_prototype_writeheader">DEP0063: ServerResponse.prototype.writeHeader()</a></li> <li><a href="#deprecations_dep0064_tls_createsecurepair">DEP0064: tls.createSecurePair()</a></li> <li><a href="#deprecations_dep0065_repl_repl_mode_magic_and_node_repl_mode_magic">DEP0065: repl.REPL_MODE_MAGIC and NODE_REPL_MODE=magic</a></li> <li><a href="#deprecations_dep0066_outgoingmessage_headers_outgoingmessage_headernames">DEP0066: outgoingMessage._headers, outgoingMessage._headerNames</a></li> <li><a href="#deprecations_dep0067_outgoingmessage_prototype_renderheaders">DEP0067: OutgoingMessage.prototype._renderHeaders</a></li> <li><a href="#deprecations_dep0068_node_debug">DEP0068: node debug</a></li> <li><a href="#deprecations_dep0069_vm_runindebugcontext_string">DEP0069: vm.runInDebugContext(string)</a></li> <li><a href="#deprecations_dep0070_async_hooks_currentid">DEP0070: async_hooks.currentId()</a></li> <li><a href="#deprecations_dep0071_async_hooks_triggerid">DEP0071: async_hooks.triggerId()</a></li> <li><a href="#deprecations_dep0072_async_hooks_asyncresource_triggerid">DEP0072: async_hooks.AsyncResource.triggerId()</a></li> <li><a href="#deprecations_dep0073_several_internal_properties_of_net_server">DEP0073: Several internal properties of net.Server</a></li> <li><a href="#deprecations_dep0074_replserver_bufferedcommand">DEP0074: REPLServer.bufferedCommand</a></li> <li><a href="#deprecations_dep0075_replserver_parsereplkeyword">DEP0075: REPLServer.parseREPLKeyword()</a></li> <li><a href="#deprecations_dep0076_tls_parsecertstring">DEP0076: tls.parseCertString()</a></li> <li><a href="#deprecations_dep0077_module_debug">DEP0077: Module._debug()</a></li> <li><a href="#deprecations_dep0078_replserver_turnoffeditormode">DEP0078: REPLServer.turnOffEditorMode()</a></li> <li><a href="#deprecations_dep0079_custom_inspection_function_on_objects_via_inspect">DEP0079: Custom inspection function on Objects via .inspect()</a></li> <li><a href="#deprecations_dep0080_path_makelong">DEP0080: path._makeLong()</a></li> <li><a href="#deprecations_dep0081_fs_truncate_using_a_file_descriptor">DEP0081: fs.truncate() using a file descriptor</a></li> <li><a href="#deprecations_dep0082_replserver_prototype_memory">DEP0082: REPLServer.prototype.memory()</a></li> <li><a href="#deprecations_dep0083_disabling_ecdh_by_setting_ecdhcurve_to_false">DEP0083: Disabling ECDH by setting ecdhCurve to false</a></li> <li><a href="#deprecations_dep0084_requiring_bundled_internal_dependencies">DEP0084: requiring bundled internal dependencies</a></li> <li><a href="#deprecations_dep0085_asynchooks_sensitive_api">DEP0085: AsyncHooks Sensitive API</a></li> <li><a href="#deprecations_dep0086_remove_runinasyncidscope">DEP0086: Remove runInAsyncIdScope</a></li> <li><a href="#deprecations_dep0089_require_assert">DEP0089: require('assert')</a></li> <li><a href="#deprecations_dep0090_invalid_gcm_authentication_tag_lengths">DEP0090: Invalid GCM authentication tag lengths</a></li> <li><a href="#deprecations_dep0091_crypto_default_encoding">DEP0091: crypto.DEFAULT_ENCODING</a></li> <li><a href="#deprecations_dep0092_top_level_this_bound_to_module_exports">DEP0092: Top-level <code>this</code> bound to <code>module.exports</code></a></li> <li><a href="#deprecations_dep0093_crypto_fips_is_deprecated_and_replaced">DEP0093: crypto.fips is deprecated and replaced.</a></li> <li><a href="#deprecations_dep0094_using_assert_fail_with_more_than_one_argument">DEP0094: Using <code>assert.fail()</code> with more than one argument.</a></li> <li><a href="#deprecations_dep0095_timers_enroll">DEP0095: timers.enroll()</a></li> <li><a href="#deprecations_dep0096_timers_unenroll">DEP0096: timers.unenroll()</a></li> <li><a href="#deprecations_dep0097_makecallback_with_domain_property">DEP0097: MakeCallback with domain property</a></li> <li><a href="#deprecations_dep0098_asynchooks_embedder_asyncresource_emitbefore_and_asyncresource_emitafter_apis">DEP0098: AsyncHooks Embedder AsyncResource.emitBefore and AsyncResource.emitAfter APIs</a></li> <li><a href="#deprecations_dep0099_async_context_unaware_node_makecallback_c_apis">DEP0099: async context-unaware node::MakeCallback C++ APIs</a></li> <li><a href="#deprecations_dep0100_process_assert">DEP0100: process.assert()</a></li> <li><a href="#deprecations_dep0101_with_lttng">DEP0101: --with-lttng</a></li> <li><a href="#deprecations_dep0102_using_noassert_in_buffer_read_write_operations">DEP0102: Using <code>noAssert</code> in Buffer#(read|write) operations.</a></li> <li><a href="#deprecations_dep0103_process_binding_util_is_typechecks">DEP0103: process.binding('util').is[...] typechecks</a></li> <li><a href="#deprecations_dep0104_process_env_string_coercion">DEP0104: process.env string coercion</a></li> <li><a href="#deprecations_dep0105_decipher_finaltol">DEP0105: decipher.finaltol</a></li> <li><a href="#deprecations_dep0106_crypto_createcipher_and_crypto_createdecipher">DEP0106: crypto.createCipher and crypto.createDecipher</a></li> <li><a href="#deprecations_dep0107_tls_convertnpnprotocols">DEP0107: tls.convertNPNProtocols()</a></li> <li><a href="#deprecations_dep0108_zlib_bytesread">DEP0108: zlib.bytesRead</a></li> <li><a href="#deprecations_dep0110_vm_script_cached_data">DEP0110: vm.Script cached data</a></li> <li><a href="#deprecations_dep0111_process_binding">DEP0111: process.binding()</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#dns_dns">DNS</a></span></p> <ul> <li> <p><a href="#dns_class_dns_resolver">Class: <code>dns.Resolver</code></a></p> <ul> <li><a href="#dns_resolver_cancel"><code>resolver.cancel()</code></a></li> </ul> </li> <li><a href="#dns_dns_getservers"><code>dns.getServers()</code></a></li> <li> <p><a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup(hostname[, options], callback)</code></a></p> <ul> <li><a href="#dns_supported_getaddrinfo_flags">Supported getaddrinfo flags</a></li> </ul> </li> <li><a href="#dns_dns_lookupservice_address_port_callback"><code>dns.lookupService(address, port, callback)</code></a></li> <li><a href="#dns_dns_resolve_hostname_rrtype_callback"><code>dns.resolve(hostname[, rrtype], callback)</code></a></li> <li><a href="#dns_dns_resolve4_hostname_options_callback"><code>dns.resolve4(hostname[, options], callback)</code></a></li> <li><a href="#dns_dns_resolve6_hostname_options_callback"><code>dns.resolve6(hostname[, options], callback)</code></a></li> <li><a href="#dns_dns_resolveany_hostname_callback"><code>dns.resolveAny(hostname, callback)</code></a></li> <li><a href="#dns_dns_resolvecname_hostname_callback"><code>dns.resolveCname(hostname, callback)</code></a></li> <li><a href="#dns_dns_resolvemx_hostname_callback"><code>dns.resolveMx(hostname, callback)</code></a></li> <li><a href="#dns_dns_resolvenaptr_hostname_callback"><code>dns.resolveNaptr(hostname, callback)</code></a></li> <li><a href="#dns_dns_resolvens_hostname_callback"><code>dns.resolveNs(hostname, callback)</code></a></li> <li><a href="#dns_dns_resolveptr_hostname_callback"><code>dns.resolvePtr(hostname, callback)</code></a></li> <li><a href="#dns_dns_resolvesoa_hostname_callback"><code>dns.resolveSoa(hostname, callback)</code></a></li> <li><a href="#dns_dns_resolvesrv_hostname_callback"><code>dns.resolveSrv(hostname, callback)</code></a></li> <li><a href="#dns_dns_resolvetxt_hostname_callback"><code>dns.resolveTxt(hostname, callback)</code></a></li> <li><a href="#dns_dns_reverse_ip_callback"><code>dns.reverse(ip, callback)</code></a></li> <li><a href="#dns_dns_setservers_servers"><code>dns.setServers(servers)</code></a></li> <li> <p><a href="#dns_dns_promises_api">DNS Promises API</a></p> <ul> <li><a href="#dns_class_dnspromises_resolver">Class: <code>dnsPromises.Resolver</code></a></li> <li><a href="#dns_dnspromises_getservers"><code>dnsPromises.getServers()</code></a></li> <li><a href="#dns_dnspromises_lookup_hostname_options"><code>dnsPromises.lookup(hostname[, options])</code></a></li> <li><a href="#dns_dnspromises_lookupservice_address_port"><code>dnsPromises.lookupService(address, port)</code></a></li> <li><a href="#dns_dnspromises_resolve_hostname_rrtype"><code>dnsPromises.resolve(hostname[, rrtype])</code></a></li> <li><a href="#dns_dnspromises_resolve4_hostname_options"><code>dnsPromises.resolve4(hostname[, options])</code></a></li> <li><a href="#dns_dnspromises_resolve6_hostname_options"><code>dnsPromises.resolve6(hostname[, options])</code></a></li> <li><a href="#dns_dnspromises_resolveany_hostname"><code>dnsPromises.resolveAny(hostname)</code></a></li> <li><a href="#dns_dnspromises_resolvecname_hostname"><code>dnsPromises.resolveCname(hostname)</code></a></li> <li><a href="#dns_dnspromises_resolvemx_hostname"><code>dnsPromises.resolveMx(hostname)</code></a></li> <li><a href="#dns_dnspromises_resolvenaptr_hostname"><code>dnsPromises.resolveNaptr(hostname)</code></a></li> <li><a href="#dns_dnspromises_resolvens_hostname"><code>dnsPromises.resolveNs(hostname)</code></a></li> <li><a href="#dns_dnspromises_resolveptr_hostname"><code>dnsPromises.resolvePtr(hostname)</code></a></li> <li><a href="#dns_dnspromises_resolvesoa_hostname"><code>dnsPromises.resolveSoa(hostname)</code></a></li> <li><a href="#dns_dnspromises_resolvesrv_hostname"><code>dnsPromises.resolveSrv(hostname)</code></a></li> <li><a href="#dns_dnspromises_resolvetxt_hostname"><code>dnsPromises.resolveTxt(hostname)</code></a></li> <li><a href="#dns_dnspromises_reverse_ip"><code>dnsPromises.reverse(ip)</code></a></li> <li><a href="#dns_dnspromises_setservers_servers"><code>dnsPromises.setServers(servers)</code></a></li> </ul> </li> <li><a href="#dns_error_codes">Error codes</a></li> <li> <p><a href="#dns_implementation_considerations">Implementation considerations</a></p> <ul> <li><a href="#dns_dns_lookup"><code>dns.lookup()</code></a></li> <li><a href="#dns_dns_resolve_dns_resolve_and_dns_reverse"><code>dns.resolve()</code>, <code>dns.resolve*()</code> and <code>dns.reverse()</code></a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_0"><a href="#domain_domain">Domain</a></span></p> <ul> <li><a href="#domain_warning_don_t_ignore_errors">Warning: Don't Ignore Errors!</a></li> <li><a href="#domain_additions_to_error_objects">Additions to Error objects</a></li> <li><a href="#domain_implicit_binding">Implicit Binding</a></li> <li><a href="#domain_explicit_binding">Explicit Binding</a></li> <li><a href="#domain_domain_create">domain.create()</a></li> <li> <p><a href="#domain_class_domain">Class: Domain</a></p> <ul> <li><a href="#domain_domain_members">domain.members</a></li> <li><a href="#domain_domain_add_emitter">domain.add(emitter)</a></li> <li><a href="#domain_domain_bind_callback">domain.bind(callback)</a></li> <li><a href="#domain_domain_enter">domain.enter()</a></li> <li><a href="#domain_domain_exit">domain.exit()</a></li> <li><a href="#domain_domain_intercept_callback">domain.intercept(callback)</a></li> <li><a href="#domain_domain_remove_emitter">domain.remove(emitter)</a></li> <li><a href="#domain_domain_run_fn_args">domain.run(fn[, ...args])</a></li> </ul> </li> <li><a href="#domain_domains_and_promises">Domains and Promises</a></li> </ul> </li> <li> <p><span class="stability_1"><a href="#esm_ecmascript_modules">ECMAScript Modules</a></span></p> <ul> <li><a href="#esm_enabling">Enabling</a></li> <li> <p><a href="#esm_features">Features</a></p> <ul> <li> <p><a href="#esm_supported">Supported</a></p> <ul> <li><a href="#esm_import_meta">import.meta</a></li> </ul> </li> <li><a href="#esm_unsupported">Unsupported</a></li> </ul> </li> <li> <p><a href="#esm_notable_differences_between_import_and_require">Notable differences between <code>import</code> and <code>require</code></a></p> <ul> <li><a href="#esm_no_node_path">No NODE_PATH</a></li> <li><a href="#esm_no_require_extensions">No <code>require.extensions</code></a></li> <li><a href="#esm_no_require_cache">No <code>require.cache</code></a></li> <li><a href="#esm_url_based_paths">URL based paths</a></li> </ul> </li> <li><a href="#esm_interop_with_existing_modules">Interop with existing modules</a></li> <li> <p><a href="#esm_loader_hooks">Loader hooks</a></p> <ul> <li><a href="#esm_resolve_hook">Resolve hook</a></li> <li><a href="#esm_dynamic_instantiate_hook">Dynamic instantiate hook</a></li> </ul> </li> </ul> </li> <li> <p><a href="#errors_errors">Errors</a></p> <ul> <li> <p><a href="#errors_error_propagation_and_interception">Error Propagation and Interception</a></p> <ul> <li><a href="#errors_error_first_callbacks">Error-first callbacks</a></li> </ul> </li> <li> <p><a href="#errors_class_error">Class: Error</a></p> <ul> <li><a href="#errors_new_error_message">new Error(message)</a></li> <li><a href="#errors_error_capturestacktrace_targetobject_constructoropt">Error.captureStackTrace(targetObject[, constructorOpt])</a></li> <li><a href="#errors_error_stacktracelimit">Error.stackTraceLimit</a></li> <li><a href="#errors_error_code">error.code</a></li> <li><a href="#errors_error_message">error.message</a></li> <li><a href="#errors_error_stack">error.stack</a></li> </ul> </li> <li><a href="#errors_class_assertionerror">Class: AssertionError</a></li> <li><a href="#errors_class_rangeerror">Class: RangeError</a></li> <li><a href="#errors_class_referenceerror">Class: ReferenceError</a></li> <li><a href="#errors_class_syntaxerror">Class: SyntaxError</a></li> <li><a href="#errors_class_typeerror">Class: TypeError</a></li> <li><a href="#errors_exceptions_vs_errors">Exceptions vs. Errors</a></li> <li> <p><a href="#errors_system_errors">System Errors</a></p> <ul> <li> <p><a href="#errors_class_systemerror">Class: SystemError</a></p> <ul> <li><a href="#errors_error_address">error.address</a></li> <li><a href="#errors_error_code_1">error.code</a></li> <li><a href="#errors_error_dest">error.dest</a></li> <li><a href="#errors_error_errno">error.errno</a></li> <li><a href="#errors_error_info">error.info</a></li> <li><a href="#errors_error_message_1">error.message</a></li> <li><a href="#errors_error_path">error.path</a></li> <li><a href="#errors_error_port">error.port</a></li> <li><a href="#errors_error_syscall">error.syscall</a></li> </ul> </li> <li><a href="#errors_common_system_errors">Common System Errors</a></li> </ul> </li> <li> <p><a href="#errors_node_js_error_codes">Node.js Error Codes</a></p> <ul> <li><a href="#errors_err_ambiguous_argument">ERR_AMBIGUOUS_ARGUMENT</a></li> <li><a href="#errors_err_arg_not_iterable">ERR_ARG_NOT_ITERABLE</a></li> <li><a href="#errors_err_assertion">ERR_ASSERTION</a></li> <li><a href="#errors_err_async_callback">ERR_ASYNC_CALLBACK</a></li> <li><a href="#errors_err_async_type">ERR_ASYNC_TYPE</a></li> <li><a href="#errors_err_brotli_compression_failed">ERR_BROTLI_COMPRESSION_FAILED</a></li> <li><a href="#errors_err_brotli_invalid_param">ERR_BROTLI_INVALID_PARAM</a></li> <li><a href="#errors_err_buffer_out_of_bounds">ERR_BUFFER_OUT_OF_BOUNDS</a></li> <li><a href="#errors_err_buffer_too_large">ERR_BUFFER_TOO_LARGE</a></li> <li><a href="#errors_err_cannot_transfer_object">ERR_CANNOT_TRANSFER_OBJECT</a></li> <li><a href="#errors_err_cannot_watch_sigint">ERR_CANNOT_WATCH_SIGINT</a></li> <li><a href="#errors_err_child_closed_before_reply">ERR_CHILD_CLOSED_BEFORE_REPLY</a></li> <li><a href="#errors_err_child_process_ipc_required">ERR_CHILD_PROCESS_IPC_REQUIRED</a></li> <li><a href="#errors_err_child_process_stdio_maxbuffer">ERR_CHILD_PROCESS_STDIO_MAXBUFFER</a></li> <li><a href="#errors_err_closed_message_port">ERR_CLOSED_MESSAGE_PORT</a></li> <li><a href="#errors_err_console_writable_stream">ERR_CONSOLE_WRITABLE_STREAM</a></li> <li><a href="#errors_err_construct_call_required">ERR_CONSTRUCT_CALL_REQUIRED</a></li> <li><a href="#errors_err_cpu_usage">ERR_CPU_USAGE</a></li> <li><a href="#errors_err_crypto_custom_engine_not_supported">ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED</a></li> <li><a href="#errors_err_crypto_ecdh_invalid_format">ERR_CRYPTO_ECDH_INVALID_FORMAT</a></li> <li><a href="#errors_err_crypto_ecdh_invalid_public_key">ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY</a></li> <li><a href="#errors_err_crypto_engine_unknown">ERR_CRYPTO_ENGINE_UNKNOWN</a></li> <li><a href="#errors_err_crypto_fips_forced">ERR_CRYPTO_FIPS_FORCED</a></li> <li><a href="#errors_err_crypto_fips_unavailable">ERR_CRYPTO_FIPS_UNAVAILABLE</a></li> <li><a href="#errors_err_crypto_hash_digest_no_utf16">ERR_CRYPTO_HASH_DIGEST_NO_UTF16</a></li> <li><a href="#errors_err_crypto_hash_finalized">ERR_CRYPTO_HASH_FINALIZED</a></li> <li><a href="#errors_err_crypto_hash_update_failed">ERR_CRYPTO_HASH_UPDATE_FAILED</a></li> <li><a href="#errors_err_crypto_incompatible_key_options">ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS</a></li> <li><a href="#errors_err_crypto_invalid_digest">ERR_CRYPTO_INVALID_DIGEST</a></li> <li><a href="#errors_err_crypto_invalid_state">ERR_CRYPTO_INVALID_STATE</a></li> <li><a href="#errors_err_crypto_pbkdf2_error">ERR_CRYPTO_PBKDF2_ERROR</a></li> <li><a href="#errors_err_crypto_scrypt_invalid_parameter">ERR_CRYPTO_SCRYPT_INVALID_PARAMETER</a></li> <li><a href="#errors_err_crypto_scrypt_not_supported">ERR_CRYPTO_SCRYPT_NOT_SUPPORTED</a></li> <li><a href="#errors_err_crypto_sign_key_required">ERR_CRYPTO_SIGN_KEY_REQUIRED</a></li> <li><a href="#errors_err_crypto_timing_safe_equal_length">ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH</a></li> <li><a href="#errors_err_dns_set_servers_failed">ERR_DNS_SET_SERVERS_FAILED</a></li> <li><a href="#errors_err_domain_callback_not_available">ERR_DOMAIN_CALLBACK_NOT_AVAILABLE</a></li> <li><a href="#errors_err_domain_cannot_set_uncaught_exception_capture">ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</a></li> <li><a href="#errors_err_encoding_invalid_encoded_data">ERR_ENCODING_INVALID_ENCODED_DATA</a></li> <li><a href="#errors_err_encoding_not_supported">ERR_ENCODING_NOT_SUPPORTED</a></li> <li><a href="#errors_err_falsy_value_rejection">ERR_FALSY_VALUE_REJECTION</a></li> <li><a href="#errors_err_fs_file_too_large">ERR_FS_FILE_TOO_LARGE</a></li> <li><a href="#errors_err_fs_invalid_symlink_type">ERR_FS_INVALID_SYMLINK_TYPE</a></li> <li><a href="#errors_err_http_headers_sent">ERR_HTTP_HEADERS_SENT</a></li> <li><a href="#errors_err_http_invalid_header_value">ERR_HTTP_INVALID_HEADER_VALUE</a></li> <li><a href="#errors_err_http_invalid_status_code">ERR_HTTP_INVALID_STATUS_CODE</a></li> <li><a href="#errors_err_http_trailer_invalid">ERR_HTTP_TRAILER_INVALID</a></li> <li><a href="#errors_err_http2_altsvc_invalid_origin">ERR_HTTP2_ALTSVC_INVALID_ORIGIN</a></li> <li><a href="#errors_err_http2_altsvc_length">ERR_HTTP2_ALTSVC_LENGTH</a></li> <li><a href="#errors_err_http2_connect_authority">ERR_HTTP2_CONNECT_AUTHORITY</a></li> <li><a href="#errors_err_http2_connect_path">ERR_HTTP2_CONNECT_PATH</a></li> <li><a href="#errors_err_http2_connect_scheme">ERR_HTTP2_CONNECT_SCHEME</a></li> <li><a href="#errors_err_http2_error">ERR_HTTP2_ERROR</a></li> <li><a href="#errors_err_http2_goaway_session">ERR_HTTP2_GOAWAY_SESSION</a></li> <li><a href="#errors_err_http2_headers_after_respond">ERR_HTTP2_HEADERS_AFTER_RESPOND</a></li> <li><a href="#errors_err_http2_headers_sent">ERR_HTTP2_HEADERS_SENT</a></li> <li><a href="#errors_err_http2_header_single_value">ERR_HTTP2_HEADER_SINGLE_VALUE</a></li> <li><a href="#errors_err_http2_info_status_not_allowed">ERR_HTTP2_INFO_STATUS_NOT_ALLOWED</a></li> <li><a href="#errors_err_http2_invalid_connection_headers">ERR_HTTP2_INVALID_CONNECTION_HEADERS</a></li> <li><a href="#errors_err_http2_invalid_header_value">ERR_HTTP2_INVALID_HEADER_VALUE</a></li> <li><a href="#errors_err_http2_invalid_info_status">ERR_HTTP2_INVALID_INFO_STATUS</a></li> <li><a href="#errors_err_http2_invalid_origin">ERR_HTTP2_INVALID_ORIGIN</a></li> <li><a href="#errors_err_http2_invalid_packed_settings_length">ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH</a></li> <li><a href="#errors_err_http2_invalid_pseudoheader">ERR_HTTP2_INVALID_PSEUDOHEADER</a></li> <li><a href="#errors_err_http2_invalid_session">ERR_HTTP2_INVALID_SESSION</a></li> <li><a href="#errors_err_http2_invalid_setting_value">ERR_HTTP2_INVALID_SETTING_VALUE</a></li> <li><a href="#errors_err_http2_invalid_stream">ERR_HTTP2_INVALID_STREAM</a></li> <li><a href="#errors_err_http2_max_pending_settings_ack">ERR_HTTP2_MAX_PENDING_SETTINGS_ACK</a></li> <li><a href="#errors_err_http2_nested_push">ERR_HTTP2_NESTED_PUSH</a></li> <li><a href="#errors_err_http2_no_socket_manipulation">ERR_HTTP2_NO_SOCKET_MANIPULATION</a></li> <li><a href="#errors_err_http2_origin_length">ERR_HTTP2_ORIGIN_LENGTH</a></li> <li><a href="#errors_err_http2_out_of_streams">ERR_HTTP2_OUT_OF_STREAMS</a></li> <li><a href="#errors_err_http2_payload_forbidden">ERR_HTTP2_PAYLOAD_FORBIDDEN</a></li> <li><a href="#errors_err_http2_ping_cancel">ERR_HTTP2_PING_CANCEL</a></li> <li><a href="#errors_err_http2_ping_length">ERR_HTTP2_PING_LENGTH</a></li> <li><a href="#errors_err_http2_pseudoheader_not_allowed">ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED</a></li> <li><a href="#errors_err_http2_push_disabled">ERR_HTTP2_PUSH_DISABLED</a></li> <li><a href="#errors_err_http2_send_file">ERR_HTTP2_SEND_FILE</a></li> <li><a href="#errors_err_http2_send_file_noseek">ERR_HTTP2_SEND_FILE_NOSEEK</a></li> <li><a href="#errors_err_http2_session_error">ERR_HTTP2_SESSION_ERROR</a></li> <li><a href="#errors_err_http2_settings_cancel">ERR_HTTP2_SETTINGS_CANCEL</a></li> <li><a href="#errors_err_http2_socket_bound">ERR_HTTP2_SOCKET_BOUND</a></li> <li><a href="#errors_err_http2_socket_unbound">ERR_HTTP2_SOCKET_UNBOUND</a></li> <li><a href="#errors_err_http2_status_101">ERR_HTTP2_STATUS_101</a></li> <li><a href="#errors_err_http2_status_invalid">ERR_HTTP2_STATUS_INVALID</a></li> <li><a href="#errors_err_http2_stream_cancel">ERR_HTTP2_STREAM_CANCEL</a></li> <li><a href="#errors_err_http2_stream_error">ERR_HTTP2_STREAM_ERROR</a></li> <li><a href="#errors_err_http2_stream_self_dependency">ERR_HTTP2_STREAM_SELF_DEPENDENCY</a></li> <li><a href="#errors_err_http2_trailers_already_sent">ERR_HTTP2_TRAILERS_ALREADY_SENT</a></li> <li><a href="#errors_err_http2_trailers_not_ready">ERR_HTTP2_TRAILERS_NOT_READY</a></li> <li><a href="#errors_err_http2_unsupported_protocol">ERR_HTTP2_UNSUPPORTED_PROTOCOL</a></li> <li><a href="#errors_err_index_out_of_range">ERR_INDEX_OUT_OF_RANGE</a></li> <li><a href="#errors_err_inspector_already_connected">ERR_INSPECTOR_ALREADY_CONNECTED</a></li> <li><a href="#errors_err_inspector_closed">ERR_INSPECTOR_CLOSED</a></li> <li><a href="#errors_err_inspector_not_available">ERR_INSPECTOR_NOT_AVAILABLE</a></li> <li><a href="#errors_err_inspector_not_connected">ERR_INSPECTOR_NOT_CONNECTED</a></li> <li><a href="#errors_err_invalid_address_family">ERR_INVALID_ADDRESS_FAMILY</a></li> <li><a href="#errors_err_invalid_arg_type">ERR_INVALID_ARG_TYPE</a></li> <li><a href="#errors_err_invalid_arg_value">ERR_INVALID_ARG_VALUE</a></li> <li><a href="#errors_err_invalid_array_length">ERR_INVALID_ARRAY_LENGTH</a></li> <li><a href="#errors_err_invalid_async_id">ERR_INVALID_ASYNC_ID</a></li> <li><a href="#errors_err_invalid_buffer_size">ERR_INVALID_BUFFER_SIZE</a></li> <li><a href="#errors_err_invalid_callback">ERR_INVALID_CALLBACK</a></li> <li><a href="#errors_err_invalid_char">ERR_INVALID_CHAR</a></li> <li><a href="#errors_err_invalid_cursor_pos">ERR_INVALID_CURSOR_POS</a></li> <li><a href="#errors_err_invalid_domain_name">ERR_INVALID_DOMAIN_NAME</a></li> <li><a href="#errors_err_invalid_fd">ERR_INVALID_FD</a></li> <li><a href="#errors_err_invalid_fd_type">ERR_INVALID_FD_TYPE</a></li> <li><a href="#errors_err_invalid_file_url_host">ERR_INVALID_FILE_URL_HOST</a></li> <li><a href="#errors_err_invalid_file_url_path">ERR_INVALID_FILE_URL_PATH</a></li> <li><a href="#errors_err_invalid_handle_type">ERR_INVALID_HANDLE_TYPE</a></li> <li><a href="#errors_err_invalid_http_token">ERR_INVALID_HTTP_TOKEN</a></li> <li><a href="#errors_err_invalid_ip_address">ERR_INVALID_IP_ADDRESS</a></li> <li><a href="#errors_err_invalid_opt_value">ERR_INVALID_OPT_VALUE</a></li> <li><a href="#errors_err_invalid_opt_value_encoding">ERR_INVALID_OPT_VALUE_ENCODING</a></li> <li><a href="#errors_err_invalid_performance_mark">ERR_INVALID_PERFORMANCE_MARK</a></li> <li><a href="#errors_err_invalid_protocol">ERR_INVALID_PROTOCOL</a></li> <li><a href="#errors_err_invalid_repl_eval_config">ERR_INVALID_REPL_EVAL_CONFIG</a></li> <li><a href="#errors_err_invalid_return_property">ERR_INVALID_RETURN_PROPERTY</a></li> <li><a href="#errors_err_invalid_return_property_value">ERR_INVALID_RETURN_PROPERTY_VALUE</a></li> <li><a href="#errors_err_invalid_return_value">ERR_INVALID_RETURN_VALUE</a></li> <li><a href="#errors_err_invalid_sync_fork_input">ERR_INVALID_SYNC_FORK_INPUT</a></li> <li><a href="#errors_err_invalid_this">ERR_INVALID_THIS</a></li> <li><a href="#errors_err_invalid_transfer_object">ERR_INVALID_TRANSFER_OBJECT</a></li> <li><a href="#errors_err_invalid_tuple">ERR_INVALID_TUPLE</a></li> <li><a href="#errors_err_invalid_uri">ERR_INVALID_URI</a></li> <li><a href="#errors_err_invalid_url">ERR_INVALID_URL</a></li> <li><a href="#errors_err_invalid_url_scheme">ERR_INVALID_URL_SCHEME</a></li> <li><a href="#errors_err_ipc_channel_closed">ERR_IPC_CHANNEL_CLOSED</a></li> <li><a href="#errors_err_ipc_disconnected">ERR_IPC_DISCONNECTED</a></li> <li><a href="#errors_err_ipc_one_pipe">ERR_IPC_ONE_PIPE</a></li> <li><a href="#errors_err_ipc_sync_fork">ERR_IPC_SYNC_FORK</a></li> <li><a href="#errors_err_memory_allocation_failed">ERR_MEMORY_ALLOCATION_FAILED</a></li> <li><a href="#errors_err_method_not_implemented">ERR_METHOD_NOT_IMPLEMENTED</a></li> <li><a href="#errors_err_missing_args">ERR_MISSING_ARGS</a></li> <li><a href="#errors_err_missing_dynamic_instantiate_hook">ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK</a></li> <li><a href="#errors_err_missing_message_port_in_transfer_list">ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</a></li> <li><a href="#errors_err_missing_module">ERR_MISSING_MODULE</a></li> <li><a href="#errors_err_missing_platform_for_worker">ERR_MISSING_PLATFORM_FOR_WORKER</a></li> <li><a href="#errors_err_module_resolution_legacy">ERR_MODULE_RESOLUTION_LEGACY</a></li> <li><a href="#errors_err_multiple_callback">ERR_MULTIPLE_CALLBACK</a></li> <li><a href="#errors_err_napi_cons_function">ERR_NAPI_CONS_FUNCTION</a></li> <li><a href="#errors_err_napi_invalid_dataview_args">ERR_NAPI_INVALID_DATAVIEW_ARGS</a></li> <li><a href="#errors_err_napi_invalid_typedarray_alignment">ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT</a></li> <li><a href="#errors_err_napi_invalid_typedarray_length">ERR_NAPI_INVALID_TYPEDARRAY_LENGTH</a></li> <li><a href="#errors_err_napi_tsfn_call_js">ERR_NAPI_TSFN_CALL_JS</a></li> <li><a href="#errors_err_napi_tsfn_get_undefined">ERR_NAPI_TSFN_GET_UNDEFINED</a></li> <li><a href="#errors_err_napi_tsfn_start_idle_loop">ERR_NAPI_TSFN_START_IDLE_LOOP</a></li> <li><a href="#errors_err_napi_tsfn_stop_idle_loop">ERR_NAPI_TSFN_STOP_IDLE_LOOP</a></li> <li><a href="#errors_err_no_crypto">ERR_NO_CRYPTO</a></li> <li><a href="#errors_err_no_icu">ERR_NO_ICU</a></li> <li><a href="#errors_err_no_longer_supported">ERR_NO_LONGER_SUPPORTED</a></li> <li><a href="#errors_err_out_of_range">ERR_OUT_OF_RANGE</a></li> <li><a href="#errors_err_require_esm">ERR_REQUIRE_ESM</a></li> <li><a href="#errors_err_script_execution_interrupted">ERR_SCRIPT_EXECUTION_INTERRUPTED</a></li> <li><a href="#errors_err_server_already_listen">ERR_SERVER_ALREADY_LISTEN</a></li> <li><a href="#errors_err_server_not_running">ERR_SERVER_NOT_RUNNING</a></li> <li><a href="#errors_err_socket_already_bound">ERR_SOCKET_ALREADY_BOUND</a></li> <li><a href="#errors_err_socket_bad_buffer_size">ERR_SOCKET_BAD_BUFFER_SIZE</a></li> <li><a href="#errors_err_socket_bad_port">ERR_SOCKET_BAD_PORT</a></li> <li><a href="#errors_err_socket_bad_type">ERR_SOCKET_BAD_TYPE</a></li> <li><a href="#errors_err_socket_buffer_size">ERR_SOCKET_BUFFER_SIZE</a></li> <li><a href="#errors_err_socket_cannot_send">ERR_SOCKET_CANNOT_SEND</a></li> <li><a href="#errors_err_socket_closed">ERR_SOCKET_CLOSED</a></li> <li><a href="#errors_err_socket_dgram_not_running">ERR_SOCKET_DGRAM_NOT_RUNNING</a></li> <li><a href="#errors_err_stream_cannot_pipe">ERR_STREAM_CANNOT_PIPE</a></li> <li><a href="#errors_err_stream_destroyed">ERR_STREAM_DESTROYED</a></li> <li><a href="#errors_err_stream_null_values">ERR_STREAM_NULL_VALUES</a></li> <li><a href="#errors_err_stream_premature_close">ERR_STREAM_PREMATURE_CLOSE</a></li> <li><a href="#errors_err_stream_push_after_eof">ERR_STREAM_PUSH_AFTER_EOF</a></li> <li><a href="#errors_err_stream_unshift_after_end_event">ERR_STREAM_UNSHIFT_AFTER_END_EVENT</a></li> <li><a href="#errors_err_stream_wrap">ERR_STREAM_WRAP</a></li> <li><a href="#errors_err_stream_write_after_end">ERR_STREAM_WRITE_AFTER_END</a></li> <li><a href="#errors_err_string_too_long">ERR_STRING_TOO_LONG</a></li> <li><a href="#errors_err_system_error">ERR_SYSTEM_ERROR</a></li> <li><a href="#errors_err_tls_cert_altname_invalid">ERR_TLS_CERT_ALTNAME_INVALID</a></li> <li><a href="#errors_err_tls_dh_param_size">ERR_TLS_DH_PARAM_SIZE</a></li> <li><a href="#errors_err_tls_handshake_timeout">ERR_TLS_HANDSHAKE_TIMEOUT</a></li> <li><a href="#errors_err_tls_invalid_protocol_version">ERR_TLS_INVALID_PROTOCOL_VERSION</a></li> <li><a href="#errors_err_tls_protocol_version_conflict">ERR_TLS_PROTOCOL_VERSION_CONFLICT</a></li> <li><a href="#errors_err_tls_renegotiate">ERR_TLS_RENEGOTIATE</a></li> <li><a href="#errors_err_tls_renegotiation_disabled">ERR_TLS_RENEGOTIATION_DISABLED</a></li> <li><a href="#errors_err_tls_required_server_name">ERR_TLS_REQUIRED_SERVER_NAME</a></li> <li><a href="#errors_err_tls_session_attack">ERR_TLS_SESSION_ATTACK</a></li> <li><a href="#errors_err_tls_sni_from_server">ERR_TLS_SNI_FROM_SERVER</a></li> <li><a href="#errors_err_trace_events_category_required">ERR_TRACE_EVENTS_CATEGORY_REQUIRED</a></li> <li><a href="#errors_err_trace_events_unavailable">ERR_TRACE_EVENTS_UNAVAILABLE</a></li> <li><a href="#errors_err_transferring_externalized_sharedarraybuffer">ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER</a></li> <li><a href="#errors_err_transform_already_transforming">ERR_TRANSFORM_ALREADY_TRANSFORMING</a></li> <li><a href="#errors_err_transform_with_length_0">ERR_TRANSFORM_WITH_LENGTH_0</a></li> <li><a href="#errors_err_tty_init_failed">ERR_TTY_INIT_FAILED</a></li> <li><a href="#errors_err_uncaught_exception_capture_already_set">ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET</a></li> <li><a href="#errors_err_unescaped_characters">ERR_UNESCAPED_CHARACTERS</a></li> <li><a href="#errors_err_unhandled_error">ERR_UNHANDLED_ERROR</a></li> <li><a href="#errors_err_unknown_builtin_module">ERR_UNKNOWN_BUILTIN_MODULE</a></li> <li><a href="#errors_err_unknown_encoding">ERR_UNKNOWN_ENCODING</a></li> <li><a href="#errors_err_unknown_file_extension">ERR_UNKNOWN_FILE_EXTENSION</a></li> <li><a href="#errors_err_unknown_module_format">ERR_UNKNOWN_MODULE_FORMAT</a></li> <li><a href="#errors_err_unknown_signal">ERR_UNKNOWN_SIGNAL</a></li> <li><a href="#errors_err_unknown_stdin_type">ERR_UNKNOWN_STDIN_TYPE</a></li> <li><a href="#errors_err_unknown_stream_type">ERR_UNKNOWN_STREAM_TYPE</a></li> <li><a href="#errors_err_v8breakiterator">ERR_V8BREAKITERATOR</a></li> <li><a href="#errors_err_valid_performance_entry_type">ERR_VALID_PERFORMANCE_ENTRY_TYPE</a></li> <li><a href="#errors_err_vm_dynamic_import_callback_missing">ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</a></li> <li><a href="#errors_err_vm_module_already_linked">ERR_VM_MODULE_ALREADY_LINKED</a></li> <li><a href="#errors_err_vm_module_different_context">ERR_VM_MODULE_DIFFERENT_CONTEXT</a></li> <li><a href="#errors_err_vm_module_linking_errored">ERR_VM_MODULE_LINKING_ERRORED</a></li> <li><a href="#errors_err_vm_module_not_linked">ERR_VM_MODULE_NOT_LINKED</a></li> <li><a href="#errors_err_vm_module_not_module">ERR_VM_MODULE_NOT_MODULE</a></li> <li><a href="#errors_err_vm_module_status">ERR_VM_MODULE_STATUS</a></li> <li><a href="#errors_err_worker_path">ERR_WORKER_PATH</a></li> <li><a href="#errors_err_worker_unserializable_error">ERR_WORKER_UNSERIALIZABLE_ERROR</a></li> <li><a href="#errors_err_worker_unsupported_extension">ERR_WORKER_UNSUPPORTED_EXTENSION</a></li> <li><a href="#errors_err_zlib_initialization_failed">ERR_ZLIB_INITIALIZATION_FAILED</a></li> <li><a href="#errors_hpe_header_overflow">HPE_HEADER_OVERFLOW</a></li> <li><a href="#errors_module_not_found">MODULE_NOT_FOUND</a></li> </ul> </li> <li> <p><a href="#errors_legacy_node_js_error_codes">Legacy Node.js Error Codes</a></p> <ul> <li><a href="#errors_err_http2_frame_error">ERR_HTTP2_FRAME_ERROR</a></li> <li><a href="#errors_err_http2_headers_object">ERR_HTTP2_HEADERS_OBJECT</a></li> <li><a href="#errors_err_http2_header_required">ERR_HTTP2_HEADER_REQUIRED</a></li> <li><a href="#errors_err_http2_info_headers_after_respond">ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND</a></li> <li><a href="#errors_err_http2_stream_closed">ERR_HTTP2_STREAM_CLOSED</a></li> <li><a href="#errors_err_http_invalid_char">ERR_HTTP_INVALID_CHAR</a></li> <li><a href="#errors_err_napi_cons_prototype_object">ERR_NAPI_CONS_PROTOTYPE_OBJECT</a></li> <li><a href="#errors_err_outofmemory">ERR_OUTOFMEMORY</a></li> <li><a href="#errors_err_parse_history_data">ERR_PARSE_HISTORY_DATA</a></li> <li><a href="#errors_err_stderr_close">ERR_STDERR_CLOSE</a></li> <li><a href="#errors_err_stdout_close">ERR_STDOUT_CLOSE</a></li> <li><a href="#errors_err_stream_read_not_implemented">ERR_STREAM_READ_NOT_IMPLEMENTED</a></li> <li><a href="#errors_err_tls_renegotiation_failed">ERR_TLS_RENEGOTIATION_FAILED</a></li> <li><a href="#errors_err_unknown_builtin_module_1">ERR_UNKNOWN_BUILTIN_MODULE</a></li> <li><a href="#errors_err_value_out_of_range">ERR_VALUE_OUT_OF_RANGE</a></li> <li><a href="#errors_err_zlib_binding_closed">ERR_ZLIB_BINDING_CLOSED</a></li> <li> <p><a href="#errors_other_error_codes">Other error codes</a></p> <ul> <li><a href="#errors_err_fs_watcher_already_started">ERR_FS_WATCHER_ALREADY_STARTED</a></li> <li><a href="#errors_err_fs_watcher_not_started">ERR_FS_WATCHER_NOT_STARTED</a></li> <li><a href="#errors_err_http2_already_shutdown">ERR_HTTP2_ALREADY_SHUTDOWN</a></li> <li><a href="#errors_err_http2_error_1">ERR_HTTP2_ERROR</a></li> <li><a href="#errors_err_invalid_repl_history">ERR_INVALID_REPL_HISTORY</a></li> <li><a href="#errors_err_missing_dynamic_instantiate_hook_1">ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK</a></li> <li><a href="#errors_err_stream_has_stringdecoder">ERR_STREAM_HAS_STRINGDECODER</a></li> <li><a href="#errors_err_string_too_large">ERR_STRING_TOO_LARGE</a></li> </ul> </li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#events_events">Events</a></span></p> <ul> <li><a href="#events_passing_arguments_and_this_to_listeners">Passing arguments and <code>this</code> to listeners</a></li> <li><a href="#events_asynchronous_vs_synchronous">Asynchronous vs. Synchronous</a></li> <li><a href="#events_handling_events_only_once">Handling events only once</a></li> <li><a href="#events_error_events">Error events</a></li> <li> <p><a href="#events_class_eventemitter">Class: EventEmitter</a></p> <ul> <li><a href="#events_event_newlistener">Event: 'newListener'</a></li> <li><a href="#events_event_removelistener">Event: 'removeListener'</a></li> <li><span class="stability_0"><a href="#events_eventemitter_listenercount_emitter_eventname">EventEmitter.listenerCount(emitter, eventName)</a></span></li> <li><a href="#events_eventemitter_defaultmaxlisteners">EventEmitter.defaultMaxListeners</a></li> <li><a href="#events_emitter_addlistener_eventname_listener">emitter.addListener(eventName, listener)</a></li> <li><a href="#events_emitter_emit_eventname_args">emitter.emit(eventName[, ...args])</a></li> <li><a href="#events_emitter_eventnames">emitter.eventNames()</a></li> <li><a href="#events_emitter_getmaxlisteners">emitter.getMaxListeners()</a></li> <li><a href="#events_emitter_listenercount_eventname">emitter.listenerCount(eventName)</a></li> <li><a href="#events_emitter_listeners_eventname">emitter.listeners(eventName)</a></li> <li><a href="#events_emitter_off_eventname_listener">emitter.off(eventName, listener)</a></li> <li><a href="#events_emitter_on_eventname_listener">emitter.on(eventName, listener)</a></li> <li><a href="#events_emitter_once_eventname_listener">emitter.once(eventName, listener)</a></li> <li><a href="#events_emitter_prependlistener_eventname_listener">emitter.prependListener(eventName, listener)</a></li> <li><a href="#events_emitter_prependoncelistener_eventname_listener">emitter.prependOnceListener(eventName, listener)</a></li> <li><a href="#events_emitter_removealllisteners_eventname">emitter.removeAllListeners([eventName])</a></li> <li><a href="#events_emitter_removelistener_eventname_listener">emitter.removeListener(eventName, listener)</a></li> <li><a href="#events_emitter_setmaxlisteners_n">emitter.setMaxListeners(n)</a></li> <li><a href="#events_emitter_rawlisteners_eventname">emitter.rawListeners(eventName)</a></li> </ul> </li> <li><a href="#events_events_once_emitter_name">events.once(emitter, name)</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#fs_file_system">File System</a></span></p> <ul> <li> <p><a href="#fs_file_paths">File paths</a></p> <ul> <li><a href="#fs_url_object_support">URL object support</a></li> </ul> </li> <li><a href="#fs_file_descriptors">File Descriptors</a></li> <li><a href="#fs_threadpool_usage">Threadpool Usage</a></li> <li> <p><a href="#fs_class_fs_dirent">Class: fs.Dirent</a></p> <ul> <li><a href="#fs_dirent_isblockdevice">dirent.isBlockDevice()</a></li> <li><a href="#fs_dirent_ischaracterdevice">dirent.isCharacterDevice()</a></li> <li><a href="#fs_dirent_isdirectory">dirent.isDirectory()</a></li> <li><a href="#fs_dirent_isfifo">dirent.isFIFO()</a></li> <li><a href="#fs_dirent_isfile">dirent.isFile()</a></li> <li><a href="#fs_dirent_issocket">dirent.isSocket()</a></li> <li><a href="#fs_dirent_issymboliclink">dirent.isSymbolicLink()</a></li> <li><a href="#fs_dirent_name">dirent.name</a></li> </ul> </li> <li> <p><a href="#fs_class_fs_fswatcher">Class: fs.FSWatcher</a></p> <ul> <li><a href="#fs_event_change">Event: 'change'</a></li> <li><a href="#fs_event_close">Event: 'close'</a></li> <li><a href="#fs_event_error">Event: 'error'</a></li> <li><a href="#fs_watcher_close">watcher.close()</a></li> </ul> </li> <li> <p><a href="#fs_class_fs_readstream">Class: fs.ReadStream</a></p> <ul> <li><a href="#fs_event_close_1">Event: 'close'</a></li> <li><a href="#fs_event_open">Event: 'open'</a></li> <li><a href="#fs_event_ready">Event: 'ready'</a></li> <li><a href="#fs_readstream_bytesread">readStream.bytesRead</a></li> <li><a href="#fs_readstream_path">readStream.path</a></li> <li><a href="#fs_readstream_pending">readStream.pending</a></li> </ul> </li> <li> <p><a href="#fs_class_fs_stats">Class: fs.Stats</a></p> <ul> <li><a href="#fs_stats_isblockdevice">stats.isBlockDevice()</a></li> <li><a href="#fs_stats_ischaracterdevice">stats.isCharacterDevice()</a></li> <li><a href="#fs_stats_isdirectory">stats.isDirectory()</a></li> <li><a href="#fs_stats_isfifo">stats.isFIFO()</a></li> <li><a href="#fs_stats_isfile">stats.isFile()</a></li> <li><a href="#fs_stats_issocket">stats.isSocket()</a></li> <li><a href="#fs_stats_issymboliclink">stats.isSymbolicLink()</a></li> <li><a href="#fs_stats_dev">stats.dev</a></li> <li><a href="#fs_stats_ino">stats.ino</a></li> <li><a href="#fs_stats_mode">stats.mode</a></li> <li><a href="#fs_stats_nlink">stats.nlink</a></li> <li><a href="#fs_stats_uid">stats.uid</a></li> <li><a href="#fs_stats_gid">stats.gid</a></li> <li><a href="#fs_stats_rdev">stats.rdev</a></li> <li><a href="#fs_stats_size">stats.size</a></li> <li><a href="#fs_stats_blksize">stats.blksize</a></li> <li><a href="#fs_stats_blocks">stats.blocks</a></li> <li><a href="#fs_stats_atimems">stats.atimeMs</a></li> <li><a href="#fs_stats_mtimems">stats.mtimeMs</a></li> <li><a href="#fs_stats_ctimems">stats.ctimeMs</a></li> <li><a href="#fs_stats_birthtimems">stats.birthtimeMs</a></li> <li><a href="#fs_stats_atime">stats.atime</a></li> <li><a href="#fs_stats_mtime">stats.mtime</a></li> <li><a href="#fs_stats_ctime">stats.ctime</a></li> <li><a href="#fs_stats_birthtime">stats.birthtime</a></li> <li><a href="#fs_stat_time_values">Stat Time Values</a></li> </ul> </li> <li> <p><a href="#fs_class_fs_writestream">Class: fs.WriteStream</a></p> <ul> <li><a href="#fs_event_close_2">Event: 'close'</a></li> <li><a href="#fs_event_open_1">Event: 'open'</a></li> <li><a href="#fs_event_ready_1">Event: 'ready'</a></li> <li><a href="#fs_writestream_byteswritten">writeStream.bytesWritten</a></li> <li><a href="#fs_writestream_path">writeStream.path</a></li> <li><a href="#fs_writestream_pending">writeStream.pending</a></li> </ul> </li> <li><a href="#fs_fs_access_path_mode_callback">fs.access(path[, mode], callback)</a></li> <li><a href="#fs_fs_accesssync_path_mode">fs.accessSync(path[, mode])</a></li> <li><a href="#fs_fs_appendfile_path_data_options_callback">fs.appendFile(path, data[, options], callback)</a></li> <li><a href="#fs_fs_appendfilesync_path_data_options">fs.appendFileSync(path, data[, options])</a></li> <li> <p><a href="#fs_fs_chmod_path_mode_callback">fs.chmod(path, mode, callback)</a></p> <ul> <li><a href="#fs_file_modes">File modes</a></li> </ul> </li> <li><a href="#fs_fs_chmodsync_path_mode">fs.chmodSync(path, mode)</a></li> <li><a href="#fs_fs_chown_path_uid_gid_callback">fs.chown(path, uid, gid, callback)</a></li> <li><a href="#fs_fs_chownsync_path_uid_gid">fs.chownSync(path, uid, gid)</a></li> <li><a href="#fs_fs_close_fd_callback">fs.close(fd, callback)</a></li> <li><a href="#fs_fs_closesync_fd">fs.closeSync(fd)</a></li> <li><a href="#fs_fs_constants">fs.constants</a></li> <li><a href="#fs_fs_copyfile_src_dest_flags_callback">fs.copyFile(src, dest[, flags], callback)</a></li> <li><a href="#fs_fs_copyfilesync_src_dest_flags">fs.copyFileSync(src, dest[, flags])</a></li> <li><a href="#fs_fs_createreadstream_path_options">fs.createReadStream(path[, options])</a></li> <li><a href="#fs_fs_createwritestream_path_options">fs.createWriteStream(path[, options])</a></li> <li><span class="stability_0"><a href="#fs_fs_exists_path_callback">fs.exists(path, callback)</a></span></li> <li><a href="#fs_fs_existssync_path">fs.existsSync(path)</a></li> <li><a href="#fs_fs_fchmod_fd_mode_callback">fs.fchmod(fd, mode, callback)</a></li> <li><a href="#fs_fs_fchmodsync_fd_mode">fs.fchmodSync(fd, mode)</a></li> <li><a href="#fs_fs_fchown_fd_uid_gid_callback">fs.fchown(fd, uid, gid, callback)</a></li> <li><a href="#fs_fs_fchownsync_fd_uid_gid">fs.fchownSync(fd, uid, gid)</a></li> <li><a href="#fs_fs_fdatasync_fd_callback">fs.fdatasync(fd, callback)</a></li> <li><a href="#fs_fs_fdatasyncsync_fd">fs.fdatasyncSync(fd)</a></li> <li><a href="#fs_fs_fstat_fd_options_callback">fs.fstat(fd[, options], callback)</a></li> <li><a href="#fs_fs_fstatsync_fd_options">fs.fstatSync(fd[, options])</a></li> <li><a href="#fs_fs_fsync_fd_callback">fs.fsync(fd, callback)</a></li> <li><a href="#fs_fs_fsyncsync_fd">fs.fsyncSync(fd)</a></li> <li><a href="#fs_fs_ftruncate_fd_len_callback">fs.ftruncate(fd[, len], callback)</a></li> <li><a href="#fs_fs_ftruncatesync_fd_len">fs.ftruncateSync(fd[, len])</a></li> <li><a href="#fs_fs_futimes_fd_atime_mtime_callback">fs.futimes(fd, atime, mtime, callback)</a></li> <li><a href="#fs_fs_futimessync_fd_atime_mtime">fs.futimesSync(fd, atime, mtime)</a></li> <li><a href="#fs_fs_lchmod_path_mode_callback">fs.lchmod(path, mode, callback)</a></li> <li><a href="#fs_fs_lchmodsync_path_mode">fs.lchmodSync(path, mode)</a></li> <li><a href="#fs_fs_lchown_path_uid_gid_callback">fs.lchown(path, uid, gid, callback)</a></li> <li><a href="#fs_fs_lchownsync_path_uid_gid">fs.lchownSync(path, uid, gid)</a></li> <li><a href="#fs_fs_link_existingpath_newpath_callback">fs.link(existingPath, newPath, callback)</a></li> <li><a href="#fs_fs_linksync_existingpath_newpath">fs.linkSync(existingPath, newPath)</a></li> <li><a href="#fs_fs_lstat_path_options_callback">fs.lstat(path[, options], callback)</a></li> <li><a href="#fs_fs_lstatsync_path_options">fs.lstatSync(path[, options])</a></li> <li><a href="#fs_fs_mkdir_path_options_callback">fs.mkdir(path[, options], callback)</a></li> <li><a href="#fs_fs_mkdirsync_path_options">fs.mkdirSync(path[, options])</a></li> <li><a href="#fs_fs_mkdtemp_prefix_options_callback">fs.mkdtemp(prefix[, options], callback)</a></li> <li><a href="#fs_fs_mkdtempsync_prefix_options">fs.mkdtempSync(prefix[, options])</a></li> <li><a href="#fs_fs_open_path_flags_mode_callback">fs.open(path[, flags[, mode]], callback)</a></li> <li><a href="#fs_fs_opensync_path_flags_mode">fs.openSync(path[, flags, mode])</a></li> <li><a href="#fs_fs_read_fd_buffer_offset_length_position_callback">fs.read(fd, buffer, offset, length, position, callback)</a></li> <li><a href="#fs_fs_readdir_path_options_callback">fs.readdir(path[, options], callback)</a></li> <li><a href="#fs_fs_readdirsync_path_options">fs.readdirSync(path[, options])</a></li> <li> <p><a href="#fs_fs_readfile_path_options_callback">fs.readFile(path[, options], callback)</a></p> <ul> <li><a href="#fs_file_descriptors_1">File Descriptors</a></li> </ul> </li> <li><a href="#fs_fs_readfilesync_path_options">fs.readFileSync(path[, options])</a></li> <li><a href="#fs_fs_readlink_path_options_callback">fs.readlink(path[, options], callback)</a></li> <li><a href="#fs_fs_readlinksync_path_options">fs.readlinkSync(path[, options])</a></li> <li><a href="#fs_fs_readsync_fd_buffer_offset_length_position">fs.readSync(fd, buffer, offset, length, position)</a></li> <li><a href="#fs_fs_realpath_path_options_callback">fs.realpath(path[, options], callback)</a></li> <li><a href="#fs_fs_realpath_native_path_options_callback">fs.realpath.native(path[, options], callback)</a></li> <li><a href="#fs_fs_realpathsync_path_options">fs.realpathSync(path[, options])</a></li> <li><a href="#fs_fs_realpathsync_native_path_options">fs.realpathSync.native(path[, options])</a></li> <li><a href="#fs_fs_rename_oldpath_newpath_callback">fs.rename(oldPath, newPath, callback)</a></li> <li><a href="#fs_fs_renamesync_oldpath_newpath">fs.renameSync(oldPath, newPath)</a></li> <li><a href="#fs_fs_rmdir_path_callback">fs.rmdir(path, callback)</a></li> <li><a href="#fs_fs_rmdirsync_path">fs.rmdirSync(path)</a></li> <li><a href="#fs_fs_stat_path_options_callback">fs.stat(path[, options], callback)</a></li> <li><a href="#fs_fs_statsync_path_options">fs.statSync(path[, options])</a></li> <li><a href="#fs_fs_symlink_target_path_type_callback">fs.symlink(target, path[, type], callback)</a></li> <li><a href="#fs_fs_symlinksync_target_path_type">fs.symlinkSync(target, path[, type])</a></li> <li><a href="#fs_fs_truncate_path_len_callback">fs.truncate(path[, len], callback)</a></li> <li><a href="#fs_fs_truncatesync_path_len">fs.truncateSync(path[, len])</a></li> <li><a href="#fs_fs_unlink_path_callback">fs.unlink(path, callback)</a></li> <li><a href="#fs_fs_unlinksync_path">fs.unlinkSync(path)</a></li> <li><a href="#fs_fs_unwatchfile_filename_listener">fs.unwatchFile(filename[, listener])</a></li> <li><a href="#fs_fs_utimes_path_atime_mtime_callback">fs.utimes(path, atime, mtime, callback)</a></li> <li><a href="#fs_fs_utimessync_path_atime_mtime">fs.utimesSync(path, atime, mtime)</a></li> <li> <p><a href="#fs_fs_watch_filename_options_listener">fs.watch(filename[, options][, listener])</a></p> <ul> <li> <p><a href="#fs_caveats">Caveats</a></p> <ul> <li><a href="#fs_availability">Availability</a></li> <li><a href="#fs_inodes">Inodes</a></li> <li><a href="#fs_filename_argument">Filename Argument</a></li> </ul> </li> </ul> </li> <li><a href="#fs_fs_watchfile_filename_options_listener">fs.watchFile(filename[, options], listener)</a></li> <li><a href="#fs_fs_write_fd_buffer_offset_length_position_callback">fs.write(fd, buffer[, offset[, length[, position]]], callback)</a></li> <li><a href="#fs_fs_write_fd_string_position_encoding_callback">fs.write(fd, string[, position[, encoding]], callback)</a></li> <li> <p><a href="#fs_fs_writefile_file_data_options_callback">fs.writeFile(file, data[, options], callback)</a></p> <ul> <li><a href="#fs_file_descriptors_2">File Descriptors</a></li> </ul> </li> <li><a href="#fs_fs_writefilesync_file_data_options">fs.writeFileSync(file, data[, options])</a></li> <li><a href="#fs_fs_writesync_fd_buffer_offset_length_position">fs.writeSync(fd, buffer[, offset[, length[, position]]])</a></li> <li><a href="#fs_fs_writesync_fd_string_position_encoding">fs.writeSync(fd, string[, position[, encoding]])</a></li> <li> <p><a href="#fs_fs_promises_api">fs Promises API</a></p> <ul> <li> <p><a href="#fs_class_filehandle">class: FileHandle</a></p> <ul> <li><a href="#fs_filehandle_appendfile_data_options">filehandle.appendFile(data, options)</a></li> <li><a href="#fs_filehandle_chmod_mode">filehandle.chmod(mode)</a></li> <li><a href="#fs_filehandle_chown_uid_gid">filehandle.chown(uid, gid)</a></li> <li><a href="#fs_filehandle_close">filehandle.close()</a></li> <li><a href="#fs_filehandle_datasync">filehandle.datasync()</a></li> <li><a href="#fs_filehandle_fd">filehandle.fd</a></li> <li><a href="#fs_filehandle_read_buffer_offset_length_position">filehandle.read(buffer, offset, length, position)</a></li> <li><a href="#fs_filehandle_readfile_options">filehandle.readFile(options)</a></li> <li><a href="#fs_filehandle_stat_options">filehandle.stat([options])</a></li> <li><a href="#fs_filehandle_sync">filehandle.sync()</a></li> <li><a href="#fs_filehandle_truncate_len">filehandle.truncate(len)</a></li> <li><a href="#fs_filehandle_utimes_atime_mtime">filehandle.utimes(atime, mtime)</a></li> <li><a href="#fs_filehandle_write_buffer_offset_length_position">filehandle.write(buffer, offset, length, position)</a></li> <li><a href="#fs_filehandle_write_string_position_encoding">filehandle.write(string[, position[, encoding]])</a></li> <li><a href="#fs_filehandle_writefile_data_options">filehandle.writeFile(data, options)</a></li> </ul> </li> <li><a href="#fs_fspromises_access_path_mode">fsPromises.access(path[, mode])</a></li> <li><a href="#fs_fspromises_appendfile_path_data_options">fsPromises.appendFile(path, data[, options])</a></li> <li><a href="#fs_fspromises_chmod_path_mode">fsPromises.chmod(path, mode)</a></li> <li><a href="#fs_fspromises_chown_path_uid_gid">fsPromises.chown(path, uid, gid)</a></li> <li><a href="#fs_fspromises_copyfile_src_dest_flags">fsPromises.copyFile(src, dest[, flags])</a></li> <li><a href="#fs_fspromises_lchmod_path_mode">fsPromises.lchmod(path, mode)</a></li> <li><a href="#fs_fspromises_lchown_path_uid_gid">fsPromises.lchown(path, uid, gid)</a></li> <li><a href="#fs_fspromises_link_existingpath_newpath">fsPromises.link(existingPath, newPath)</a></li> <li><a href="#fs_fspromises_lstat_path_options">fsPromises.lstat(path[, options])</a></li> <li><a href="#fs_fspromises_mkdir_path_options">fsPromises.mkdir(path[, options])</a></li> <li><a href="#fs_fspromises_mkdtemp_prefix_options">fsPromises.mkdtemp(prefix[, options])</a></li> <li><a href="#fs_fspromises_open_path_flags_mode">fsPromises.open(path, flags[, mode])</a></li> <li><a href="#fs_fspromises_readdir_path_options">fsPromises.readdir(path[, options])</a></li> <li><a href="#fs_fspromises_readfile_path_options">fsPromises.readFile(path[, options])</a></li> <li><a href="#fs_fspromises_readlink_path_options">fsPromises.readlink(path[, options])</a></li> <li><a href="#fs_fspromises_realpath_path_options">fsPromises.realpath(path[, options])</a></li> <li><a href="#fs_fspromises_rename_oldpath_newpath">fsPromises.rename(oldPath, newPath)</a></li> <li><a href="#fs_fspromises_rmdir_path">fsPromises.rmdir(path)</a></li> <li><a href="#fs_fspromises_stat_path_options">fsPromises.stat(path[, options])</a></li> <li><a href="#fs_fspromises_symlink_target_path_type">fsPromises.symlink(target, path[, type])</a></li> <li><a href="#fs_fspromises_truncate_path_len">fsPromises.truncate(path[, len])</a></li> <li><a href="#fs_fspromises_unlink_path">fsPromises.unlink(path)</a></li> <li><a href="#fs_fspromises_utimes_path_atime_mtime">fsPromises.utimes(path, atime, mtime)</a></li> <li><a href="#fs_fspromises_writefile_file_data_options">fsPromises.writeFile(file, data[, options])</a></li> </ul> </li> <li> <p><a href="#fs_fs_constants_1">FS Constants</a></p> <ul> <li><a href="#fs_file_access_constants">File Access Constants</a></li> <li><a href="#fs_file_copy_constants">File Copy Constants</a></li> <li><a href="#fs_file_open_constants">File Open Constants</a></li> <li><a href="#fs_file_type_constants">File Type Constants</a></li> <li><a href="#fs_file_mode_constants">File Mode Constants</a></li> </ul> </li> <li><a href="#fs_file_system_flags">File System Flags</a></li> </ul> </li> <li> <p><a href="#globals_global_objects">Global Objects</a></p> <ul> <li><a href="#globals_class_buffer">Class: Buffer</a></li> <li><a href="#globals_dirname">__dirname</a></li> <li><a href="#globals_filename">__filename</a></li> <li><a href="#globals_clearimmediate_immediateobject">clearImmediate(immediateObject)</a></li> <li><a href="#globals_clearinterval_intervalobject">clearInterval(intervalObject)</a></li> <li><a href="#globals_cleartimeout_timeoutobject">clearTimeout(timeoutObject)</a></li> <li><a href="#globals_console">console</a></li> <li><a href="#globals_exports">exports</a></li> <li><a href="#globals_global">global</a></li> <li><a href="#globals_module">module</a></li> <li><a href="#globals_process">process</a></li> <li><a href="#globals_require">require()</a></li> <li><a href="#globals_setimmediate_callback_args">setImmediate(callback[, ...args])</a></li> <li><a href="#globals_setinterval_callback_delay_args">setInterval(callback, delay[, ...args])</a></li> <li><a href="#globals_settimeout_callback_delay_args">setTimeout(callback, delay[, ...args])</a></li> <li><a href="#globals_url">URL</a></li> <li><a href="#globals_urlsearchparams">URLSearchParams</a></li> <li><a href="#globals_webassembly">WebAssembly</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#http_http">HTTP</a></span></p> <ul> <li> <p><a href="#http_class_http_agent">Class: http.Agent</a></p> <ul> <li><a href="#http_new_agent_options">new Agent([options])</a></li> <li><a href="#http_agent_createconnection_options_callback">agent.createConnection(options[, callback])</a></li> <li><a href="#http_agent_keepsocketalive_socket">agent.keepSocketAlive(socket)</a></li> <li><a href="#http_agent_reusesocket_socket_request">agent.reuseSocket(socket, request)</a></li> <li><a href="#http_agent_destroy">agent.destroy()</a></li> <li><a href="#http_agent_freesockets">agent.freeSockets</a></li> <li><a href="#http_agent_getname_options">agent.getName(options)</a></li> <li><a href="#http_agent_maxfreesockets">agent.maxFreeSockets</a></li> <li><a href="#http_agent_maxsockets">agent.maxSockets</a></li> <li><a href="#http_agent_requests">agent.requests</a></li> <li><a href="#http_agent_sockets">agent.sockets</a></li> </ul> </li> <li> <p><a href="#http_class_http_clientrequest">Class: http.ClientRequest</a></p> <ul> <li><a href="#http_event_abort">Event: 'abort'</a></li> <li><a href="#http_event_connect">Event: 'connect'</a></li> <li><a href="#http_event_continue">Event: 'continue'</a></li> <li><a href="#http_event_information">Event: 'information'</a></li> <li><a href="#http_event_response">Event: 'response'</a></li> <li><a href="#http_event_socket">Event: 'socket'</a></li> <li><a href="#http_event_timeout">Event: 'timeout'</a></li> <li><a href="#http_event_upgrade">Event: 'upgrade'</a></li> <li><a href="#http_request_abort">request.abort()</a></li> <li><a href="#http_request_aborted">request.aborted</a></li> <li><a href="#http_request_connection">request.connection</a></li> <li><a href="#http_request_end_data_encoding_callback">request.end([data[, encoding]][, callback])</a></li> <li><a href="#http_request_finished">request.finished</a></li> <li><a href="#http_request_flushheaders">request.flushHeaders()</a></li> <li><a href="#http_request_getheader_name">request.getHeader(name)</a></li> <li><a href="#http_request_maxheaderscount">request.maxHeadersCount</a></li> <li><a href="#http_request_removeheader_name">request.removeHeader(name)</a></li> <li><a href="#http_request_setheader_name_value">request.setHeader(name, value)</a></li> <li><a href="#http_request_setnodelay_nodelay">request.setNoDelay([noDelay])</a></li> <li><a href="#http_request_setsocketkeepalive_enable_initialdelay">request.setSocketKeepAlive([enable][, initialDelay])</a></li> <li><a href="#http_request_settimeout_timeout_callback">request.setTimeout(timeout[, callback])</a></li> <li><a href="#http_request_socket">request.socket</a></li> <li><a href="#http_request_write_chunk_encoding_callback">request.write(chunk[, encoding][, callback])</a></li> </ul> </li> <li> <p><a href="#http_class_http_server">Class: http.Server</a></p> <ul> <li><a href="#http_event_checkcontinue">Event: 'checkContinue'</a></li> <li><a href="#http_event_checkexpectation">Event: 'checkExpectation'</a></li> <li><a href="#http_event_clienterror">Event: 'clientError'</a></li> <li><a href="#http_event_close">Event: 'close'</a></li> <li><a href="#http_event_connect_1">Event: 'connect'</a></li> <li><a href="#http_event_connection">Event: 'connection'</a></li> <li><a href="#http_event_request">Event: 'request'</a></li> <li><a href="#http_event_upgrade_1">Event: 'upgrade'</a></li> <li><a href="#http_server_close_callback">server.close([callback])</a></li> <li><a href="#http_server_listen"><code>server.listen()</code></a></li> <li><a href="#http_server_listening">server.listening</a></li> <li><a href="#http_server_maxheaderscount">server.maxHeadersCount</a></li> <li><a href="#http_server_headerstimeout">server.headersTimeout</a></li> <li><a href="#http_server_settimeout_msecs_callback">server.setTimeout([msecs][, callback])</a></li> <li><a href="#http_server_timeout">server.timeout</a></li> <li><a href="#http_server_keepalivetimeout">server.keepAliveTimeout</a></li> </ul> </li> <li> <p><a href="#http_class_http_serverresponse">Class: http.ServerResponse</a></p> <ul> <li><a href="#http_event_close_1">Event: 'close'</a></li> <li><a href="#http_event_finish">Event: 'finish'</a></li> <li><a href="#http_response_addtrailers_headers">response.addTrailers(headers)</a></li> <li><a href="#http_response_connection">response.connection</a></li> <li><a href="#http_response_end_data_encoding_callback">response.end([data][, encoding][, callback])</a></li> <li><a href="#http_response_finished">response.finished</a></li> <li><a href="#http_response_getheader_name">response.getHeader(name)</a></li> <li><a href="#http_response_getheadernames">response.getHeaderNames()</a></li> <li><a href="#http_response_getheaders">response.getHeaders()</a></li> <li><a href="#http_response_hasheader_name">response.hasHeader(name)</a></li> <li><a href="#http_response_headerssent">response.headersSent</a></li> <li><a href="#http_response_removeheader_name">response.removeHeader(name)</a></li> <li><a href="#http_response_senddate">response.sendDate</a></li> <li><a href="#http_response_setheader_name_value">response.setHeader(name, value)</a></li> <li><a href="#http_response_settimeout_msecs_callback">response.setTimeout(msecs[, callback])</a></li> <li><a href="#http_response_socket">response.socket</a></li> <li><a href="#http_response_statuscode">response.statusCode</a></li> <li><a href="#http_response_statusmessage">response.statusMessage</a></li> <li><a href="#http_response_write_chunk_encoding_callback">response.write(chunk[, encoding][, callback])</a></li> <li><a href="#http_response_writecontinue">response.writeContinue()</a></li> <li><a href="#http_response_writehead_statuscode_statusmessage_headers">response.writeHead(statusCode[, statusMessage][, headers])</a></li> <li><a href="#http_response_writeprocessing">response.writeProcessing()</a></li> </ul> </li> <li> <p><a href="#http_class_http_incomingmessage">Class: http.IncomingMessage</a></p> <ul> <li><a href="#http_event_aborted">Event: 'aborted'</a></li> <li><a href="#http_event_close_2">Event: 'close'</a></li> <li><a href="#http_message_aborted">message.aborted</a></li> <li><a href="#http_message_complete">message.complete</a></li> <li><a href="#http_message_destroy_error">message.destroy([error])</a></li> <li><a href="#http_message_headers">message.headers</a></li> <li><a href="#http_message_httpversion">message.httpVersion</a></li> <li><a href="#http_message_method">message.method</a></li> <li><a href="#http_message_rawheaders">message.rawHeaders</a></li> <li><a href="#http_message_rawtrailers">message.rawTrailers</a></li> <li><a href="#http_message_settimeout_msecs_callback">message.setTimeout(msecs, callback)</a></li> <li><a href="#http_message_socket">message.socket</a></li> <li><a href="#http_message_statuscode">message.statusCode</a></li> <li><a href="#http_message_statusmessage">message.statusMessage</a></li> <li><a href="#http_message_trailers">message.trailers</a></li> <li><a href="#http_message_url">message.url</a></li> </ul> </li> <li><a href="#http_http_methods">http.METHODS</a></li> <li><a href="#http_http_status_codes">http.STATUS_CODES</a></li> <li><a href="#http_http_createserver_options_requestlistener">http.createServer([options][, requestListener])</a></li> <li><a href="#http_http_get_options_callback">http.get(options[, callback])</a></li> <li><a href="#http_http_get_url_options_callback">http.get(url[, options][, callback])</a></li> <li><a href="#http_http_globalagent">http.globalAgent</a></li> <li><a href="#http_http_maxheadersize">http.maxHeaderSize</a></li> <li><a href="#http_http_request_options_callback">http.request(options[, callback])</a></li> <li><a href="#http_http_request_url_options_callback">http.request(url[, options][, callback])</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#http2_http_2">HTTP/2</a></span></p> <ul> <li> <p><a href="#http2_core_api">Core API</a></p> <ul> <li><a href="#http2_server_side_example">Server-side example</a></li> <li><a href="#http2_client_side_example">Client-side example</a></li> <li> <p><a href="#http2_class_http2session">Class: Http2Session</a></p> <ul> <li><a href="#http2_http2session_and_sockets">Http2Session and Sockets</a></li> <li><a href="#http2_event_close">Event: 'close'</a></li> <li><a href="#http2_event_connect">Event: 'connect'</a></li> <li><a href="#http2_event_error">Event: 'error'</a></li> <li><a href="#http2_event_frameerror">Event: 'frameError'</a></li> <li><a href="#http2_event_goaway">Event: 'goaway'</a></li> <li><a href="#http2_event_localsettings">Event: 'localSettings'</a></li> <li><a href="#http2_event_ping">Event: 'ping'</a></li> <li><a href="#http2_event_remotesettings">Event: 'remoteSettings'</a></li> <li><a href="#http2_event_stream">Event: 'stream'</a></li> <li><a href="#http2_event_timeout">Event: 'timeout'</a></li> <li><a href="#http2_http2session_alpnprotocol">http2session.alpnProtocol</a></li> <li><a href="#http2_http2session_close_callback">http2session.close([callback])</a></li> <li><a href="#http2_http2session_closed">http2session.closed</a></li> <li><a href="#http2_http2session_connecting">http2session.connecting</a></li> <li><a href="#http2_http2session_destroy_error_code">http2session.destroy([error][, code])</a></li> <li><a href="#http2_http2session_destroyed">http2session.destroyed</a></li> <li><a href="#http2_http2session_encrypted">http2session.encrypted</a></li> <li><a href="#http2_http2session_goaway_code_laststreamid_opaquedata">http2session.goaway([code[, lastStreamID[, opaqueData]]])</a></li> <li><a href="#http2_http2session_localsettings">http2session.localSettings</a></li> <li><a href="#http2_http2session_originset">http2session.originSet</a></li> <li><a href="#http2_http2session_pendingsettingsack">http2session.pendingSettingsAck</a></li> <li><a href="#http2_http2session_ping_payload_callback">http2session.ping([payload, ]callback)</a></li> <li><a href="#http2_http2session_ref">http2session.ref()</a></li> <li><a href="#http2_http2session_remotesettings">http2session.remoteSettings</a></li> <li><a href="#http2_http2session_settimeout_msecs_callback">http2session.setTimeout(msecs, callback)</a></li> <li><a href="#http2_http2session_socket">http2session.socket</a></li> <li><a href="#http2_http2session_state">http2session.state</a></li> <li><a href="#http2_http2session_settings_settings">http2session.settings(settings)</a></li> <li><a href="#http2_http2session_type">http2session.type</a></li> <li><a href="#http2_http2session_unref">http2session.unref()</a></li> </ul> </li> <li> <p><a href="#http2_class_serverhttp2session">Class: ServerHttp2Session</a></p> <ul> <li><a href="#http2_serverhttp2session_altsvc_alt_originorstream">serverhttp2session.altsvc(alt, originOrStream)</a></li> <li><a href="#http2_specifying_alternative_services">Specifying alternative services</a></li> <li><a href="#http2_serverhttp2session_origin_origins">serverhttp2session.origin(...origins)</a></li> </ul> </li> <li> <p><a href="#http2_class_clienthttp2session">Class: ClientHttp2Session</a></p> <ul> <li><a href="#http2_event_altsvc">Event: 'altsvc'</a></li> <li><a href="#http2_event_origin">Event: 'origin'</a></li> <li><a href="#http2_clienthttp2session_request_headers_options">clienthttp2session.request(headers[, options])</a></li> </ul> </li> <li> <p><a href="#http2_class_http2stream">Class: Http2Stream</a></p> <ul> <li> <p><a href="#http2_http2stream_lifecycle">Http2Stream Lifecycle</a></p> <ul> <li><a href="#http2_creation">Creation</a></li> <li><a href="#http2_destruction">Destruction</a></li> </ul> </li> <li><a href="#http2_event_aborted">Event: 'aborted'</a></li> <li><a href="#http2_event_close_1">Event: 'close'</a></li> <li><a href="#http2_event_error_1">Event: 'error'</a></li> <li><a href="#http2_event_frameerror_1">Event: 'frameError'</a></li> <li><a href="#http2_event_timeout_1">Event: 'timeout'</a></li> <li><a href="#http2_event_trailers">Event: 'trailers'</a></li> <li><a href="#http2_event_wanttrailers">Event: 'wantTrailers'</a></li> <li><a href="#http2_http2stream_aborted">http2stream.aborted</a></li> <li><a href="#http2_http2stream_buffersize">http2stream.bufferSize</a></li> <li><a href="#http2_http2stream_close_code_callback">http2stream.close(code[, callback])</a></li> <li><a href="#http2_http2stream_closed">http2stream.closed</a></li> <li><a href="#http2_http2stream_destroyed">http2stream.destroyed</a></li> <li><a href="#http2_http2stream_endafterheaders">http2stream.endAfterHeaders</a></li> <li><a href="#http2_http2stream_pending">http2stream.pending</a></li> <li><a href="#http2_http2stream_priority_options">http2stream.priority(options)</a></li> <li><a href="#http2_http2stream_rstcode">http2stream.rstCode</a></li> <li><a href="#http2_http2stream_sentheaders">http2stream.sentHeaders</a></li> <li><a href="#http2_http2stream_sentinfoheaders">http2stream.sentInfoHeaders</a></li> <li><a href="#http2_http2stream_senttrailers">http2stream.sentTrailers</a></li> <li><a href="#http2_http2stream_session">http2stream.session</a></li> <li><a href="#http2_http2stream_settimeout_msecs_callback">http2stream.setTimeout(msecs, callback)</a></li> <li><a href="#http2_http2stream_state">http2stream.state</a></li> <li><a href="#http2_http2stream_sendtrailers_headers">http2stream.sendTrailers(headers)</a></li> </ul> </li> <li> <p><a href="#http2_class_clienthttp2stream">Class: ClientHttp2Stream</a></p> <ul> <li><a href="#http2_event_continue">Event: 'continue'</a></li> <li><a href="#http2_event_headers">Event: 'headers'</a></li> <li><a href="#http2_event_push">Event: 'push'</a></li> <li><a href="#http2_event_response">Event: 'response'</a></li> </ul> </li> <li> <p><a href="#http2_class_serverhttp2stream">Class: ServerHttp2Stream</a></p> <ul> <li><a href="#http2_http2stream_additionalheaders_headers">http2stream.additionalHeaders(headers)</a></li> <li><a href="#http2_http2stream_headerssent">http2stream.headersSent</a></li> <li><a href="#http2_http2stream_pushallowed">http2stream.pushAllowed</a></li> <li><a href="#http2_http2stream_pushstream_headers_options_callback">http2stream.pushStream(headers[, options], callback)</a></li> <li><a href="#http2_http2stream_respond_headers_options">http2stream.respond([headers[, options]])</a></li> <li><a href="#http2_http2stream_respondwithfd_fd_headers_options">http2stream.respondWithFD(fd[, headers[, options]])</a></li> <li><a href="#http2_http2stream_respondwithfile_path_headers_options">http2stream.respondWithFile(path[, headers[, options]])</a></li> </ul> </li> <li> <p><a href="#http2_class_http2server">Class: Http2Server</a></p> <ul> <li><a href="#http2_event_checkcontinue">Event: 'checkContinue'</a></li> <li><a href="#http2_event_request">Event: 'request'</a></li> <li><a href="#http2_event_session">Event: 'session'</a></li> <li><a href="#http2_event_sessionerror">Event: 'sessionError'</a></li> <li><a href="#http2_event_stream_1">Event: 'stream'</a></li> <li><a href="#http2_event_timeout_2">Event: 'timeout'</a></li> <li><a href="#http2_server_close_callback">server.close([callback])</a></li> <li><a href="#http2_server_settimeout_msecs_callback">server.setTimeout([msecs][, callback])</a></li> </ul> </li> <li> <p><a href="#http2_class_http2secureserver">Class: Http2SecureServer</a></p> <ul> <li><a href="#http2_event_checkcontinue_1">Event: 'checkContinue'</a></li> <li><a href="#http2_event_request_1">Event: 'request'</a></li> <li><a href="#http2_event_session_1">Event: 'session'</a></li> <li><a href="#http2_event_sessionerror_1">Event: 'sessionError'</a></li> <li><a href="#http2_event_stream_2">Event: 'stream'</a></li> <li><a href="#http2_event_timeout_3">Event: 'timeout'</a></li> <li><a href="#http2_event_unknownprotocol">Event: 'unknownProtocol'</a></li> <li><a href="#http2_server_close_callback_1">server.close([callback])</a></li> <li><a href="#http2_server_settimeout_msecs_callback_1">server.setTimeout([msecs][, callback])</a></li> </ul> </li> <li><a href="#http2_http2_createserver_options_onrequesthandler">http2.createServer(options[, onRequestHandler])</a></li> <li><a href="#http2_http2_createsecureserver_options_onrequesthandler">http2.createSecureServer(options[, onRequestHandler])</a></li> <li><a href="#http2_http2_connect_authority_options_listener">http2.connect(authority[, options][, listener])</a></li> <li> <p><a href="#http2_http2_constants">http2.constants</a></p> <ul> <li><a href="#http2_error_codes_for_rst_stream_and_goaway">Error Codes for RST_STREAM and GOAWAY</a></li> </ul> </li> <li><a href="#http2_http2_getdefaultsettings">http2.getDefaultSettings()</a></li> <li><a href="#http2_http2_getpackedsettings_settings">http2.getPackedSettings(settings)</a></li> <li><a href="#http2_http2_getunpackedsettings_buf">http2.getUnpackedSettings(buf)</a></li> <li><a href="#http2_headers_object">Headers Object</a></li> <li><a href="#http2_settings_object">Settings Object</a></li> <li><a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a></li> <li><a href="#http2_error_handling">Error Handling</a></li> <li><a href="#http2_invalid_character_handling_in_header_names_and_values">Invalid character handling in header names and values</a></li> <li><a href="#http2_push_streams_on_the_client">Push streams on the client</a></li> <li><a href="#http2_supporting_the_connect_method">Supporting the CONNECT method</a></li> <li><a href="#http2_the_extended_connect_protocol">The Extended CONNECT Protocol</a></li> </ul> </li> <li> <p><a href="#http2_compatibility_api">Compatibility API</a></p> <ul> <li><a href="#http2_alpn_negotiation">ALPN negotiation</a></li> <li> <p><a href="#http2_class_http2_http2serverrequest">Class: http2.Http2ServerRequest</a></p> <ul> <li><a href="#http2_event_aborted_1">Event: 'aborted'</a></li> <li><a href="#http2_event_close_2">Event: 'close'</a></li> <li><a href="#http2_request_aborted">request.aborted</a></li> <li><a href="#http2_request_authority">request.authority</a></li> <li><a href="#http2_request_destroy_error">request.destroy([error])</a></li> <li><a href="#http2_request_headers">request.headers</a></li> <li><a href="#http2_request_httpversion">request.httpVersion</a></li> <li><a href="#http2_request_method">request.method</a></li> <li><a href="#http2_request_rawheaders">request.rawHeaders</a></li> <li><a href="#http2_request_rawtrailers">request.rawTrailers</a></li> <li><a href="#http2_request_scheme">request.scheme</a></li> <li><a href="#http2_request_settimeout_msecs_callback">request.setTimeout(msecs, callback)</a></li> <li><a href="#http2_request_socket">request.socket</a></li> <li><a href="#http2_request_stream">request.stream</a></li> <li><a href="#http2_request_trailers">request.trailers</a></li> <li><a href="#http2_request_url">request.url</a></li> </ul> </li> <li> <p><a href="#http2_class_http2_http2serverresponse">Class: http2.Http2ServerResponse</a></p> <ul> <li><a href="#http2_event_close_3">Event: 'close'</a></li> <li><a href="#http2_event_finish">Event: 'finish'</a></li> <li><a href="#http2_response_addtrailers_headers">response.addTrailers(headers)</a></li> <li><a href="#http2_response_connection">response.connection</a></li> <li><a href="#http2_response_end_data_encoding_callback">response.end([data][, encoding][, callback])</a></li> <li><a href="#http2_response_finished">response.finished</a></li> <li><a href="#http2_response_getheader_name">response.getHeader(name)</a></li> <li><a href="#http2_response_getheadernames">response.getHeaderNames()</a></li> <li><a href="#http2_response_getheaders">response.getHeaders()</a></li> <li><a href="#http2_response_hasheader_name">response.hasHeader(name)</a></li> <li><a href="#http2_response_headerssent">response.headersSent</a></li> <li><a href="#http2_response_removeheader_name">response.removeHeader(name)</a></li> <li><a href="#http2_response_senddate">response.sendDate</a></li> <li><a href="#http2_response_setheader_name_value">response.setHeader(name, value)</a></li> <li><a href="#http2_response_settimeout_msecs_callback">response.setTimeout(msecs[, callback])</a></li> <li><a href="#http2_response_socket">response.socket</a></li> <li><a href="#http2_response_statuscode">response.statusCode</a></li> <li><a href="#http2_response_statusmessage">response.statusMessage</a></li> <li><a href="#http2_response_stream">response.stream</a></li> <li><a href="#http2_response_write_chunk_encoding_callback">response.write(chunk[, encoding][, callback])</a></li> <li><a href="#http2_response_writecontinue">response.writeContinue()</a></li> <li><a href="#http2_response_writehead_statuscode_statusmessage_headers">response.writeHead(statusCode[, statusMessage][, headers])</a></li> <li><a href="#http2_response_createpushresponse_headers_callback">response.createPushResponse(headers, callback)</a></li> </ul> </li> </ul> </li> <li><a href="#http2_collecting_http_2_performance_metrics">Collecting HTTP/2 Performance Metrics</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#https_https">HTTPS</a></span></p> <ul> <li><a href="#https_class_https_agent">Class: https.Agent</a></li> <li> <p><a href="#https_class_https_server">Class: https.Server</a></p> <ul> <li><a href="#https_server_close_callback">server.close([callback])</a></li> <li><a href="#https_server_listen">server.listen()</a></li> <li><a href="#https_server_maxheaderscount">server.maxHeadersCount</a></li> <li><a href="#https_server_headerstimeout">server.headersTimeout</a></li> <li><a href="#https_server_settimeout_msecs_callback">server.setTimeout([msecs][, callback])</a></li> <li><a href="#https_server_timeout">server.timeout</a></li> <li><a href="#https_server_keepalivetimeout">server.keepAliveTimeout</a></li> </ul> </li> <li><a href="#https_https_createserver_options_requestlistener">https.createServer([options][, requestListener])</a></li> <li><a href="#https_https_get_options_callback">https.get(options[, callback])</a></li> <li><a href="#https_https_get_url_options_callback">https.get(url[, options][, callback])</a></li> <li><a href="#https_https_globalagent">https.globalAgent</a></li> <li><a href="#https_https_request_options_callback">https.request(options[, callback])</a></li> <li><a href="#https_https_request_url_options_callback">https.request(url[, options][, callback])</a></li> </ul> </li> <li> <p><span class="stability_1"><a href="#inspector_inspector">Inspector</a></span></p> <ul> <li><a href="#inspector_inspector_close">inspector.close()</a></li> <li><a href="#inspector_inspector_console">inspector.console</a></li> <li><a href="#inspector_inspector_open_port_host_wait">inspector.open([port[, host[, wait]]])</a></li> <li><a href="#inspector_inspector_url">inspector.url()</a></li> <li> <p><a href="#inspector_class_inspector_session">Class: inspector.Session</a></p> <ul> <li><a href="#inspector_constructor_new_inspector_session">Constructor: new inspector.Session()</a></li> <li><a href="#inspector_event_inspectornotification">Event: 'inspectorNotification'</a></li> <li><a href="#inspector_event_lt_inspector_protocol_method_gt">Event: <inspector-protocol-method></a></li> <li><a href="#inspector_session_connect">session.connect()</a></li> <li><a href="#inspector_session_disconnect">session.disconnect()</a></li> <li><a href="#inspector_session_post_method_params_callback">session.post(method[, params][, callback])</a></li> </ul> </li> <li> <p><a href="#inspector_example_usage">Example usage</a></p> <ul> <li><a href="#inspector_cpu_profiler">CPU Profiler</a></li> <li><a href="#inspector_heap_profiler">Heap Profiler</a></li> </ul> </li> </ul> </li> <li> <p><a href="#intl_internationalization_support">Internationalization Support</a></p> <ul> <li> <p><a href="#intl_options_for_building_node_js">Options for building Node.js</a></p> <ul> <li><a href="#intl_disable_all_internationalization_features_none">Disable all internationalization features (<code>none</code>)</a></li> <li><a href="#intl_build_with_a_pre_installed_icu_system_icu">Build with a pre-installed ICU (<code>system-icu</code>)</a></li> <li> <p><a href="#intl_embed_a_limited_set_of_icu_data_small_icu">Embed a limited set of ICU data (<code>small-icu</code>)</a></p> <ul> <li><a href="#intl_providing_icu_data_at_runtime">Providing ICU data at runtime</a></li> </ul> </li> <li><a href="#intl_embed_the_entire_icu_full_icu">Embed the entire ICU (<code>full-icu</code>)</a></li> </ul> </li> <li><a href="#intl_detecting_internationalization_support">Detecting internationalization support</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#modules_modules">Modules</a></span></p> <ul> <li><a href="#modules_accessing_the_main_module">Accessing the main module</a></li> <li><a href="#modules_addenda_package_manager_tips">Addenda: Package Manager Tips</a></li> <li><a href="#modules_all_together">All Together...</a></li> <li> <p><a href="#modules_caching">Caching</a></p> <ul> <li><a href="#modules_module_caching_caveats">Module Caching Caveats</a></li> </ul> </li> <li><a href="#modules_core_modules">Core Modules</a></li> <li><a href="#modules_cycles">Cycles</a></li> <li><a href="#modules_file_modules">File Modules</a></li> <li><a href="#modules_folders_as_modules">Folders as Modules</a></li> <li><a href="#modules_loading_from_node_modules_folders">Loading from <code>node_modules</code> Folders</a></li> <li><a href="#modules_loading_from_the_global_folders">Loading from the global folders</a></li> <li><a href="#modules_the_module_wrapper">The module wrapper</a></li> <li> <p><a href="#modules_the_module_scope">The module scope</a></p> <ul> <li><a href="#modules_dirname">__dirname</a></li> <li><a href="#modules_filename">__filename</a></li> <li><a href="#modules_exports">exports</a></li> <li><a href="#modules_module">module</a></li> <li> <p><a href="#modules_require">require()</a></p> <ul> <li><a href="#modules_require_cache">require.cache</a></li> <li><span class="stability_0"><a href="#modules_require_extensions">require.extensions</a></span></li> <li><a href="#modules_require_main">require.main</a></li> <li><a href="#modules_require_resolve_request_options">require.resolve(request[, options])</a></li> <li><a href="#modules_require_resolve_paths_request">require.resolve.paths(request)</a></li> </ul> </li> </ul> </li> <li> <p><a href="#modules_the_module_object">The <code>module</code> Object</a></p> <ul> <li><a href="#modules_module_children">module.children</a></li> <li> <p><a href="#modules_module_exports">module.exports</a></p> <ul> <li><a href="#modules_exports_shortcut">exports shortcut</a></li> </ul> </li> <li><a href="#modules_module_filename">module.filename</a></li> <li><a href="#modules_module_id">module.id</a></li> <li><a href="#modules_module_loaded">module.loaded</a></li> <li><a href="#modules_module_parent">module.parent</a></li> <li><a href="#modules_module_paths">module.paths</a></li> <li><a href="#modules_module_require_id">module.require(id)</a></li> </ul> </li> <li> <p><a href="#modules_the_module_object_1">The <code>Module</code> Object</a></p> <ul> <li><a href="#modules_module_builtinmodules">module.builtinModules</a></li> <li><a href="#modules_module_createrequirefrompath_filename">module.createRequireFromPath(filename)</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#net_net">Net</a></span></p> <ul> <li> <p><a href="#net_ipc_support">IPC Support</a></p> <ul> <li><a href="#net_identifying_paths_for_ipc_connections">Identifying paths for IPC connections</a></li> </ul> </li> <li> <p><a href="#net_class_net_server">Class: net.Server</a></p> <ul> <li><a href="#net_new_net_server_options_connectionlistener">new net.Server([options][, connectionListener])</a></li> <li><a href="#net_event_close">Event: 'close'</a></li> <li><a href="#net_event_connection">Event: 'connection'</a></li> <li><a href="#net_event_error">Event: 'error'</a></li> <li><a href="#net_event_listening">Event: 'listening'</a></li> <li><a href="#net_server_address">server.address()</a></li> <li><a href="#net_server_close_callback">server.close([callback])</a></li> <li><span class="stability_0"><a href="#net_server_connections">server.connections</a></span></li> <li><a href="#net_server_getconnections_callback">server.getConnections(callback)</a></li> <li> <p><a href="#net_server_listen">server.listen()</a></p> <ul> <li><a href="#net_server_listen_handle_backlog_callback">server.listen(handle[, backlog][, callback])</a></li> <li><a href="#net_server_listen_options_callback">server.listen(options[, callback])</a></li> <li><a href="#net_server_listen_path_backlog_callback">server.listen(path[, backlog][, callback])</a></li> <li><a href="#net_server_listen_port_host_backlog_callback">server.listen([port[, host[, backlog]]][, callback])</a></li> </ul> </li> <li><a href="#net_server_listening">server.listening</a></li> <li><a href="#net_server_maxconnections">server.maxConnections</a></li> <li><a href="#net_server_ref">server.ref()</a></li> <li><a href="#net_server_unref">server.unref()</a></li> </ul> </li> <li> <p><a href="#net_class_net_socket">Class: net.Socket</a></p> <ul> <li><a href="#net_new_net_socket_options">new net.Socket([options])</a></li> <li><a href="#net_event_close_1">Event: 'close'</a></li> <li><a href="#net_event_connect">Event: 'connect'</a></li> <li><a href="#net_event_data">Event: 'data'</a></li> <li><a href="#net_event_drain">Event: 'drain'</a></li> <li><a href="#net_event_end">Event: 'end'</a></li> <li><a href="#net_event_error_1">Event: 'error'</a></li> <li><a href="#net_event_lookup">Event: 'lookup'</a></li> <li><a href="#net_event_ready">Event: 'ready'</a></li> <li><a href="#net_event_timeout">Event: 'timeout'</a></li> <li><a href="#net_socket_address">socket.address()</a></li> <li><a href="#net_socket_buffersize">socket.bufferSize</a></li> <li><a href="#net_socket_bytesread">socket.bytesRead</a></li> <li><a href="#net_socket_byteswritten">socket.bytesWritten</a></li> <li> <p><a href="#net_socket_connect">socket.connect()</a></p> <ul> <li><a href="#net_socket_connect_options_connectlistener">socket.connect(options[, connectListener])</a></li> <li><a href="#net_socket_connect_path_connectlistener">socket.connect(path[, connectListener])</a></li> <li><a href="#net_socket_connect_port_host_connectlistener">socket.connect(port[, host][, connectListener])</a></li> </ul> </li> <li><a href="#net_socket_connecting">socket.connecting</a></li> <li><a href="#net_socket_destroy_exception">socket.destroy([exception])</a></li> <li><a href="#net_socket_destroyed">socket.destroyed</a></li> <li><a href="#net_socket_end_data_encoding_callback">socket.end([data][, encoding][, callback])</a></li> <li><a href="#net_socket_localaddress">socket.localAddress</a></li> <li><a href="#net_socket_localport">socket.localPort</a></li> <li><a href="#net_socket_pause">socket.pause()</a></li> <li><a href="#net_socket_pending">socket.pending</a></li> <li><a href="#net_socket_ref">socket.ref()</a></li> <li><a href="#net_socket_remoteaddress">socket.remoteAddress</a></li> <li><a href="#net_socket_remotefamily">socket.remoteFamily</a></li> <li><a href="#net_socket_remoteport">socket.remotePort</a></li> <li><a href="#net_socket_resume">socket.resume()</a></li> <li><a href="#net_socket_setencoding_encoding">socket.setEncoding([encoding])</a></li> <li><a href="#net_socket_setkeepalive_enable_initialdelay">socket.setKeepAlive([enable][, initialDelay])</a></li> <li><a href="#net_socket_setnodelay_nodelay">socket.setNoDelay([noDelay])</a></li> <li><a href="#net_socket_settimeout_timeout_callback">socket.setTimeout(timeout[, callback])</a></li> <li><a href="#net_socket_unref">socket.unref()</a></li> <li><a href="#net_socket_write_data_encoding_callback">socket.write(data[, encoding][, callback])</a></li> </ul> </li> <li> <p><a href="#net_net_connect">net.connect()</a></p> <ul> <li><a href="#net_net_connect_options_connectlistener">net.connect(options[, connectListener])</a></li> <li><a href="#net_net_connect_path_connectlistener">net.connect(path[, connectListener])</a></li> <li><a href="#net_net_connect_port_host_connectlistener">net.connect(port[, host][, connectListener])</a></li> </ul> </li> <li> <p><a href="#net_net_createconnection">net.createConnection()</a></p> <ul> <li><a href="#net_net_createconnection_options_connectlistener">net.createConnection(options[, connectListener])</a></li> <li><a href="#net_net_createconnection_path_connectlistener">net.createConnection(path[, connectListener])</a></li> <li><a href="#net_net_createconnection_port_host_connectlistener">net.createConnection(port[, host][, connectListener])</a></li> </ul> </li> <li><a href="#net_net_createserver_options_connectionlistener">net.createServer([options][, connectionListener])</a></li> <li><a href="#net_net_isip_input">net.isIP(input)</a></li> <li><a href="#net_net_isipv4_input">net.isIPv4(input)</a></li> <li><a href="#net_net_isipv6_input">net.isIPv6(input)</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#os_os">OS</a></span></p> <ul> <li><a href="#os_os_eol">os.EOL</a></li> <li><a href="#os_os_arch">os.arch()</a></li> <li><a href="#os_os_constants">os.constants</a></li> <li><a href="#os_os_cpus">os.cpus()</a></li> <li><a href="#os_os_endianness">os.endianness()</a></li> <li><a href="#os_os_freemem">os.freemem()</a></li> <li><a href="#os_os_getpriority_pid">os.getPriority([pid])</a></li> <li><a href="#os_os_homedir">os.homedir()</a></li> <li><a href="#os_os_hostname">os.hostname()</a></li> <li><a href="#os_os_loadavg">os.loadavg()</a></li> <li><a href="#os_os_networkinterfaces">os.networkInterfaces()</a></li> <li><a href="#os_os_platform">os.platform()</a></li> <li><a href="#os_os_release">os.release()</a></li> <li><a href="#os_os_setpriority_pid_priority">os.setPriority([pid, ]priority)</a></li> <li><a href="#os_os_tmpdir">os.tmpdir()</a></li> <li><a href="#os_os_totalmem">os.totalmem()</a></li> <li><a href="#os_os_type">os.type()</a></li> <li><a href="#os_os_uptime">os.uptime()</a></li> <li><a href="#os_os_userinfo_options">os.userInfo([options])</a></li> <li> <p><a href="#os_os_constants_1">OS Constants</a></p> <ul> <li><a href="#os_signal_constants">Signal Constants</a></li> <li> <p><a href="#os_error_constants">Error Constants</a></p> <ul> <li><a href="#os_posix_error_constants">POSIX Error Constants</a></li> <li><a href="#os_windows_specific_error_constants">Windows Specific Error Constants</a></li> </ul> </li> <li><a href="#os_dlopen_constants">dlopen Constants</a></li> <li><a href="#os_priority_constants">Priority Constants</a></li> <li><a href="#os_libuv_constants">libuv Constants</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#path_path">Path</a></span></p> <ul> <li><a href="#path_windows_vs_posix">Windows vs. POSIX</a></li> <li><a href="#path_path_basename_path_ext">path.basename(path[, ext])</a></li> <li><a href="#path_path_delimiter">path.delimiter</a></li> <li><a href="#path_path_dirname_path">path.dirname(path)</a></li> <li><a href="#path_path_extname_path">path.extname(path)</a></li> <li><a href="#path_path_format_pathobject">path.format(pathObject)</a></li> <li><a href="#path_path_isabsolute_path">path.isAbsolute(path)</a></li> <li><a href="#path_path_join_paths">path.join([...paths])</a></li> <li><a href="#path_path_normalize_path">path.normalize(path)</a></li> <li><a href="#path_path_parse_path">path.parse(path)</a></li> <li><a href="#path_path_posix">path.posix</a></li> <li><a href="#path_path_relative_from_to">path.relative(from, to)</a></li> <li><a href="#path_path_resolve_paths">path.resolve([...paths])</a></li> <li><a href="#path_path_sep">path.sep</a></li> <li><a href="#path_path_tonamespacedpath_path">path.toNamespacedPath(path)</a></li> <li><a href="#path_path_win32">path.win32</a></li> </ul> </li> <li> <p><span class="stability_1"><a href="#perf_hooks_performance_timing_api">Performance Timing API</a></span></p> <ul> <li> <p><a href="#perf_hooks_class_performance">Class: Performance</a></p> <ul> <li><a href="#perf_hooks_performance_clearmarks_name">performance.clearMarks([name])</a></li> <li><a href="#perf_hooks_performance_mark_name">performance.mark([name])</a></li> <li><a href="#perf_hooks_performance_measure_name_startmark_endmark">performance.measure(name, startMark, endMark)</a></li> <li><a href="#perf_hooks_performance_nodetiming">performance.nodeTiming</a></li> <li><a href="#perf_hooks_performance_now">performance.now()</a></li> <li><a href="#perf_hooks_performance_timeorigin">performance.timeOrigin</a></li> <li><a href="#perf_hooks_performance_timerify_fn">performance.timerify(fn)</a></li> </ul> </li> <li> <p><a href="#perf_hooks_class_performanceentry">Class: PerformanceEntry</a></p> <ul> <li><a href="#perf_hooks_performanceentry_duration">performanceEntry.duration</a></li> <li><a href="#perf_hooks_performanceentry_name">performanceEntry.name</a></li> <li><a href="#perf_hooks_performanceentry_starttime">performanceEntry.startTime</a></li> <li><a href="#perf_hooks_performanceentry_entrytype">performanceEntry.entryType</a></li> <li><a href="#perf_hooks_performanceentry_kind">performanceEntry.kind</a></li> </ul> </li> <li> <p><a href="#perf_hooks_class_performancenodetiming_extends_performanceentry">Class: PerformanceNodeTiming extends PerformanceEntry</a></p> <ul> <li><a href="#perf_hooks_performancenodetiming_bootstrapcomplete">performanceNodeTiming.bootstrapComplete</a></li> <li><a href="#perf_hooks_performancenodetiming_loopexit">performanceNodeTiming.loopExit</a></li> <li><a href="#perf_hooks_performancenodetiming_loopstart">performanceNodeTiming.loopStart</a></li> <li><a href="#perf_hooks_performancenodetiming_nodestart">performanceNodeTiming.nodeStart</a></li> <li><a href="#perf_hooks_performancenodetiming_v8start">performanceNodeTiming.v8Start</a></li> </ul> </li> <li> <p><a href="#perf_hooks_class_performanceobserver">Class: PerformanceObserver</a></p> <ul> <li><a href="#perf_hooks_new_performanceobserver_callback">new PerformanceObserver(callback)</a></li> <li><a href="#perf_hooks_performanceobserver_disconnect">performanceObserver.disconnect()</a></li> <li><a href="#perf_hooks_performanceobserver_observe_options">performanceObserver.observe(options)</a></li> </ul> </li> <li> <p><a href="#perf_hooks_class_performanceobserverentrylist">Class: PerformanceObserverEntryList</a></p> <ul> <li><a href="#perf_hooks_performanceobserverentrylist_getentries">performanceObserverEntryList.getEntries()</a></li> <li><a href="#perf_hooks_performanceobserverentrylist_getentriesbyname_name_type">performanceObserverEntryList.getEntriesByName(name[, type])</a></li> <li><a href="#perf_hooks_performanceobserverentrylist_getentriesbytype_type">performanceObserverEntryList.getEntriesByType(type)</a></li> </ul> </li> <li> <p><a href="#perf_hooks_examples">Examples</a></p> <ul> <li><a href="#perf_hooks_measuring_the_duration_of_async_operations">Measuring the duration of async operations</a></li> <li><a href="#perf_hooks_measuring_how_long_it_takes_to_load_dependencies">Measuring how long it takes to load dependencies</a></li> </ul> </li> </ul> </li> <li> <p><a href="#process_process">Process</a></p> <ul> <li> <p><a href="#process_process_events">Process Events</a></p> <ul> <li><a href="#process_event_beforeexit">Event: 'beforeExit'</a></li> <li><a href="#process_event_disconnect">Event: 'disconnect'</a></li> <li><a href="#process_event_exit">Event: 'exit'</a></li> <li><a href="#process_event_message">Event: 'message'</a></li> <li><a href="#process_event_multipleresolves">Event: 'multipleResolves'</a></li> <li><a href="#process_event_rejectionhandled">Event: 'rejectionHandled'</a></li> <li> <p><a href="#process_event_uncaughtexception">Event: 'uncaughtException'</a></p> <ul> <li><a href="#process_warning_using_uncaughtexception_correctly">Warning: Using <code>'uncaughtException'</code> correctly</a></li> </ul> </li> <li><a href="#process_event_unhandledrejection">Event: 'unhandledRejection'</a></li> <li> <p><a href="#process_event_warning">Event: 'warning'</a></p> <ul> <li><a href="#process_emitting_custom_warnings">Emitting custom warnings</a></li> </ul> </li> <li><a href="#process_signal_events">Signal Events</a></li> </ul> </li> <li><a href="#process_process_abort">process.abort()</a></li> <li><a href="#process_process_allowednodeenvironmentflags">process.allowedNodeEnvironmentFlags</a></li> <li><a href="#process_process_arch">process.arch</a></li> <li><a href="#process_process_argv">process.argv</a></li> <li><a href="#process_process_argv0">process.argv0</a></li> <li><a href="#process_process_channel">process.channel</a></li> <li><a href="#process_process_chdir_directory">process.chdir(directory)</a></li> <li><a href="#process_process_config">process.config</a></li> <li><a href="#process_process_connected">process.connected</a></li> <li><a href="#process_process_cpuusage_previousvalue">process.cpuUsage([previousValue])</a></li> <li><a href="#process_process_cwd">process.cwd()</a></li> <li><a href="#process_process_debugport">process.debugPort</a></li> <li><a href="#process_process_disconnect">process.disconnect()</a></li> <li><a href="#process_process_dlopen_module_filename_flags">process.dlopen(module, filename[, flags])</a></li> <li><a href="#process_process_emitwarning_warning_options">process.emitWarning(warning[, options])</a></li> <li> <p><a href="#process_process_emitwarning_warning_type_code_ctor">process.emitWarning(warning[, type[, code]][, ctor])</a></p> <ul> <li><a href="#process_avoiding_duplicate_warnings">Avoiding duplicate warnings</a></li> </ul> </li> <li><a href="#process_process_env">process.env</a></li> <li><a href="#process_process_execargv">process.execArgv</a></li> <li><a href="#process_process_execpath">process.execPath</a></li> <li><a href="#process_process_exit_code">process.exit([code])</a></li> <li><a href="#process_process_exitcode">process.exitCode</a></li> <li><a href="#process_process_getegid">process.getegid()</a></li> <li><a href="#process_process_geteuid">process.geteuid()</a></li> <li><a href="#process_process_getgid">process.getgid()</a></li> <li><a href="#process_process_getgroups">process.getgroups()</a></li> <li><a href="#process_process_getuid">process.getuid()</a></li> <li><a href="#process_process_hasuncaughtexceptioncapturecallback">process.hasUncaughtExceptionCaptureCallback()</a></li> <li><a href="#process_process_hrtime_time">process.hrtime([time])</a></li> <li><a href="#process_process_hrtime_bigint">process.hrtime.bigint()</a></li> <li><a href="#process_process_initgroups_user_extragroup">process.initgroups(user, extraGroup)</a></li> <li><a href="#process_process_kill_pid_signal">process.kill(pid[, signal])</a></li> <li><a href="#process_process_mainmodule">process.mainModule</a></li> <li><a href="#process_process_memoryusage">process.memoryUsage()</a></li> <li><a href="#process_process_nexttick_callback_args">process.nextTick(callback[, ...args])</a></li> <li><a href="#process_process_nodeprecation">process.noDeprecation</a></li> <li><a href="#process_process_pid">process.pid</a></li> <li><a href="#process_process_platform">process.platform</a></li> <li><a href="#process_process_ppid">process.ppid</a></li> <li><a href="#process_process_release">process.release</a></li> <li><a href="#process_process_send_message_sendhandle_options_callback">process.send(message[, sendHandle[, options]][, callback])</a></li> <li><a href="#process_process_setegid_id">process.setegid(id)</a></li> <li><a href="#process_process_seteuid_id">process.seteuid(id)</a></li> <li><a href="#process_process_setgid_id">process.setgid(id)</a></li> <li><a href="#process_process_setgroups_groups">process.setgroups(groups)</a></li> <li><a href="#process_process_setuid_id">process.setuid(id)</a></li> <li><a href="#process_process_setuncaughtexceptioncapturecallback_fn">process.setUncaughtExceptionCaptureCallback(fn)</a></li> <li><a href="#process_process_stderr">process.stderr</a></li> <li><a href="#process_process_stdin">process.stdin</a></li> <li> <p><a href="#process_process_stdout">process.stdout</a></p> <ul> <li><a href="#process_a_note_on_process_i_o">A note on process I/O</a></li> </ul> </li> <li><a href="#process_process_throwdeprecation">process.throwDeprecation</a></li> <li><a href="#process_process_title">process.title</a></li> <li><a href="#process_process_tracedeprecation">process.traceDeprecation</a></li> <li><a href="#process_process_umask_mask">process.umask([mask])</a></li> <li><a href="#process_process_uptime">process.uptime()</a></li> <li><a href="#process_process_version">process.version</a></li> <li><a href="#process_process_versions">process.versions</a></li> <li><a href="#process_exit_codes">Exit Codes</a></li> </ul> </li> <li> <p><span class="stability_0"><a href="#punycode_punycode">Punycode</a></span></p> <ul> <li><a href="#punycode_punycode_decode_string">punycode.decode(string)</a></li> <li><a href="#punycode_punycode_encode_string">punycode.encode(string)</a></li> <li><a href="#punycode_punycode_toascii_domain">punycode.toASCII(domain)</a></li> <li><a href="#punycode_punycode_tounicode_domain">punycode.toUnicode(domain)</a></li> <li> <p><a href="#punycode_punycode_ucs2">punycode.ucs2</a></p> <ul> <li><a href="#punycode_punycode_ucs2_decode_string">punycode.ucs2.decode(string)</a></li> <li><a href="#punycode_punycode_ucs2_encode_codepoints">punycode.ucs2.encode(codePoints)</a></li> </ul> </li> <li><a href="#punycode_punycode_version">punycode.version</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#querystring_query_string">Query String</a></span></p> <ul> <li><a href="#querystring_querystring_decode">querystring.decode()</a></li> <li><a href="#querystring_querystring_encode">querystring.encode()</a></li> <li><a href="#querystring_querystring_escape_str">querystring.escape(str)</a></li> <li><a href="#querystring_querystring_parse_str_sep_eq_options">querystring.parse(str[, sep[, eq[, options]]])</a></li> <li><a href="#querystring_querystring_stringify_obj_sep_eq_options">querystring.stringify(obj[, sep[, eq[, options]]])</a></li> <li><a href="#querystring_querystring_unescape_str">querystring.unescape(str)</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#readline_readline">Readline</a></span></p> <ul> <li> <p><a href="#readline_class_interface">Class: Interface</a></p> <ul> <li><a href="#readline_event_close">Event: 'close'</a></li> <li><a href="#readline_event_line">Event: 'line'</a></li> <li><a href="#readline_event_pause">Event: 'pause'</a></li> <li><a href="#readline_event_resume">Event: 'resume'</a></li> <li><a href="#readline_event_sigcont">Event: 'SIGCONT'</a></li> <li><a href="#readline_event_sigint">Event: 'SIGINT'</a></li> <li><a href="#readline_event_sigtstp">Event: 'SIGTSTP'</a></li> <li><a href="#readline_rl_close">rl.close()</a></li> <li><a href="#readline_rl_pause">rl.pause()</a></li> <li><a href="#readline_rl_prompt_preservecursor">rl.prompt([preserveCursor])</a></li> <li><a href="#readline_rl_question_query_callback">rl.question(query, callback)</a></li> <li><a href="#readline_rl_resume">rl.resume()</a></li> <li><a href="#readline_rl_setprompt_prompt">rl.setPrompt(prompt)</a></li> <li><a href="#readline_rl_write_data_key">rl.write(data[, key])</a></li> <li><span class="stability_2"><a href="#readline_rl_symbol_asynciterator">rl[Symbol.asyncIterator]()</a></span></li> </ul> </li> <li><a href="#readline_readline_clearline_stream_dir">readline.clearLine(stream, dir)</a></li> <li><a href="#readline_readline_clearscreendown_stream">readline.clearScreenDown(stream)</a></li> <li> <p><a href="#readline_readline_createinterface_options">readline.createInterface(options)</a></p> <ul> <li><a href="#readline_use_of_the_completer_function">Use of the <code>completer</code> Function</a></li> </ul> </li> <li><a href="#readline_readline_cursorto_stream_x_y">readline.cursorTo(stream, x, y)</a></li> <li><a href="#readline_readline_emitkeypressevents_stream_interface">readline.emitKeypressEvents(stream[, interface])</a></li> <li><a href="#readline_readline_movecursor_stream_dx_dy">readline.moveCursor(stream, dx, dy)</a></li> <li><a href="#readline_example_tiny_cli">Example: Tiny CLI</a></li> <li><a href="#readline_example_read_file_stream_line_by_line">Example: Read File Stream Line-by-Line</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#repl_repl">REPL</a></span></p> <ul> <li> <p><a href="#repl_design_and_features">Design and Features</a></p> <ul> <li><a href="#repl_commands_and_special_keys">Commands and Special Keys</a></li> <li> <p><a href="#repl_default_evaluation">Default Evaluation</a></p> <ul> <li><a href="#repl_javascript_expressions">JavaScript Expressions</a></li> <li><a href="#repl_global_and_local_scope">Global and Local Scope</a></li> <li><a href="#repl_accessing_core_node_js_modules">Accessing Core Node.js Modules</a></li> <li><a href="#repl_global_uncaught_exceptions">Global Uncaught Exceptions</a></li> <li><a href="#repl_assignment_of_the_underscore_variable">Assignment of the <code>_</code> (underscore) variable</a></li> <li><a href="#repl_await_keyword"><code>await</code> keyword</a></li> </ul> </li> <li> <p><a href="#repl_custom_evaluation_functions">Custom Evaluation Functions</a></p> <ul> <li><a href="#repl_recoverable_errors">Recoverable Errors</a></li> </ul> </li> <li><a href="#repl_customizing_repl_output">Customizing REPL Output</a></li> </ul> </li> <li> <p><a href="#repl_class_replserver">Class: REPLServer</a></p> <ul> <li><a href="#repl_event_exit">Event: 'exit'</a></li> <li><a href="#repl_event_reset">Event: 'reset'</a></li> <li><a href="#repl_replserver_definecommand_keyword_cmd">replServer.defineCommand(keyword, cmd)</a></li> <li><a href="#repl_replserver_displayprompt_preservecursor">replServer.displayPrompt([preserveCursor])</a></li> <li><a href="#repl_replserver_clearbufferedcommand">replServer.clearBufferedCommand()</a></li> <li><span class="stability_0"><a href="#repl_replserver_parsereplkeyword_keyword_rest">replServer.parseREPLKeyword(keyword[, rest])</a></span></li> </ul> </li> <li><a href="#repl_repl_start_options">repl.start([options])</a></li> <li> <p><a href="#repl_the_node_js_repl">The Node.js REPL</a></p> <ul> <li><a href="#repl_environment_variable_options">Environment Variable Options</a></li> <li><a href="#repl_persistent_history">Persistent History</a></li> <li><a href="#repl_using_the_node_js_repl_with_advanced_line_editors">Using the Node.js REPL with advanced line-editors</a></li> <li><a href="#repl_starting_multiple_repl_instances_against_a_single_running_instance">Starting multiple REPL instances against a single running instance</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#stream_stream">Stream</a></span></p> <ul> <li><a href="#stream_organization_of_this_document">Organization of this Document</a></li> <li> <p><a href="#stream_types_of_streams">Types of Streams</a></p> <ul> <li><a href="#stream_object_mode">Object Mode</a></li> <li><a href="#stream_buffering">Buffering</a></li> </ul> </li> <li> <p><a href="#stream_api_for_stream_consumers">API for Stream Consumers</a></p> <ul> <li> <p><a href="#stream_writable_streams">Writable Streams</a></p> <ul> <li> <p><a href="#stream_class_stream_writable">Class: stream.Writable</a></p> <ul> <li><a href="#stream_event_close">Event: 'close'</a></li> <li><a href="#stream_event_drain">Event: 'drain'</a></li> <li><a href="#stream_event_error">Event: 'error'</a></li> <li><a href="#stream_event_finish">Event: 'finish'</a></li> <li><a href="#stream_event_pipe">Event: 'pipe'</a></li> <li><a href="#stream_event_unpipe">Event: 'unpipe'</a></li> <li><a href="#stream_writable_cork">writable.cork()</a></li> <li><a href="#stream_writable_destroy_error">writable.destroy([error])</a></li> <li><a href="#stream_writable_end_chunk_encoding_callback">writable.end([chunk][, encoding][, callback])</a></li> <li><a href="#stream_writable_setdefaultencoding_encoding">writable.setDefaultEncoding(encoding)</a></li> <li><a href="#stream_writable_uncork">writable.uncork()</a></li> <li><a href="#stream_writable_writable">writable.writable</a></li> <li><a href="#stream_writable_writablehighwatermark">writable.writableHighWaterMark</a></li> <li><a href="#stream_writable_writablelength">writable.writableLength</a></li> <li><a href="#stream_writable_write_chunk_encoding_callback">writable.write(chunk[, encoding][, callback])</a></li> </ul> </li> </ul> </li> <li> <p><a href="#stream_readable_streams">Readable Streams</a></p> <ul> <li><a href="#stream_two_reading_modes">Two Reading Modes</a></li> <li><a href="#stream_three_states">Three States</a></li> <li><a href="#stream_choose_one_api_style">Choose One API Style</a></li> <li> <p><a href="#stream_class_stream_readable">Class: stream.Readable</a></p> <ul> <li><a href="#stream_event_close_1">Event: 'close'</a></li> <li><a href="#stream_event_data">Event: 'data'</a></li> <li><a href="#stream_event_end">Event: 'end'</a></li> <li><a href="#stream_event_error_1">Event: 'error'</a></li> <li><a href="#stream_event_readable">Event: 'readable'</a></li> <li><a href="#stream_readable_destroy_error">readable.destroy([error])</a></li> <li><a href="#stream_readable_ispaused">readable.isPaused()</a></li> <li><a href="#stream_readable_pause">readable.pause()</a></li> <li><a href="#stream_readable_pipe_destination_options">readable.pipe(destination[, options])</a></li> <li><a href="#stream_readable_read_size">readable.read([size])</a></li> <li><a href="#stream_readable_readable">readable.readable</a></li> <li><a href="#stream_readable_readableflowing">readable.readableFlowing</a></li> <li><a href="#stream_readable_readablehighwatermark">readable.readableHighWaterMark</a></li> <li><a href="#stream_readable_readablelength">readable.readableLength</a></li> <li><a href="#stream_readable_resume">readable.resume()</a></li> <li><a href="#stream_readable_setencoding_encoding">readable.setEncoding(encoding)</a></li> <li><a href="#stream_readable_unpipe_destination">readable.unpipe([destination])</a></li> <li><a href="#stream_readable_unshift_chunk">readable.unshift(chunk)</a></li> <li><a href="#stream_readable_wrap_stream">readable.wrap(stream)</a></li> <li><span class="stability_2"><a href="#stream_readable_symbol_asynciterator">readable[Symbol.asyncIterator]()</a></span></li> </ul> </li> </ul> </li> <li> <p><a href="#stream_duplex_and_transform_streams">Duplex and Transform Streams</a></p> <ul> <li><a href="#stream_class_stream_duplex">Class: stream.Duplex</a></li> <li> <p><a href="#stream_class_stream_transform">Class: stream.Transform</a></p> <ul> <li><a href="#stream_transform_destroy_error">transform.destroy([error])</a></li> </ul> </li> </ul> </li> <li><a href="#stream_stream_finished_stream_callback">stream.finished(stream, callback)</a></li> <li><a href="#stream_stream_pipeline_streams_callback">stream.pipeline(...streams[, callback])</a></li> <li><a href="#stream_readable_from_iterable_options">Readable.from(iterable, [options])</a></li> </ul> </li> <li> <p><a href="#stream_api_for_stream_implementers">API for Stream Implementers</a></p> <ul> <li><a href="#stream_simplified_construction">Simplified Construction</a></li> <li> <p><a href="#stream_implementing_a_writable_stream">Implementing a Writable Stream</a></p> <ul> <li><a href="#stream_constructor_new_stream_writable_options">Constructor: new stream.Writable([options])</a></li> <li><a href="#stream_writable_write_chunk_encoding_callback_1">writable._write(chunk, encoding, callback)</a></li> <li><a href="#stream_writable_writev_chunks_callback">writable._writev(chunks, callback)</a></li> <li><a href="#stream_writable_destroy_err_callback">writable._destroy(err, callback)</a></li> <li><a href="#stream_writable_final_callback">writable._final(callback)</a></li> <li><a href="#stream_errors_while_writing">Errors While Writing</a></li> <li><a href="#stream_an_example_writable_stream">An Example Writable Stream</a></li> <li><a href="#stream_decoding_buffers_in_a_writable_stream">Decoding buffers in a Writable Stream</a></li> </ul> </li> <li> <p><a href="#stream_implementing_a_readable_stream">Implementing a Readable Stream</a></p> <ul> <li><a href="#stream_new_stream_readable_options">new stream.Readable([options])</a></li> <li><a href="#stream_readable_read_size_1">readable._read(size)</a></li> <li><a href="#stream_readable_destroy_err_callback">readable._destroy(err, callback)</a></li> <li><a href="#stream_readable_push_chunk_encoding">readable.push(chunk[, encoding])</a></li> <li><a href="#stream_errors_while_reading">Errors While Reading</a></li> <li><a href="#stream_an_example_counting_stream">An Example Counting Stream</a></li> </ul> </li> <li> <p><a href="#stream_implementing_a_duplex_stream">Implementing a Duplex Stream</a></p> <ul> <li><a href="#stream_new_stream_duplex_options">new stream.Duplex(options)</a></li> <li><a href="#stream_an_example_duplex_stream">An Example Duplex Stream</a></li> <li><a href="#stream_object_mode_duplex_streams">Object Mode Duplex Streams</a></li> </ul> </li> <li> <p><a href="#stream_implementing_a_transform_stream">Implementing a Transform Stream</a></p> <ul> <li><a href="#stream_new_stream_transform_options">new stream.Transform([options])</a></li> <li><a href="#stream_events_finish_and_end">Events: 'finish' and 'end'</a></li> <li><a href="#stream_transform_flush_callback">transform._flush(callback)</a></li> <li><a href="#stream_transform_transform_chunk_encoding_callback">transform._transform(chunk, encoding, callback)</a></li> <li><a href="#stream_class_stream_passthrough">Class: stream.PassThrough</a></li> </ul> </li> </ul> </li> <li> <p><a href="#stream_additional_notes">Additional Notes</a></p> <ul> <li> <p><a href="#stream_streams_compatibility_with_async_generators_and_async_iterators">Streams Compatibility with Async Generators and Async Iterators</a></p> <ul> <li><a href="#stream_consuming_readable_streams_with_async_iterators">Consuming Readable Streams with Async Iterators</a></li> <li><a href="#stream_creating_readable_streams_with_async_generators">Creating Readable Streams with Async Generators</a></li> <li><a href="#stream_piping_to_writable_streams_from_async_iterators">Piping to Writable Streams from Async Iterators</a></li> </ul> </li> <li><a href="#stream_compatibility_with_older_node_js_versions">Compatibility with Older Node.js Versions</a></li> <li><a href="#stream_readable_read_0"><code>readable.read(0)</code></a></li> <li><a href="#stream_readable_push"><code>readable.push('')</code></a></li> <li><a href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#string_decoder_string_decoder">String Decoder</a></span></p> <ul> <li> <p><a href="#string_decoder_class_stringdecoder">Class: StringDecoder</a></p> <ul> <li><a href="#string_decoder_new_stringdecoder_encoding">new StringDecoder([encoding])</a></li> <li><a href="#string_decoder_stringdecoder_end_buffer">stringDecoder.end([buffer])</a></li> <li><a href="#string_decoder_stringdecoder_write_buffer">stringDecoder.write(buffer)</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#timers_timers">Timers</a></span></p> <ul> <li> <p><a href="#timers_class_immediate">Class: Immediate</a></p> <ul> <li><a href="#timers_immediate_ref">immediate.ref()</a></li> <li><a href="#timers_immediate_unref">immediate.unref()</a></li> </ul> </li> <li> <p><a href="#timers_class_timeout">Class: Timeout</a></p> <ul> <li><a href="#timers_timeout_ref">timeout.ref()</a></li> <li><a href="#timers_timeout_refresh">timeout.refresh()</a></li> <li><a href="#timers_timeout_unref">timeout.unref()</a></li> </ul> </li> <li> <p><a href="#timers_scheduling_timers">Scheduling Timers</a></p> <ul> <li><a href="#timers_setimmediate_callback_args">setImmediate(callback[, ...args])</a></li> <li><a href="#timers_setinterval_callback_delay_args">setInterval(callback, delay[, ...args])</a></li> <li><a href="#timers_settimeout_callback_delay_args">setTimeout(callback, delay[, ...args])</a></li> </ul> </li> <li> <p><a href="#timers_cancelling_timers">Cancelling Timers</a></p> <ul> <li><a href="#timers_clearimmediate_immediate">clearImmediate(immediate)</a></li> <li><a href="#timers_clearinterval_timeout">clearInterval(timeout)</a></li> <li><a href="#timers_cleartimeout_timeout">clearTimeout(timeout)</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#tls_tls_ssl">TLS (SSL)</a></span></p> <ul> <li> <p><a href="#tls_tls_ssl_concepts">TLS/SSL Concepts</a></p> <ul> <li><a href="#tls_perfect_forward_secrecy">Perfect Forward Secrecy</a></li> <li><a href="#tls_alpn_and_sni">ALPN and SNI</a></li> <li><a href="#tls_client_initiated_renegotiation_attack_mitigation">Client-initiated renegotiation attack mitigation</a></li> <li><a href="#tls_session_resumption">Session Resumption</a></li> </ul> </li> <li><a href="#tls_modifying_the_default_tls_cipher_suite">Modifying the Default TLS Cipher suite</a></li> <li> <p><a href="#tls_class_tls_server">Class: tls.Server</a></p> <ul> <li><a href="#tls_event_keylog">Event: 'keylog'</a></li> <li><a href="#tls_event_newsession">Event: 'newSession'</a></li> <li><a href="#tls_event_ocsprequest">Event: 'OCSPRequest'</a></li> <li><a href="#tls_event_resumesession">Event: 'resumeSession'</a></li> <li><a href="#tls_event_secureconnection">Event: 'secureConnection'</a></li> <li><a href="#tls_event_tlsclienterror">Event: 'tlsClientError'</a></li> <li><a href="#tls_server_addcontext_hostname_context">server.addContext(hostname, context)</a></li> <li><a href="#tls_server_address">server.address()</a></li> <li><a href="#tls_server_close_callback">server.close([callback])</a></li> <li><span class="stability_0"><a href="#tls_server_connections">server.connections</a></span></li> <li><a href="#tls_server_getticketkeys">server.getTicketKeys()</a></li> <li><a href="#tls_server_listen">server.listen()</a></li> <li><a href="#tls_server_setticketkeys_keys">server.setTicketKeys(keys)</a></li> </ul> </li> <li> <p><a href="#tls_class_tls_tlssocket">Class: tls.TLSSocket</a></p> <ul> <li><a href="#tls_new_tls_tlssocket_socket_options">new tls.TLSSocket(socket[, options])</a></li> <li><a href="#tls_event_keylog_1">Event: 'keylog'</a></li> <li><a href="#tls_event_ocspresponse">Event: 'OCSPResponse'</a></li> <li><a href="#tls_event_secureconnect">Event: 'secureConnect'</a></li> <li><a href="#tls_tlssocket_address">tlsSocket.address()</a></li> <li><a href="#tls_tlssocket_authorizationerror">tlsSocket.authorizationError</a></li> <li><a href="#tls_tlssocket_authorized">tlsSocket.authorized</a></li> <li><a href="#tls_tlssocket_disablerenegotiation">tlsSocket.disableRenegotiation()</a></li> <li><a href="#tls_tlssocket_encrypted">tlsSocket.encrypted</a></li> <li><a href="#tls_tlssocket_getcipher">tlsSocket.getCipher()</a></li> <li><a href="#tls_tlssocket_getephemeralkeyinfo">tlsSocket.getEphemeralKeyInfo()</a></li> <li><a href="#tls_tlssocket_getfinished">tlsSocket.getFinished()</a></li> <li><a href="#tls_tlssocket_getpeercertificate_detailed">tlsSocket.getPeerCertificate([detailed])</a></li> <li><a href="#tls_tlssocket_getpeerfinished">tlsSocket.getPeerFinished()</a></li> <li><a href="#tls_tlssocket_getprotocol">tlsSocket.getProtocol()</a></li> <li><a href="#tls_tlssocket_getsession">tlsSocket.getSession()</a></li> <li><a href="#tls_tlssocket_gettlsticket">tlsSocket.getTLSTicket()</a></li> <li><a href="#tls_tlssocket_issessionreused">tlsSocket.isSessionReused()</a></li> <li><a href="#tls_tlssocket_localaddress">tlsSocket.localAddress</a></li> <li><a href="#tls_tlssocket_localport">tlsSocket.localPort</a></li> <li><a href="#tls_tlssocket_remoteaddress">tlsSocket.remoteAddress</a></li> <li><a href="#tls_tlssocket_remotefamily">tlsSocket.remoteFamily</a></li> <li><a href="#tls_tlssocket_remoteport">tlsSocket.remotePort</a></li> <li><a href="#tls_tlssocket_renegotiate_options_callback">tlsSocket.renegotiate(options, callback)</a></li> <li><a href="#tls_tlssocket_setmaxsendfragment_size">tlsSocket.setMaxSendFragment(size)</a></li> </ul> </li> <li><a href="#tls_tls_checkserveridentity_hostname_cert">tls.checkServerIdentity(hostname, cert)</a></li> <li><a href="#tls_tls_connect_options_callback">tls.connect(options[, callback])</a></li> <li><a href="#tls_tls_connect_path_options_callback">tls.connect(path[, options][, callback])</a></li> <li><a href="#tls_tls_connect_port_host_options_callback">tls.connect(port[, host][, options][, callback])</a></li> <li><a href="#tls_tls_createsecurecontext_options">tls.createSecureContext([options])</a></li> <li><a href="#tls_tls_createserver_options_secureconnectionlistener">tls.createServer([options][, secureConnectionListener])</a></li> <li><a href="#tls_tls_getciphers">tls.getCiphers()</a></li> <li><a href="#tls_tls_default_ecdh_curve">tls.DEFAULT_ECDH_CURVE</a></li> <li><a href="#tls_tls_default_max_version">tls.DEFAULT_MAX_VERSION</a></li> <li><a href="#tls_tls_default_min_version">tls.DEFAULT_MIN_VERSION</a></li> <li> <p><a href="#tls_deprecated_apis">Deprecated APIs</a></p> <ul> <li> <p><span class="stability_0"><a href="#tls_class_cryptostream">Class: CryptoStream</a></span></p> <ul> <li><a href="#tls_cryptostream_byteswritten">cryptoStream.bytesWritten</a></li> </ul> </li> <li> <p><span class="stability_0"><a href="#tls_class_securepair">Class: SecurePair</a></span></p> <ul> <li><a href="#tls_event_secure">Event: 'secure'</a></li> </ul> </li> <li><span class="stability_0"><a href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options">tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])</a></span></li> </ul> </li> </ul> </li> <li> <p><span class="stability_1"><a href="#tracing_trace_events">Trace Events</a></span></p> <ul> <li> <p><a href="#tracing_the_trace_events_module">The <code>trace_events</code> module</a></p> <ul> <li> <p><a href="#tracing_tracing_object"><code>Tracing</code> object</a></p> <ul> <li><a href="#tracing_tracing_categories"><code>tracing.categories</code></a></li> <li><a href="#tracing_tracing_disable"><code>tracing.disable()</code></a></li> <li><a href="#tracing_tracing_enable"><code>tracing.enable()</code></a></li> <li><a href="#tracing_tracing_enabled"><code>tracing.enabled</code></a></li> </ul> </li> <li><a href="#tracing_trace_events_createtracing_options"><code>trace_events.createTracing(options)</code></a></li> <li><a href="#tracing_trace_events_getenabledcategories"><code>trace_events.getEnabledCategories()</code></a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#tty_tty">TTY</a></span></p> <ul> <li> <p><a href="#tty_class_tty_readstream">Class: tty.ReadStream</a></p> <ul> <li><a href="#tty_readstream_israw">readStream.isRaw</a></li> <li><a href="#tty_readstream_istty">readStream.isTTY</a></li> <li><a href="#tty_readstream_setrawmode_mode">readStream.setRawMode(mode)</a></li> </ul> </li> <li> <p><a href="#tty_class_tty_writestream">Class: tty.WriteStream</a></p> <ul> <li><a href="#tty_event_resize">Event: 'resize'</a></li> <li><a href="#tty_writestream_clearline_dir">writeStream.clearLine(dir)</a></li> <li><a href="#tty_writestream_clearscreendown">writeStream.clearScreenDown()</a></li> <li><a href="#tty_writestream_columns">writeStream.columns</a></li> <li><a href="#tty_writestream_cursorto_x_y">writeStream.cursorTo(x, y)</a></li> <li><a href="#tty_writestream_getcolordepth_env">writeStream.getColorDepth([env])</a></li> <li><a href="#tty_writestream_getwindowsize">writeStream.getWindowSize()</a></li> <li><a href="#tty_writestream_hascolors_count_env">writeStream.hasColors([count][, env])</a></li> <li><a href="#tty_writestream_istty">writeStream.isTTY</a></li> <li><a href="#tty_writestream_movecursor_dx_dy">writeStream.moveCursor(dx, dy)</a></li> <li><a href="#tty_writestream_rows">writeStream.rows</a></li> </ul> </li> <li><a href="#tty_tty_isatty_fd">tty.isatty(fd)</a></li> </ul> </li> <li> <p><span class="stability_2"><a href="#dgram_udp_datagram_sockets">UDP/Datagram Sockets</a></span></p> <ul> <li> <p><a href="#dgram_class_dgram_socket">Class: dgram.Socket</a></p> <ul> <li><a href="#dgram_event_close">Event: 'close'</a></li> <li><a href="#dgram_event_error">Event: 'error'</a></li> <li><a href="#dgram_event_listening">Event: 'listening'</a></li> <li><a href="#dgram_event_message">Event: 'message'</a></li> <li><a href="#dgram_socket_addmembership_multicastaddress_multicastinterface">socket.addMembership(multicastAddress[, multicastInterface])</a></li> <li><a href="#dgram_socket_address">socket.address()</a></li> <li><a href="#dgram_socket_bind_port_address_callback">socket.bind([port][, address][, callback])</a></li> <li><a href="#dgram_socket_bind_options_callback">socket.bind(options[, callback])</a></li> <li><a href="#dgram_socket_close_callback">socket.close([callback])</a></li> <li><a href="#dgram_socket_dropmembership_multicastaddress_multicastinterface">socket.dropMembership(multicastAddress[, multicastInterface])</a></li> <li><a href="#dgram_socket_getrecvbuffersize">socket.getRecvBufferSize()</a></li> <li><a href="#dgram_socket_getsendbuffersize">socket.getSendBufferSize()</a></li> <li><a href="#dgram_socket_ref">socket.ref()</a></li> <li><a href="#dgram_socket_send_msg_offset_length_port_address_callback">socket.send(msg[, offset, length], port[, address][, callback])</a></li> <li><a href="#dgram_socket_setbroadcast_flag">socket.setBroadcast(flag)</a></li> <li> <p><a href="#dgram_socket_setmulticastinterface_multicastinterface">socket.setMulticastInterface(multicastInterface)</a></p> <ul> <li><a href="#dgram_examples_ipv6_outgoing_multicast_interface">Examples: IPv6 Outgoing Multicast Interface</a></li> <li><a href="#dgram_example_ipv4_outgoing_multicast_interface">Example: IPv4 Outgoing Multicast Interface</a></li> <li><a href="#dgram_call_results">Call Results</a></li> </ul> </li> <li><a href="#dgram_socket_setmulticastloopback_flag">socket.setMulticastLoopback(flag)</a></li> <li><a href="#dgram_socket_setmulticastttl_ttl">socket.setMulticastTTL(ttl)</a></li> <li><a href="#dgram_socket_setrecvbuffersize_size">socket.setRecvBufferSize(size)</a></li> <li><a href="#dgram_socket_setsendbuffersize_size">socket.setSendBufferSize(size)</a></li> <li><a href="#dgram_socket_setttl_ttl">socket.setTTL(ttl)</a></li> <li><a href="#dgram_socket_unref">socket.unref()</a></li> <li><a href="#dgram_change_to_asynchronous_socket_bind_behavior">Change to asynchronous <code>socket.bind()</code> behavior</a></li> </ul> </li> <li> <p><a href="#dgram_dgram_module_functions"><code>dgram</code> module functions</a></p> <ul> <li><a href="#dgram_dgram_createsocket_options_callback">dgram.createSocket(options[, callback])</a></li> <li><a href="#dgram_dgram_createsocket_type_callback">dgram.createSocket(type[, callback])</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#url_url">URL</a></span></p> <ul> <li><a href="#url_url_strings_and_url_objects">URL Strings and URL Objects</a></li> <li> <p><a href="#url_the_whatwg_url_api">The WHATWG URL API</a></p> <ul> <li> <p><a href="#url_class_url">Class: URL</a></p> <ul> <li><a href="#url_constructor_new_url_input_base">Constructor: new URL(input[, base])</a></li> <li><a href="#url_url_hash">url.hash</a></li> <li><a href="#url_url_host">url.host</a></li> <li><a href="#url_url_hostname">url.hostname</a></li> <li><a href="#url_url_href">url.href</a></li> <li><a href="#url_url_origin">url.origin</a></li> <li><a href="#url_url_password">url.password</a></li> <li><a href="#url_url_pathname">url.pathname</a></li> <li><a href="#url_url_port">url.port</a></li> <li> <p><a href="#url_url_protocol">url.protocol</a></p> <ul> <li><a href="#url_special_schemes">Special Schemes</a></li> </ul> </li> <li><a href="#url_url_search">url.search</a></li> <li><a href="#url_url_searchparams">url.searchParams</a></li> <li><a href="#url_url_username">url.username</a></li> <li><a href="#url_url_tostring">url.toString()</a></li> <li><a href="#url_url_tojson">url.toJSON()</a></li> </ul> </li> <li> <p><a href="#url_class_urlsearchparams">Class: URLSearchParams</a></p> <ul> <li><a href="#url_constructor_new_urlsearchparams">Constructor: new URLSearchParams()</a></li> <li><a href="#url_constructor_new_urlsearchparams_string">Constructor: new URLSearchParams(string)</a></li> <li><a href="#url_constructor_new_urlsearchparams_obj">Constructor: new URLSearchParams(obj)</a></li> <li><a href="#url_constructor_new_urlsearchparams_iterable">Constructor: new URLSearchParams(iterable)</a></li> <li><a href="#url_urlsearchparams_append_name_value">urlSearchParams.append(name, value)</a></li> <li><a href="#url_urlsearchparams_delete_name">urlSearchParams.delete(name)</a></li> <li><a href="#url_urlsearchparams_entries">urlSearchParams.entries()</a></li> <li><a href="#url_urlsearchparams_foreach_fn_thisarg">urlSearchParams.forEach(fn[, thisArg])</a></li> <li><a href="#url_urlsearchparams_get_name">urlSearchParams.get(name)</a></li> <li><a href="#url_urlsearchparams_getall_name">urlSearchParams.getAll(name)</a></li> <li><a href="#url_urlsearchparams_has_name">urlSearchParams.has(name)</a></li> <li><a href="#url_urlsearchparams_keys">urlSearchParams.keys()</a></li> <li><a href="#url_urlsearchparams_set_name_value">urlSearchParams.set(name, value)</a></li> <li><a href="#url_urlsearchparams_sort">urlSearchParams.sort()</a></li> <li><a href="#url_urlsearchparams_tostring">urlSearchParams.toString()</a></li> <li><a href="#url_urlsearchparams_values">urlSearchParams.values()</a></li> <li><a href="#url_urlsearchparams_symbol_iterator">urlSearchParams[Symbol.iterator]()</a></li> </ul> </li> <li><a href="#url_url_domaintoascii_domain">url.domainToASCII(domain)</a></li> <li><a href="#url_url_domaintounicode_domain">url.domainToUnicode(domain)</a></li> <li><a href="#url_url_fileurltopath_url">url.fileURLToPath(url)</a></li> <li><a href="#url_url_format_url_options">url.format(URL[, options])</a></li> <li><a href="#url_url_pathtofileurl_path">url.pathToFileURL(path)</a></li> </ul> </li> <li> <p><a href="#url_legacy_url_api">Legacy URL API</a></p> <ul> <li> <p><a href="#url_legacy_urlobject">Legacy <code>urlObject</code></a></p> <ul> <li><a href="#url_urlobject_auth">urlObject.auth</a></li> <li><a href="#url_urlobject_hash">urlObject.hash</a></li> <li><a href="#url_urlobject_host">urlObject.host</a></li> <li><a href="#url_urlobject_hostname">urlObject.hostname</a></li> <li><a href="#url_urlobject_href">urlObject.href</a></li> <li><a href="#url_urlobject_path">urlObject.path</a></li> <li><a href="#url_urlobject_pathname">urlObject.pathname</a></li> <li><a href="#url_urlobject_port">urlObject.port</a></li> <li><a href="#url_urlobject_protocol">urlObject.protocol</a></li> <li><a href="#url_urlobject_query">urlObject.query</a></li> <li><a href="#url_urlobject_search">urlObject.search</a></li> <li><a href="#url_urlobject_slashes">urlObject.slashes</a></li> </ul> </li> <li><a href="#url_url_format_urlobject">url.format(urlObject)</a></li> <li><a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost">url.parse(urlString[, parseQueryString[, slashesDenoteHost]])</a></li> <li><a href="#url_url_resolve_from_to">url.resolve(from, to)</a></li> </ul> </li> <li> <p><a href="#url_percent_encoding_in_urls">Percent-Encoding in URLs</a></p> <ul> <li><a href="#url_legacy_api">Legacy API</a></li> <li><a href="#url_whatwg_api">WHATWG API</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#util_util">Util</a></span></p> <ul> <li><a href="#util_util_callbackify_original">util.callbackify(original)</a></li> <li><a href="#util_util_debuglog_section">util.debuglog(section)</a></li> <li><a href="#util_util_deprecate_fn_msg_code">util.deprecate(fn, msg[, code])</a></li> <li><a href="#util_util_format_format_args">util.format(format[, ...args])</a></li> <li><a href="#util_util_formatwithoptions_inspectoptions_format_args">util.formatWithOptions(inspectOptions, format[, ...args])</a></li> <li><a href="#util_util_getsystemerrorname_err">util.getSystemErrorName(err)</a></li> <li><a href="#util_util_inherits_constructor_superconstructor">util.inherits(constructor, superConstructor)</a></li> <li><a href="#util_util_inspect_object_options">util.inspect(object[, options])</a></li> <li> <p><a href="#util_util_inspect_object_showhidden_depth_colors">util.inspect(object[, showHidden[, depth[, colors]]])</a></p> <ul> <li><a href="#util_customizing_util_inspect_colors">Customizing <code>util.inspect</code> colors</a></li> <li><a href="#util_custom_inspection_functions_on_objects">Custom inspection functions on Objects</a></li> <li><a href="#util_util_inspect_custom">util.inspect.custom</a></li> <li><a href="#util_util_inspect_defaultoptions">util.inspect.defaultOptions</a></li> </ul> </li> <li><a href="#util_util_isdeepstrictequal_val1_val2">util.isDeepStrictEqual(val1, val2)</a></li> <li> <p><a href="#util_util_promisify_original">util.promisify(original)</a></p> <ul> <li><a href="#util_custom_promisified_functions">Custom promisified functions</a></li> <li><a href="#util_util_promisify_custom">util.promisify.custom</a></li> </ul> </li> <li> <p><a href="#util_class_util_textdecoder">Class: util.TextDecoder</a></p> <ul> <li> <p><a href="#util_whatwg_supported_encodings">WHATWG Supported Encodings</a></p> <ul> <li><a href="#util_encodings_supported_without_icu">Encodings Supported Without ICU</a></li> <li><a href="#util_encodings_supported_by_default_with_icu">Encodings Supported by Default (With ICU)</a></li> <li><a href="#util_encodings_requiring_full_icu_data">Encodings Requiring Full ICU Data</a></li> </ul> </li> <li><a href="#util_new_textdecoder_encoding_options">new TextDecoder([encoding[, options]])</a></li> <li><a href="#util_textdecoder_decode_input_options">textDecoder.decode([input[, options]])</a></li> <li><a href="#util_textdecoder_encoding">textDecoder.encoding</a></li> <li><a href="#util_textdecoder_fatal">textDecoder.fatal</a></li> <li><a href="#util_textdecoder_ignorebom">textDecoder.ignoreBOM</a></li> </ul> </li> <li> <p><a href="#util_class_util_textencoder">Class: util.TextEncoder</a></p> <ul> <li><a href="#util_textencoder_encode_input">textEncoder.encode([input])</a></li> <li><a href="#util_textencoder_encoding">textEncoder.encoding</a></li> </ul> </li> <li> <p><a href="#util_util_types">util.types</a></p> <ul> <li><a href="#util_util_types_isanyarraybuffer_value">util.types.isAnyArrayBuffer(value)</a></li> <li><a href="#util_util_types_isargumentsobject_value">util.types.isArgumentsObject(value)</a></li> <li><a href="#util_util_types_isarraybuffer_value">util.types.isArrayBuffer(value)</a></li> <li><a href="#util_util_types_isasyncfunction_value">util.types.isAsyncFunction(value)</a></li> <li><a href="#util_util_types_isbigint64array_value">util.types.isBigInt64Array(value)</a></li> <li><a href="#util_util_types_isbiguint64array_value">util.types.isBigUint64Array(value)</a></li> <li><a href="#util_util_types_isbooleanobject_value">util.types.isBooleanObject(value)</a></li> <li><a href="#util_util_types_isboxedprimitive_value">util.types.isBoxedPrimitive(value)</a></li> <li><a href="#util_util_types_isdataview_value">util.types.isDataView(value)</a></li> <li><a href="#util_util_types_isdate_value">util.types.isDate(value)</a></li> <li><a href="#util_util_types_isexternal_value">util.types.isExternal(value)</a></li> <li><a href="#util_util_types_isfloat32array_value">util.types.isFloat32Array(value)</a></li> <li><a href="#util_util_types_isfloat64array_value">util.types.isFloat64Array(value)</a></li> <li><a href="#util_util_types_isgeneratorfunction_value">util.types.isGeneratorFunction(value)</a></li> <li><a href="#util_util_types_isgeneratorobject_value">util.types.isGeneratorObject(value)</a></li> <li><a href="#util_util_types_isint8array_value">util.types.isInt8Array(value)</a></li> <li><a href="#util_util_types_isint16array_value">util.types.isInt16Array(value)</a></li> <li><a href="#util_util_types_isint32array_value">util.types.isInt32Array(value)</a></li> <li><a href="#util_util_types_ismap_value">util.types.isMap(value)</a></li> <li><a href="#util_util_types_ismapiterator_value">util.types.isMapIterator(value)</a></li> <li><a href="#util_util_types_ismodulenamespaceobject_value">util.types.isModuleNamespaceObject(value)</a></li> <li><a href="#util_util_types_isnativeerror_value">util.types.isNativeError(value)</a></li> <li><a href="#util_util_types_isnumberobject_value">util.types.isNumberObject(value)</a></li> <li><a href="#util_util_types_ispromise_value">util.types.isPromise(value)</a></li> <li><a href="#util_util_types_isproxy_value">util.types.isProxy(value)</a></li> <li><a href="#util_util_types_isregexp_value">util.types.isRegExp(value)</a></li> <li><a href="#util_util_types_isset_value">util.types.isSet(value)</a></li> <li><a href="#util_util_types_issetiterator_value">util.types.isSetIterator(value)</a></li> <li><a href="#util_util_types_issharedarraybuffer_value">util.types.isSharedArrayBuffer(value)</a></li> <li><a href="#util_util_types_isstringobject_value">util.types.isStringObject(value)</a></li> <li><a href="#util_util_types_issymbolobject_value">util.types.isSymbolObject(value)</a></li> <li><a href="#util_util_types_istypedarray_value">util.types.isTypedArray(value)</a></li> <li><a href="#util_util_types_isuint8array_value">util.types.isUint8Array(value)</a></li> <li><a href="#util_util_types_isuint8clampedarray_value">util.types.isUint8ClampedArray(value)</a></li> <li><a href="#util_util_types_isuint16array_value">util.types.isUint16Array(value)</a></li> <li><a href="#util_util_types_isuint32array_value">util.types.isUint32Array(value)</a></li> <li><a href="#util_util_types_isweakmap_value">util.types.isWeakMap(value)</a></li> <li><a href="#util_util_types_isweakset_value">util.types.isWeakSet(value)</a></li> <li><a href="#util_util_types_iswebassemblycompiledmodule_value">util.types.isWebAssemblyCompiledModule(value)</a></li> </ul> </li> <li> <p><a href="#util_deprecated_apis">Deprecated APIs</a></p> <ul> <li><span class="stability_0"><a href="#util_util_extend_target_source">util._extend(target, source)</a></span></li> <li><span class="stability_0"><a href="#util_util_debug_string">util.debug(string)</a></span></li> <li><span class="stability_0"><a href="#util_util_error_strings">util.error([...strings])</a></span></li> <li><span class="stability_0"><a href="#util_util_isarray_object">util.isArray(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isboolean_object">util.isBoolean(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isbuffer_object">util.isBuffer(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isdate_object">util.isDate(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_iserror_object">util.isError(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isfunction_object">util.isFunction(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isnull_object">util.isNull(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isnullorundefined_object">util.isNullOrUndefined(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isnumber_object">util.isNumber(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isobject_object">util.isObject(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isprimitive_object">util.isPrimitive(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isregexp_object">util.isRegExp(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isstring_object">util.isString(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_issymbol_object">util.isSymbol(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_isundefined_object">util.isUndefined(object)</a></span></li> <li><span class="stability_0"><a href="#util_util_log_string">util.log(string)</a></span></li> <li><span class="stability_0"><a href="#util_util_print_strings">util.print([...strings])</a></span></li> <li><span class="stability_0"><a href="#util_util_puts_strings">util.puts([...strings])</a></span></li> </ul> </li> </ul> </li> <li> <p><a href="#v8_v8">V8</a></p> <ul> <li><a href="#v8_v8_cacheddataversiontag">v8.cachedDataVersionTag()</a></li> <li><a href="#v8_v8_getheapspacestatistics">v8.getHeapSpaceStatistics()</a></li> <li><a href="#v8_v8_getheapstatistics">v8.getHeapStatistics()</a></li> <li><a href="#v8_v8_setflagsfromstring_flags">v8.setFlagsFromString(flags)</a></li> <li> <p><a href="#v8_serialization_api">Serialization API</a></p> <ul> <li><a href="#v8_v8_serialize_value">v8.serialize(value)</a></li> <li><a href="#v8_v8_deserialize_buffer">v8.deserialize(buffer)</a></li> <li> <p><a href="#v8_class_v8_serializer">class: v8.Serializer</a></p> <ul> <li><a href="#v8_new_serializer">new Serializer()</a></li> <li><a href="#v8_serializer_writeheader">serializer.writeHeader()</a></li> <li><a href="#v8_serializer_writevalue_value">serializer.writeValue(value)</a></li> <li><a href="#v8_serializer_releasebuffer">serializer.releaseBuffer()</a></li> <li><a href="#v8_serializer_transferarraybuffer_id_arraybuffer">serializer.transferArrayBuffer(id, arrayBuffer)</a></li> <li><a href="#v8_serializer_writeuint32_value">serializer.writeUint32(value)</a></li> <li><a href="#v8_serializer_writeuint64_hi_lo">serializer.writeUint64(hi, lo)</a></li> <li><a href="#v8_serializer_writedouble_value">serializer.writeDouble(value)</a></li> <li><a href="#v8_serializer_writerawbytes_buffer">serializer.writeRawBytes(buffer)</a></li> <li><a href="#v8_serializer_writehostobject_object">serializer._writeHostObject(object)</a></li> <li><a href="#v8_serializer_getdatacloneerror_message">serializer._getDataCloneError(message)</a></li> <li><a href="#v8_serializer_getsharedarraybufferid_sharedarraybuffer">serializer._getSharedArrayBufferId(sharedArrayBuffer)</a></li> <li><a href="#v8_serializer_settreatarraybufferviewsashostobjects_flag">serializer._setTreatArrayBufferViewsAsHostObjects(flag)</a></li> </ul> </li> <li> <p><a href="#v8_class_v8_deserializer">class: v8.Deserializer</a></p> <ul> <li><a href="#v8_new_deserializer_buffer">new Deserializer(buffer)</a></li> <li><a href="#v8_deserializer_readheader">deserializer.readHeader()</a></li> <li><a href="#v8_deserializer_readvalue">deserializer.readValue()</a></li> <li><a href="#v8_deserializer_transferarraybuffer_id_arraybuffer">deserializer.transferArrayBuffer(id, arrayBuffer)</a></li> <li><a href="#v8_deserializer_getwireformatversion">deserializer.getWireFormatVersion()</a></li> <li><a href="#v8_deserializer_readuint32">deserializer.readUint32()</a></li> <li><a href="#v8_deserializer_readuint64">deserializer.readUint64()</a></li> <li><a href="#v8_deserializer_readdouble">deserializer.readDouble()</a></li> <li><a href="#v8_deserializer_readrawbytes_length">deserializer.readRawBytes(length)</a></li> <li><a href="#v8_deserializer_readhostobject">deserializer._readHostObject()</a></li> </ul> </li> <li><a href="#v8_class_v8_defaultserializer">class: v8.DefaultSerializer</a></li> <li><a href="#v8_class_v8_defaultdeserializer">class: v8.DefaultDeserializer</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#vm_vm_executing_javascript">VM (Executing JavaScript)</a></span></p> <ul> <li> <p><span class="stability_1"><a href="#vm_class_vm_sourcetextmodule">Class: vm.SourceTextModule</a></span></p> <ul> <li><a href="#vm_constructor_new_vm_sourcetextmodule_code_options">Constructor: new vm.SourceTextModule(code[, options])</a></li> <li><a href="#vm_module_dependencyspecifiers">module.dependencySpecifiers</a></li> <li><a href="#vm_module_error">module.error</a></li> <li><a href="#vm_module_evaluate_options">module.evaluate([options])</a></li> <li><a href="#vm_module_instantiate">module.instantiate()</a></li> <li><a href="#vm_module_link_linker">module.link(linker)</a></li> <li><a href="#vm_module_linkingstatus">module.linkingStatus</a></li> <li><a href="#vm_module_namespace">module.namespace</a></li> <li><a href="#vm_module_status">module.status</a></li> <li><a href="#vm_module_url">module.url</a></li> </ul> </li> <li> <p><a href="#vm_class_vm_script">Class: vm.Script</a></p> <ul> <li><a href="#vm_new_vm_script_code_options">new vm.Script(code, options)</a></li> <li><a href="#vm_script_createcacheddata">script.createCachedData()</a></li> <li><a href="#vm_script_runincontext_contextifiedsandbox_options">script.runInContext(contextifiedSandbox[, options])</a></li> <li><a href="#vm_script_runinnewcontext_sandbox_options">script.runInNewContext([sandbox[, options]])</a></li> <li><a href="#vm_script_runinthiscontext_options">script.runInThisContext([options])</a></li> </ul> </li> <li><a href="#vm_vm_compilefunction_code_params_options">vm.compileFunction(code[, params[, options]])</a></li> <li><a href="#vm_vm_createcontext_sandbox_options">vm.createContext([sandbox[, options]])</a></li> <li><a href="#vm_vm_iscontext_sandbox">vm.isContext(sandbox)</a></li> <li><a href="#vm_vm_runincontext_code_contextifiedsandbox_options">vm.runInContext(code, contextifiedSandbox[, options])</a></li> <li><a href="#vm_vm_runinnewcontext_code_sandbox_options">vm.runInNewContext(code[, sandbox[, options]])</a></li> <li><a href="#vm_vm_runinthiscontext_code_options">vm.runInThisContext(code[, options])</a></li> <li><a href="#vm_example_running_an_http_server_within_a_vm">Example: Running an HTTP Server within a VM</a></li> <li><a href="#vm_what_does_it_mean_to_contextify_an_object">What does it mean to "contextify" an object?</a></li> <li><a href="#vm_timeout_limitations_when_using_process_nexttick_and_promises">Timeout limitations when using process.nextTick(), and Promises</a></li> </ul> </li> <li> <p><span class="stability_1"><a href="#worker_threads_worker_threads">Worker Threads</a></span></p> <ul> <li><a href="#worker_threads_worker_ismainthread">worker.isMainThread</a></li> <li><a href="#worker_threads_worker_parentport">worker.parentPort</a></li> <li><a href="#worker_threads_worker_threadid">worker.threadId</a></li> <li><a href="#worker_threads_worker_workerdata">worker.workerData</a></li> <li><a href="#worker_threads_class_messagechannel">Class: MessageChannel</a></li> <li> <p><a href="#worker_threads_class_messageport">Class: MessagePort</a></p> <ul> <li><a href="#worker_threads_event_close">Event: 'close'</a></li> <li><a href="#worker_threads_event_message">Event: 'message'</a></li> <li><a href="#worker_threads_port_close">port.close()</a></li> <li><a href="#worker_threads_port_postmessage_value_transferlist">port.postMessage(value[, transferList])</a></li> <li><a href="#worker_threads_port_ref">port.ref()</a></li> <li><a href="#worker_threads_port_start">port.start()</a></li> <li><a href="#worker_threads_port_unref">port.unref()</a></li> </ul> </li> <li> <p><a href="#worker_threads_class_worker">Class: Worker</a></p> <ul> <li><a href="#worker_threads_new_worker_filename_options">new Worker(filename[, options])</a></li> <li><a href="#worker_threads_event_error">Event: 'error'</a></li> <li><a href="#worker_threads_event_exit">Event: 'exit'</a></li> <li><a href="#worker_threads_event_message_1">Event: 'message'</a></li> <li><a href="#worker_threads_event_online">Event: 'online'</a></li> <li><a href="#worker_threads_worker_postmessage_value_transferlist">worker.postMessage(value[, transferList])</a></li> <li><a href="#worker_threads_worker_ref">worker.ref()</a></li> <li><a href="#worker_threads_worker_stderr">worker.stderr</a></li> <li><a href="#worker_threads_worker_stdin">worker.stdin</a></li> <li><a href="#worker_threads_worker_stdout">worker.stdout</a></li> <li><a href="#worker_threads_worker_terminate_callback">worker.terminate([callback])</a></li> <li><a href="#worker_threads_worker_threadid_1">worker.threadId</a></li> <li><a href="#worker_threads_worker_unref">worker.unref()</a></li> </ul> </li> </ul> </li> <li> <p><span class="stability_2"><a href="#zlib_zlib">Zlib</a></span></p> <ul> <li><a href="#zlib_threadpool_usage">Threadpool Usage</a></li> <li><a href="#zlib_compressing_http_requests_and_responses">Compressing HTTP requests and responses</a></li> <li> <p><a href="#zlib_memory_usage_tuning">Memory Usage Tuning</a></p> <ul> <li><a href="#zlib_for_zlib_based_streams">For zlib-based streams</a></li> <li><a href="#zlib_for_brotli_based_streams">For Brotli-based streams</a></li> </ul> </li> <li><a href="#zlib_flushing">Flushing</a></li> <li> <p><a href="#zlib_constants">Constants</a></p> <ul> <li><a href="#zlib_zlib_constants">zlib constants</a></li> <li> <p><a href="#zlib_brotli_constants">Brotli constants</a></p> <ul> <li><a href="#zlib_flush_operations">Flush operations</a></li> <li><a href="#zlib_compressor_options">Compressor options</a></li> <li><a href="#zlib_decompressor_options">Decompressor options</a></li> </ul> </li> </ul> </li> <li><a href="#zlib_class_options">Class: Options</a></li> <li><a href="#zlib_class_brotlioptions">Class: BrotliOptions</a></li> <li><a href="#zlib_class_zlib_brotlicompress">Class: zlib.BrotliCompress</a></li> <li><a href="#zlib_class_zlib_brotlidecompress">Class: zlib.BrotliDecompress</a></li> <li><a href="#zlib_class_zlib_deflate">Class: zlib.Deflate</a></li> <li><a href="#zlib_class_zlib_deflateraw">Class: zlib.DeflateRaw</a></li> <li><a href="#zlib_class_zlib_gunzip">Class: zlib.Gunzip</a></li> <li><a href="#zlib_class_zlib_gzip">Class: zlib.Gzip</a></li> <li><a href="#zlib_class_zlib_inflate">Class: zlib.Inflate</a></li> <li><a href="#zlib_class_zlib_inflateraw">Class: zlib.InflateRaw</a></li> <li><a href="#zlib_class_zlib_unzip">Class: zlib.Unzip</a></li> <li> <p><a href="#zlib_class_zlib_zlibbase">Class: zlib.ZlibBase</a></p> <ul> <li><span class="stability_0"><a href="#zlib_zlib_bytesread">zlib.bytesRead</a></span></li> <li><a href="#zlib_zlib_byteswritten">zlib.bytesWritten</a></li> <li><a href="#zlib_zlib_close_callback">zlib.close([callback])</a></li> <li><a href="#zlib_zlib_flush_kind_callback">zlib.flush([kind, ]callback)</a></li> <li><a href="#zlib_zlib_params_level_strategy_callback">zlib.params(level, strategy, callback)</a></li> <li><a href="#zlib_zlib_reset">zlib.reset()</a></li> </ul> </li> <li><a href="#zlib_zlib_constants_1">zlib.constants</a></li> <li><a href="#zlib_zlib_createbrotlicompress_options">zlib.createBrotliCompress([options])</a></li> <li><a href="#zlib_zlib_createbrotlidecompress_options">zlib.createBrotliDecompress([options])</a></li> <li><a href="#zlib_zlib_createdeflate_options">zlib.createDeflate([options])</a></li> <li><a href="#zlib_zlib_createdeflateraw_options">zlib.createDeflateRaw([options])</a></li> <li><a href="#zlib_zlib_creategunzip_options">zlib.createGunzip([options])</a></li> <li><a href="#zlib_zlib_creategzip_options">zlib.createGzip([options])</a></li> <li><a href="#zlib_zlib_createinflate_options">zlib.createInflate([options])</a></li> <li><a href="#zlib_zlib_createinflateraw_options">zlib.createInflateRaw([options])</a></li> <li><a href="#zlib_zlib_createunzip_options">zlib.createUnzip([options])</a></li> <li> <p><a href="#zlib_convenience_methods">Convenience Methods</a></p> <ul> <li><a href="#zlib_zlib_brotlicompress_buffer_options_callback">zlib.brotliCompress(buffer[, options], callback)</a></li> <li><a href="#zlib_zlib_brotlicompresssync_buffer_options">zlib.brotliCompressSync(buffer[, options])</a></li> <li><a href="#zlib_zlib_brotlidecompress_buffer_options_callback">zlib.brotliDecompress(buffer[, options], callback)</a></li> <li><a href="#zlib_zlib_brotlidecompresssync_buffer_options">zlib.brotliDecompressSync(buffer[, options])</a></li> <li><a href="#zlib_zlib_deflate_buffer_options_callback">zlib.deflate(buffer[, options], callback)</a></li> <li><a href="#zlib_zlib_deflatesync_buffer_options">zlib.deflateSync(buffer[, options])</a></li> <li><a href="#zlib_zlib_deflateraw_buffer_options_callback">zlib.deflateRaw(buffer[, options], callback)</a></li> <li><a href="#zlib_zlib_deflaterawsync_buffer_options">zlib.deflateRawSync(buffer[, options])</a></li> <li><a href="#zlib_zlib_gunzip_buffer_options_callback">zlib.gunzip(buffer[, options], callback)</a></li> <li><a href="#zlib_zlib_gunzipsync_buffer_options">zlib.gunzipSync(buffer[, options])</a></li> <li><a href="#zlib_zlib_gzip_buffer_options_callback">zlib.gzip(buffer[, options], callback)</a></li> <li><a href="#zlib_zlib_gzipsync_buffer_options">zlib.gzipSync(buffer[, options])</a></li> <li><a href="#zlib_zlib_inflate_buffer_options_callback">zlib.inflate(buffer[, options], callback)</a></li> <li><a href="#zlib_zlib_inflatesync_buffer_options">zlib.inflateSync(buffer[, options])</a></li> <li><a href="#zlib_zlib_inflateraw_buffer_options_callback">zlib.inflateRaw(buffer[, options], callback)</a></li> <li><a href="#zlib_zlib_inflaterawsync_buffer_options">zlib.inflateRawSync(buffer[, options])</a></li> <li><a href="#zlib_zlib_unzip_buffer_options_callback">zlib.unzip(buffer[, options], callback)</a></li> <li><a href="#zlib_zlib_unzipsync_buffer_options">zlib.unzipSync(buffer[, options])</a></li> </ul> </li> </ul> </li> </ul> </div> <div id="apicontent"> <h1>About this Documentation<span><a class="mark" href="#documentation_about_this_documentation" id="documentation_about_this_documentation">#</a></span></h1> <p>The goal of this documentation is to comprehensively explain the Node.js API, both from a reference as well as a conceptual point of view. Each section describes a built-in module or high-level concept.</p> <p>Where appropriate, property types, method arguments, and the arguments provided to event handlers are detailed in a list underneath the topic heading.</p> <h2>Contributing<span><a class="mark" href="#documentation_contributing" id="documentation_contributing">#</a></span></h2> <p>If errors are found in this documentation, please <a href="https://github.com/nodejs/node/issues/new">submit an issue</a> or see <a href="https://github.com/nodejs/node/blob/master/CONTRIBUTING.md">the contributing guide</a> for directions on how to submit a patch.</p> <p>Every file is generated based on the corresponding <code>.md</code> file in the <code>doc/api/</code> folder in Node.js's source tree. The documentation is generated using the <code>tools/doc/generate.js</code> program. An HTML template is located at <code>doc/template.html</code>.</p> <h2>Stability Index<span><a class="mark" href="#documentation_stability_index" id="documentation_stability_index">#</a></span></h2> <p>Throughout the documentation are indications of a section's stability. The Node.js API is still somewhat changing, and as it matures, certain parts are more reliable than others. Some are so proven, and so relied upon, that they are unlikely to ever change at all. Others are brand new and experimental, or known to be hazardous and in the process of being redesigned.</p> <p>The stability indices are as follows:</p> <p></p><div class="api_stability api_stability_0">Stability: 0 - Deprecated. The feature may emit warnings. Backward compatibility is not guaranteed.</div><p></p> <!-- separator --> <p></p><div class="api_stability api_stability_1">Stability: 1 - Experimental. This feature is still under active development and subject to non-backward compatible changes or removal in any future version. Use of the feature is not recommended in production environments. Experimental features are not subject to the Node.js Semantic Versioning model.</div><p></p> <!-- separator --> <p></p><div class="api_stability api_stability_2">Stability: 2 - Stable. Compatibility with the npm ecosystem is a high priority.</div><p></p> <p>Caution must be used when making use of <code>Experimental</code> features, particularly within modules that may be used as dependencies (or dependencies of dependencies) within a Node.js application. End users may not be aware that experimental features are being used, and therefore may experience unexpected failures or behavior changes when API modifications occur. To help avoid such surprises, <code>Experimental</code> features may require a command-line flag to explicitly enable them, or may cause a process warning to be emitted. By default, such warnings are printed to <a href="#process_process_stderr"><code>stderr</code></a> and may be handled by attaching a listener to the <a href="#process_event_warning"><code>'warning'</code></a> event.</p> <h2>JSON Output<span><a class="mark" href="#documentation_json_output" id="documentation_json_output">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.6.12</span> </div> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>Every <code>.html</code> document has a corresponding <code>.json</code> document presenting the same information in a structured manner. This feature is experimental, and added for the benefit of IDEs and other utilities that wish to do programmatic things with the documentation.</p> <h2>Syscalls and man pages<span><a class="mark" href="#documentation_syscalls_and_man_pages" id="documentation_syscalls_and_man_pages">#</a></span></h2> <p>System calls like <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a> and <a href="http://man7.org/linux/man-pages/man2/read.2.html"><code>read(2)</code></a> define the interface between user programs and the underlying operating system. Node.js functions which simply wrap a syscall, like <a href="#fs_fs_open_path_flags_mode_callback"><code>fs.open()</code></a>, will document that. The docs link to the corresponding man pages (short for manual pages) which describe how the syscalls work.</p> <p>Most Unix syscalls have Windows equivalents, but behavior may differ on Windows relative to Linux and macOS. For an example of the subtle ways in which it's sometimes impossible to replace Unix syscall semantics on Windows, see <a href="https://github.com/nodejs/node/issues/4760">Node.js issue 4760</a>.</p> <h1>Usage<span><a class="mark" href="#synopsis_usage" id="synopsis_usage">#</a></span></h1> <p><code>node [options] [V8 options] [script.js | -e "script" | - ] [arguments]</code></p> <p>Please see the <a href="#cli_command_line_options">Command Line Options</a> document for information about different options and ways to run scripts with Node.js.</p> <h2>Example<span><a class="mark" href="#synopsis_example" id="synopsis_example">#</a></span></h2> <p>An example of a <a href="http.html">web server</a> written with Node.js which responds with <code>'Hello, World!'</code>:</p> <p>Commands displayed in this document are shown starting with <code>$</code> or <code>></code> to replicate how they would appear in a user's terminal. Do not include the <code>$</code> and <code>></code> characters. They are there to indicate the start of each command.</p> <p>There are many tutorials and examples that follow this convention: <code>$</code> or <code>></code> for commands run as a regular user, and <code>#</code> for commands that should be executed as an administrator.</p> <p>Lines that don’t start with <code>$</code> or <code>></code> character are typically showing the output of the previous command.</p> <p>Firstly, make sure to have downloaded and installed Node.js. See <a href="https://nodejs.org/en/download/package-manager/">this guide</a> for further install information.</p> <p>Now, create an empty project folder called <code>projects</code>, then navigate into it. The project folder can be named based on the user's current project title, but this example will use <code>projects</code> as the project folder.</p> <p>Linux and Mac:</p> <pre><code class="language-console">$ mkdir ~/projects $ cd ~/projects </code></pre> <p>Windows CMD:</p> <pre><code class="language-console">> mkdir %USERPROFILE%\projects > cd %USERPROFILE%\projects </code></pre> <p>Windows PowerShell:</p> <pre><code class="language-console">> mkdir $env:USERPROFILE\projects > cd $env:USERPROFILE\projects </code></pre> <p>Next, create a new source file in the <code>projects</code> folder and call it <code>hello-world.js</code>.</p> <p>In Node.js it is considered good style to use hyphens (<code>-</code>) or underscores (<code>_</code>) to separate multiple words in filenames.</p> <p>Open <code>hello-world.js</code> in any preferred text editor and paste in the following content:</p> <pre><code class="language-js">const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); </code></pre> <p>Save the file, go back to the terminal window enter the following command:</p> <pre><code class="language-console">$ node hello-world.js </code></pre> <p>An output like this should appear in the terminal to indicate Node.js server is running:</p> <pre><code class="language-console">Server running at http://127.0.0.1:3000/ </code></pre> <p>Now, open any preferred web browser and visit <code>http://127.0.0.1:3000</code>.</p> <p>If the browser displays the string <code>Hello, World!</code>, that indicates the server is working.</p> <p>Many of the examples in the documentation can be run similarly.</p> <h1>Assert<span><a class="mark" href="#assert_assert" id="assert_assert">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>assert</code> module provides a simple set of assertion tests that can be used to test invariants.</p> <p>A <code>strict</code> and a <code>legacy</code> mode exist, while it is recommended to only use <a href="#assert_strict_mode"><code>strict mode</code></a>.</p> <p>For more information about the used equality comparisons see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness">MDN's guide on equality comparisons and sameness</a>.</p> <h2>Class: assert.AssertionError<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L132">[src]</a><span><a class="mark" href="#assert_class_assert_assertionerror" id="assert_class_assert_assertionerror">#</a></span></h2> <p>A subclass of <code>Error</code> that indicates the failure of an assertion. All errors thrown by the <code>assert</code> module will be instances of the <code>AssertionError</code> class.</p> <h3>new assert.AssertionError(options)<span><a class="mark" href="#assert_new_assert_assertionerror_options" id="assert_new_assert_assertionerror_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.21</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If provided, the error message is going to be set to this value.</li> <li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The <code>actual</code> property on the error instance is going to contain this value. Internally used for the <code>actual</code> error input in case e.g., <a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual()</code></a> is used.</li> <li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The <code>expected</code> property on the error instance is going to contain this value. Internally used for the <code>expected</code> error input in case e.g., <a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual()</code></a> is used.</li> <li><code>operator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <code>operator</code> property on the error instance is going to contain this value. Internally used to indicate what operation was used for comparison (or what assertion function triggered the error).</li> <li><code>stackStartFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> If provided, the generated stack trace is going to remove all frames up to the provided function.</li> </ul> </li> </ul> <p>A subclass of <code>Error</code> that indicates the failure of an assertion.</p> <p>All instances contain the built-in <code>Error</code> properties (<code>message</code> and <code>name</code>) and:</p> <ul> <li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Set to the actual value in case e.g., <a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual()</code></a> is used.</li> <li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Set to the expected value in case e.g., <a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual()</code></a> is used.</li> <li><code>generatedMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates if the message was auto-generated (<code>true</code>) or not.</li> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> This is always set to the string <code>ERR_ASSERTION</code> to indicate that the error is actually an assertion error.</li> <li><code>operator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Set to the passed in operator value.</li> </ul> <pre><code class="language-js">const assert = require('assert'); // Generate an AssertionError to compare the error message later: const { message } = new assert.AssertionError({ actual: 1, expected: 2, operator: 'strictEqual' }); // Verify error output: try { assert.strictEqual(1, 2); } catch (err) { assert(err instanceof assert.AssertionError); assert.strictEqual(err.message, message); assert.strictEqual(err.name, 'AssertionError [ERR_ASSERTION]'); assert.strictEqual(err.actual, 1); assert.strictEqual(err.expected, 2); assert.strictEqual(err.code, 'ERR_ASSERTION'); assert.strictEqual(err.operator, 'strictEqual'); assert.strictEqual(err.generatedMessage, true); } </code></pre> <h2>Strict mode<span><a class="mark" href="#assert_strict_mode" id="assert_strict_mode">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.9.0</td> <td><p>Added error diffs to the strict mode</p></td></tr> <tr><td>v9.9.0</td> <td><p>Added strict mode to the assert module.</p></td></tr> <tr><td>v9.9.0</td> <td><p><span>Added in: v9.9.0</span></p></td></tr> </tbody></table> </details> </div> <p>When using the <code>strict mode</code>, any <code>assert</code> function will use the equality used in the strict function mode. So <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a> will, for example, work the same as <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a>.</p> <p>On top of that, error messages which involve objects produce an error diff instead of displaying both objects. That is not the case for the legacy mode.</p> <p>It can be accessed using:</p> <pre><code class="language-js">const assert = require('assert').strict; </code></pre> <p>Example error diff:</p> <pre><code class="language-js">const assert = require('assert').strict; assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); // AssertionError: Input A expected to strictly deep-equal input B: // + expected - actual ... Lines skipped // // [ // [ // ... // 2, // - 3 // + '3' // ], // ... // 5 // ] </code></pre> <p>To deactivate the colors, use the <code>NODE_DISABLE_COLORS</code> environment variable. Please note that this will also deactivate the colors in the REPL.</p> <h2>Legacy mode<span><a class="mark" href="#assert_legacy_mode" id="assert_legacy_mode">#</a></span></h2> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use strict mode instead.</div><p></p> <p>When accessing <code>assert</code> directly instead of using the <code>strict</code> property, the <a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">Abstract Equality Comparison</a> will be used for any function without "strict" in its name, such as <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a>.</p> <p>It can be accessed using:</p> <pre><code class="language-js">const assert = require('assert'); </code></pre> <p>It is recommended to use the <a href="#assert_strict_mode"><code>strict mode</code></a> instead as the <a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">Abstract Equality Comparison</a> can often have surprising results. This is especially true for <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a>, where the comparison rules are lax:</p> <pre><code class="language-js">// WARNING: This does not throw an AssertionError! assert.deepEqual(/a/gi, new Date()); </code></pre> <h2>assert(value[, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L71">[src]</a><span><a class="mark" href="#assert_assert_value_message" id="assert_assert_value_message">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The input that is checked for being truthy.</li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>An alias of <a href="#assert_assert_ok_value_message"><code>assert.ok()</code></a>.</p> <h2>assert.deepEqual(actual, expected[, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L381">[src]</a><span><a class="mark" href="#assert_assert_deepequal_actual_expected_message" id="assert_assert_deepequal_actual_expected_message">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>The <code>Error</code> names and messages are now properly compared</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>Set</code> and <code>Map</code> content is also compared</p></td></tr> <tr><td>v6.4.0, v4.7.1</td> <td><p>Typed array slices are handled correctly now.</p></td></tr> <tr><td>v6.1.0, v4.5.0</td> <td><p>Objects with circular references can be used as inputs now.</p></td></tr> <tr><td>v5.10.1, v4.4.3</td> <td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p><strong>Strict mode</strong></p> <p>An alias of <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a>.</p> <p><strong>Legacy mode</strong></p> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a> instead.</div><p></p> <p>Tests for deep equality between the <code>actual</code> and <code>expected</code> parameters. Primitive values are compared with the <a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">Abstract Equality Comparison</a> ( <code>==</code> ).</p> <p>Only <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">enumerable "own" properties</a> are considered. The <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a> implementation does not test the <a href="https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots"><code>[[Prototype]]</code></a> of objects or enumerable own <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol"><code>Symbol</code></a> properties. For such checks, consider using <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a> instead. <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a> can have potentially surprising results. The following example does not throw an <code>AssertionError</code> because the properties on the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a> object are not enumerable:</p> <pre><code class="language-js">// WARNING: This does not throw an AssertionError! assert.deepEqual(/a/gi, new Date()); </code></pre> <p>An exception is made for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a>. <code>Map</code>s and <code>Set</code>s have their contained items compared too, as expected.</p> <p>"Deep" equality means that the enumerable "own" properties of child objects are evaluated also:</p> <pre><code class="language-js">const assert = require('assert'); const obj1 = { a: { b: 1 } }; const obj2 = { a: { b: 2 } }; const obj3 = { a: { b: 1 } }; const obj4 = Object.create(obj1); assert.deepEqual(obj1, obj1); // OK // Values of b are different: assert.deepEqual(obj1, obj2); // AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } } assert.deepEqual(obj1, obj3); // OK // Prototypes are ignored: assert.deepEqual(obj1, obj4); // AssertionError: { a: { b: 1 } } deepEqual {} </code></pre> <p>If the values are not equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. If the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the <code>AssertionError</code>.</p> <h2>assert.deepStrictEqual(actual, expected[, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L409">[src]</a><span><a class="mark" href="#assert_assert_deepstrictequal_actual_expected_message" id="assert_assert_deepstrictequal_actual_expected_message">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Enumerable symbol properties are now compared.</p></td></tr> <tr><td>v9.0.0</td> <td><p>The <code>NaN</code> is now compared using the <a href="https://tc39.github.io/ecma262/#sec-samevaluezero">SameValueZero</a> comparison.</p></td></tr> <tr><td>v8.5.0</td> <td><p>The <code>Error</code> names and messages are now properly compared</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>Set</code> and <code>Map</code> content is also compared</p></td></tr> <tr><td>v6.4.0, v4.7.1</td> <td><p>Typed array slices are handled correctly now.</p></td></tr> <tr><td>v6.1.0</td> <td><p>Objects with circular references can be used as inputs now.</p></td></tr> <tr><td>v5.10.1, v4.4.3</td> <td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr> <tr><td>v1.2.0</td> <td><p><span>Added in: v1.2.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Tests for deep equality between the <code>actual</code> and <code>expected</code> parameters. "Deep" equality means that the enumerable "own" properties of child objects are recursively evaluated also by the following rules.</p> <h3>Comparison details<span><a class="mark" href="#assert_comparison_details" id="assert_comparison_details">#</a></span></h3> <ul> <li>Primitive values are compared using the <a href="https://tc39.github.io/ecma262/#sec-samevalue">SameValue Comparison</a>, used by <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is"><code>Object.is()</code></a>.</li> <li><a href="https://tc39.github.io/ecma262/#sec-object.prototype.tostring">Type tags</a> of objects should be the same.</li> <li><a href="https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots"><code>[[Prototype]]</code></a> of objects are compared using the <a href="https://tc39.github.io/ecma262/#sec-strict-equality-comparison">Strict Equality Comparison</a>.</li> <li>Only <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">enumerable "own" properties</a> are considered.</li> <li><a href="#errors_class_error"><code>Error</code></a> names and messages are always compared, even if these are not enumerable properties.</li> <li>Enumerable own <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol"><code>Symbol</code></a> properties are compared as well.</li> <li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript">Object wrappers</a> are compared both as objects and unwrapped values.</li> <li><code>Object</code> properties are compared unordered.</li> <li><code>Map</code> keys and <code>Set</code> items are compared unordered.</li> <li>Recursion stops when both sides differ or both sides encounter a circular reference.</li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> comparison does not rely on their values. See below for further details.</li> </ul> <pre><code class="language-js">const assert = require('assert').strict; // This fails because 1 !== '1'. assert.deepStrictEqual({ a: 1 }, { a: '1' }); // AssertionError: Input A expected to strictly deep-equal input B: // + expected - actual // { // - a: 1 // + a: '1' // } // The following objects don't have own properties const date = new Date(); const object = {}; const fakeDate = {}; Object.setPrototypeOf(fakeDate, Date.prototype); // Different [[Prototype]]: assert.deepStrictEqual(object, fakeDate); // AssertionError: Input A expected to strictly deep-equal input B: // + expected - actual // - {} // + Date {} // Different type tags: assert.deepStrictEqual(date, fakeDate); // AssertionError: Input A expected to strictly deep-equal input B: // + expected - actual // - 2018-04-26T00:49:08.604Z // + Date {} assert.deepStrictEqual(NaN, NaN); // OK, because of the SameValue comparison // Different unwrapped numbers: assert.deepStrictEqual(new Number(1), new Number(2)); // AssertionError: Input A expected to strictly deep-equal input B: // + expected - actual // - [Number: 1] // + [Number: 2] assert.deepStrictEqual(new String('foo'), Object('foo')); // OK because the object and the string are identical when unwrapped. assert.deepStrictEqual(-0, -0); // OK // Different zeros using the SameValue Comparison: assert.deepStrictEqual(0, -0); // AssertionError: Input A expected to strictly deep-equal input B: // + expected - actual // - 0 // + -0 const symbol1 = Symbol(); const symbol2 = Symbol(); assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 }); // OK, because it is the same symbol on both objects. assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 }); // AssertionError [ERR_ASSERTION]: Input objects not identical: // { // [Symbol()]: 1 // } const weakMap1 = new WeakMap(); const weakMap2 = new WeakMap([[{}, {}]]); const weakMap3 = new WeakMap(); weakMap3.unequal = true; assert.deepStrictEqual(weakMap1, weakMap2); // OK, because it is impossible to compare the entries // Fails because weakMap3 has a property that weakMap1 does not contain: assert.deepStrictEqual(weakMap1, weakMap3); // AssertionError: Input A expected to strictly deep-equal input B: // + expected - actual // WeakMap { // - [items unknown] // + [items unknown], // + unequal: true // } </code></pre> <p>If the values are not equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. If the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the <code>AssertionError</code>.</p> <h2>assert.doesNotReject(asyncFn[, error][, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L690">[src]</a><span><a class="mark" href="#assert_assert_doesnotreject_asyncfn_error_message" id="assert_assert_doesnotreject_asyncfn_error_message">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>asyncFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type"><RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Awaits the <code>asyncFn</code> promise or, if <code>asyncFn</code> is a function, immediately calls the function and awaits the returned promise to complete. It will then check that the promise is not rejected.</p> <p>If <code>asyncFn</code> is a function and it throws an error synchronously, <code>assert.doesNotReject()</code> will return a rejected <code>Promise</code> with that error. If the function does not return a promise, <code>assert.doesNotReject()</code> will return a rejected <code>Promise</code> with an <a href="#errors_err_invalid_return_value"><code>ERR_INVALID_RETURN_VALUE</code></a> error. In both cases the error handler is skipped.</p> <p>Using <code>assert.doesNotReject()</code> is actually not useful because there is little benefit in catching a rejection and then rejecting it again. Instead, consider adding a comment next to the specific code path that should not reject and keep error messages as expressive as possible.</p> <p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a> or a validation function. See <a href="#assert_assert_throws_fn_error_message"><code>assert.throws()</code></a> for more details.</p> <p>Besides the async nature to await the completion behaves identically to <a href="#assert_assert_doesnotthrow_fn_error_message"><code>assert.doesNotThrow()</code></a>.</p> <pre><code class="language-js">(async () => { await assert.doesNotReject( async () => { throw new TypeError('Wrong value'); }, SyntaxError ); })(); </code></pre> <pre><code class="language-js">assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) .then(() => { // ... }); </code></pre> <h2>assert.doesNotThrow(fn[, error][, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L686">[src]</a><span><a class="mark" href="#assert_assert_doesnotthrow_fn_error_message" id="assert_assert_doesnotthrow_fn_error_message">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v5.11.0, v4.4.5</td> <td><p>The <code>message</code> parameter is respected now.</p></td></tr> <tr><td>v4.2.0</td> <td><p>The <code>error</code> parameter can now be an arrow function.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type"><RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Asserts that the function <code>fn</code> does not throw an error.</p> <p>Using <code>assert.doesNotThrow()</code> is actually not useful because there is no benefit in catching an error and then rethrowing it. Instead, consider adding a comment next to the specific code path that should not throw and keep error messages as expressive as possible.</p> <p>When <code>assert.doesNotThrow()</code> is called, it will immediately call the <code>fn</code> function.</p> <p>If an error is thrown and it is the same type as that specified by the <code>error</code> parameter, then an <code>AssertionError</code> is thrown. If the error is of a different type, or if the <code>error</code> parameter is undefined, the error is propagated back to the caller.</p> <p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a> or a validation function. See <a href="#assert_assert_throws_fn_error_message"><code>assert.throws()</code></a> for more details.</p> <p>The following, for instance, will throw the <a href="#errors_class_typeerror"><code>TypeError</code></a> because there is no matching error type in the assertion:</p> <!-- eslint-disable no-restricted-syntax --> <pre><code class="language-js">assert.doesNotThrow( () => { throw new TypeError('Wrong value'); }, SyntaxError ); </code></pre> <p>However, the following will result in an <code>AssertionError</code> with the message 'Got unwanted exception...':</p> <!-- eslint-disable no-restricted-syntax --> <pre><code class="language-js">assert.doesNotThrow( () => { throw new TypeError('Wrong value'); }, TypeError ); </code></pre> <p>If an <code>AssertionError</code> is thrown and a value is provided for the <code>message</code> parameter, the value of <code>message</code> will be appended to the <code>AssertionError</code> message:</p> <!-- eslint-disable no-restricted-syntax --> <pre><code class="language-js">assert.doesNotThrow( () => { throw new TypeError('Wrong value'); }, /Wrong value/, 'Whoops' ); // Throws: AssertionError: Got unwanted exception: Whoops </code></pre> <h2>assert.equal(actual, expected[, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L352">[src]</a><span><a class="mark" href="#assert_assert_equal_actual_expected_message" id="assert_assert_equal_actual_expected_message">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.21</span> </div> <ul> <li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p><strong>Strict mode</strong></p> <p>An alias of <a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual()</code></a>.</p> <p><strong>Legacy mode</strong></p> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual()</code></a> instead.</div><p></p> <p>Tests shallow, coercive equality between the <code>actual</code> and <code>expected</code> parameters using the <a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">Abstract Equality Comparison</a> ( <code>==</code> ).</p> <pre><code class="language-js">const assert = require('assert'); assert.equal(1, 1); // OK, 1 == 1 assert.equal(1, '1'); // OK, 1 == '1' assert.equal(1, 2); // AssertionError: 1 == 2 assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } </code></pre> <p>If the values are not equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. If the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the <code>AssertionError</code>.</p> <h2>assert.fail([message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L87">[src]</a><span><a class="mark" href="#assert_assert_fail_message" id="assert_assert_fail_message">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.21</span> </div> <ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> <strong>Default:</strong> <code>'Failed'</code></li> </ul> <p>Throws an <code>AssertionError</code> with the provided error message or a default error message. If the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the <code>AssertionError</code>.</p> <pre><code class="language-js">const assert = require('assert').strict; assert.fail(); // AssertionError [ERR_ASSERTION]: Failed assert.fail('boom'); // AssertionError [ERR_ASSERTION]: boom assert.fail(new TypeError('need array')); // TypeError: need array </code></pre> <p>Using <code>assert.fail()</code> with more than two arguments is possible but deprecated. See below for further details.</p> <h2>assert.fail(actual, expected[, message[, operator[, stackStartFn]]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L87">[src]</a><span><a class="mark" href="#assert_assert_fail_actual_expected_message_operator_stackstartfn" id="assert_assert_fail_actual_expected_message_operator_stackstartfn">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Calling <code>assert.fail()</code> with more than one argument is deprecated and emits a warning.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>operator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'!='</code></li> <li><code>stackStartFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> <strong>Default:</strong> <code>assert.fail</code></li> </ul> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>assert.fail([message])</code> or other assert functions instead.</div><p></p> <p>If <code>message</code> is falsy, the error message is set as the values of <code>actual</code> and <code>expected</code> separated by the provided <code>operator</code>. If just the two <code>actual</code> and <code>expected</code> arguments are provided, <code>operator</code> will default to <code>'!='</code>. If <code>message</code> is provided as third argument it will be used as the error message and the other arguments will be stored as properties on the thrown object. If <code>stackStartFn</code> is provided, all stack frames above that function will be removed from stacktrace (see <a href="#errors_error_capturestacktrace_targetobject_constructoropt"><code>Error.captureStackTrace</code></a>). If no arguments are given, the default message <code>Failed</code> will be used.</p> <pre><code class="language-js">const assert = require('assert').strict; assert.fail('a', 'b'); // AssertionError [ERR_ASSERTION]: 'a' != 'b' assert.fail(1, 2, undefined, '>'); // AssertionError [ERR_ASSERTION]: 1 > 2 assert.fail(1, 2, 'fail'); // AssertionError [ERR_ASSERTION]: fail assert.fail(1, 2, 'whoops', '>'); // AssertionError [ERR_ASSERTION]: whoops assert.fail(1, 2, new TypeError('need array')); // TypeError: need array </code></pre> <p>In the last three cases <code>actual</code>, <code>expected</code>, and <code>operator</code> have no influence on the error message.</p> <p>Example use of <code>stackStartFn</code> for truncating the exception's stacktrace:</p> <pre><code class="language-js">function suppressFrame() { assert.fail('a', 'b', undefined, '!==', suppressFrame); } suppressFrame(); // AssertionError [ERR_ASSERTION]: 'a' !== 'b' // at repl:1:1 // at ContextifyScript.Script.runInThisContext (vm.js:44:33) // ... </code></pre> <h2>assert.ifError(value)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L694">[src]</a><span><a class="mark" href="#assert_assert_iferror_value" id="assert_assert_iferror_value">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Instead of throwing the original error it is now wrapped into an <code>AssertionError</code> that contains the full stack trace.</p></td></tr> <tr><td>v10.0.0</td> <td><p>Value may now only be <code>undefined</code> or <code>null</code>. Before all falsy values were handled the same as <code>null</code> and did not throw.</p></td></tr> <tr><td>v0.1.97</td> <td><p><span>Added in: v0.1.97</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Throws <code>value</code> if <code>value</code> is not <code>undefined</code> or <code>null</code>. This is useful when testing the <code>error</code> argument in callbacks. The stack trace contains all frames from the error passed to <code>ifError()</code> including the potential new frames for <code>ifError()</code> itself.</p> <pre><code class="language-js">const assert = require('assert').strict; assert.ifError(null); // OK assert.ifError(0); // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 assert.ifError('error'); // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' assert.ifError(new Error()); // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error // Create some random error frames. let err; (function errorFrame() { err = new Error('test error'); })(); (function ifErrorFrame() { assert.ifError(err); })(); // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error // at ifErrorFrame // at errorFrame </code></pre> <h2>assert.notDeepEqual(actual, expected[, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L395">[src]</a><span><a class="mark" href="#assert_assert_notdeepequal_actual_expected_message" id="assert_assert_notdeepequal_actual_expected_message">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>The <code>Error</code> names and messages are now properly compared</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>Set</code> and <code>Map</code> content is also compared</p></td></tr> <tr><td>v6.4.0, v4.7.1</td> <td><p>Typed array slices are handled correctly now.</p></td></tr> <tr><td>v6.1.0, v4.5.0</td> <td><p>Objects with circular references can be used as inputs now.</p></td></tr> <tr><td>v5.10.1, v4.4.3</td> <td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p><strong>Strict mode</strong></p> <p>An alias of <a href="#assert_assert_notdeepstrictequal_actual_expected_message"><code>assert.notDeepStrictEqual()</code></a>.</p> <p><strong>Legacy mode</strong></p> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#assert_assert_notdeepstrictequal_actual_expected_message"><code>assert.notDeepStrictEqual()</code></a> instead.</div><p></p> <p>Tests for any deep inequality. Opposite of <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a>.</p> <pre><code class="language-js">const assert = require('assert'); const obj1 = { a: { b: 1 } }; const obj2 = { a: { b: 2 } }; const obj3 = { a: { b: 1 } }; const obj4 = Object.create(obj1); assert.notDeepEqual(obj1, obj1); // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } assert.notDeepEqual(obj1, obj2); // OK assert.notDeepEqual(obj1, obj3); // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } assert.notDeepEqual(obj1, obj4); // OK </code></pre> <p>If the values are deeply equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. If the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the <code>AssertionError</code>.</p> <h2>assert.notDeepStrictEqual(actual, expected[, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L423">[src]</a><span><a class="mark" href="#assert_assert_notdeepstrictequal_actual_expected_message" id="assert_assert_notdeepstrictequal_actual_expected_message">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>The <code>-0</code> and <code>+0</code> are not considered equal anymore.</p></td></tr> <tr><td>v9.0.0</td> <td><p>The <code>NaN</code> is now compared using the <a href="https://tc39.github.io/ecma262/#sec-samevaluezero">SameValueZero</a> comparison.</p></td></tr> <tr><td>v9.0.0</td> <td><p>The <code>Error</code> names and messages are now properly compared</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>Set</code> and <code>Map</code> content is also compared</p></td></tr> <tr><td>v6.4.0, v4.7.1</td> <td><p>Typed array slices are handled correctly now.</p></td></tr> <tr><td>v6.1.0</td> <td><p>Objects with circular references can be used as inputs now.</p></td></tr> <tr><td>v5.10.1, v4.4.3</td> <td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr> <tr><td>v1.2.0</td> <td><p><span>Added in: v1.2.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Tests for deep strict inequality. Opposite of <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a>.</p> <pre><code class="language-js">const assert = require('assert').strict; assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); // OK </code></pre> <p>If the values are deeply and strictly equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. If the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the <code>AssertionError</code>.</p> <h2>assert.notEqual(actual, expected[, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L367">[src]</a><span><a class="mark" href="#assert_assert_notequal_actual_expected_message" id="assert_assert_notequal_actual_expected_message">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.21</span> </div> <ul> <li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p><strong>Strict mode</strong></p> <p>An alias of <a href="#assert_assert_notstrictequal_actual_expected_message"><code>assert.notStrictEqual()</code></a>.</p> <p><strong>Legacy mode</strong></p> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#assert_assert_notstrictequal_actual_expected_message"><code>assert.notStrictEqual()</code></a> instead.</div><p></p> <p>Tests shallow, coercive inequality with the <a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">Abstract Equality Comparison</a> ( <code>!=</code> ).</p> <pre><code class="language-js">const assert = require('assert'); assert.notEqual(1, 2); // OK assert.notEqual(1, 1); // AssertionError: 1 != 1 assert.notEqual(1, '1'); // AssertionError: 1 != '1' </code></pre> <p>If the values are equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. If the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the <code>AssertionError</code>.</p> <h2>assert.notStrictEqual(actual, expected[, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L448">[src]</a><span><a class="mark" href="#assert_assert_notstrictequal_actual_expected_message" id="assert_assert_notstrictequal_actual_expected_message">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Used comparison changed from Strict Equality to <code>Object.is()</code></p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Tests strict inequality between the <code>actual</code> and <code>expected</code> parameters as determined by the <a href="https://tc39.github.io/ecma262/#sec-samevalue">SameValue Comparison</a>.</p> <pre><code class="language-js">const assert = require('assert').strict; assert.notStrictEqual(1, 2); // OK assert.notStrictEqual(1, 1); // AssertionError [ERR_ASSERTION]: Identical input passed to notStrictEqual: 1 assert.notStrictEqual(1, '1'); // OK </code></pre> <p>If the values are strictly equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. If the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the <code>AssertionError</code>.</p> <h2>assert.ok(value[, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L345">[src]</a><span><a class="mark" href="#assert_assert_ok_value_message" id="assert_assert_ok_value_message">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>assert.ok()</code> (no arguments) will now use a predefined error message.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Tests if <code>value</code> is truthy. It is equivalent to <code>assert.equal(!!value, true, message)</code>.</p> <p>If <code>value</code> is not truthy, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is <code>undefined</code>, a default error message is assigned. If the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the <code>AssertionError</code>. If no arguments are passed in at all <code>message</code> will be set to the string: <code>'No value argument passed to `assert.ok()`'</code>.</p> <p>Be aware that in the <code>repl</code> the error message will be different to the one thrown in a file! See below for further details.</p> <pre><code class="language-js">const assert = require('assert').strict; assert.ok(true); // OK assert.ok(1); // OK assert.ok(); // AssertionError: No value argument passed to `assert.ok()` assert.ok(false, 'it\'s false'); // AssertionError: it's false // In the repl: assert.ok(typeof 123 === 'string'); // AssertionError: false == true // In a file (e.g. test.js): assert.ok(typeof 123 === 'string'); // AssertionError: The expression evaluated to a falsy value: // // assert.ok(typeof 123 === 'string') assert.ok(false); // AssertionError: The expression evaluated to a falsy value: // // assert.ok(false) assert.ok(0); // AssertionError: The expression evaluated to a falsy value: // // assert.ok(0) // Using `assert()` works the same: assert(0); // AssertionError: The expression evaluated to a falsy value: // // assert(0) </code></pre> <h2>assert.rejects(asyncFn[, error][, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L682">[src]</a><span><a class="mark" href="#assert_assert_rejects_asyncfn_error_message" id="assert_assert_rejects_asyncfn_error_message">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>asyncFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type"><RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Awaits the <code>asyncFn</code> promise or, if <code>asyncFn</code> is a function, immediately calls the function and awaits the returned promise to complete. It will then check that the promise is rejected.</p> <p>If <code>asyncFn</code> is a function and it throws an error synchronously, <code>assert.rejects()</code> will return a rejected <code>Promise</code> with that error. If the function does not return a promise, <code>assert.rejects()</code> will return a rejected <code>Promise</code> with an <a href="#errors_err_invalid_return_value"><code>ERR_INVALID_RETURN_VALUE</code></a> error. In both cases the error handler is skipped.</p> <p>Besides the async nature to await the completion behaves identically to <a href="#assert_assert_throws_fn_error_message"><code>assert.throws()</code></a>.</p> <p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>, a validation function, an object where each property will be tested for, or an instance of error where each property will be tested for including the non-enumerable <code>message</code> and <code>name</code> properties.</p> <p>If specified, <code>message</code> will be the message provided by the <code>AssertionError</code> if the <code>asyncFn</code> fails to reject.</p> <pre><code class="language-js">(async () => { await assert.rejects( async () => { throw new TypeError('Wrong value'); }, { name: 'TypeError', message: 'Wrong value' } ); })(); </code></pre> <pre><code class="language-js">assert.rejects( Promise.reject(new Error('Wrong value')), Error ).then(() => { // ... }); </code></pre> <p>Note that <code>error</code> cannot be a string. If a string is provided as the second argument, then <code>error</code> is assumed to be omitted and the string will be used for <code>message</code> instead. This can lead to easy-to-miss mistakes. Please read the example in <a href="#assert_assert_throws_fn_error_message"><code>assert.throws()</code></a> carefully if using a string as the second argument gets considered.</p> <h2>assert.strictEqual(actual, expected[, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L436">[src]</a><span><a class="mark" href="#assert_assert_strictequal_actual_expected_message" id="assert_assert_strictequal_actual_expected_message">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Used comparison changed from Strict Equality to <code>Object.is()</code></p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Tests strict equality between the <code>actual</code> and <code>expected</code> parameters as determined by the <a href="https://tc39.github.io/ecma262/#sec-samevalue">SameValue Comparison</a>.</p> <pre><code class="language-js">const assert = require('assert').strict; assert.strictEqual(1, 2); // AssertionError [ERR_ASSERTION]: Input A expected to strictly equal input B: // + expected - actual // - 1 // + 2 assert.strictEqual(1, 1); // OK assert.strictEqual(1, '1'); // AssertionError [ERR_ASSERTION]: Input A expected to strictly equal input B: // + expected - actual // - 1 // + '1' </code></pre> <p>If the values are not strictly equal, an <code>AssertionError</code> is thrown with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If the <code>message</code> parameter is undefined, a default error message is assigned. If the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the <code>AssertionError</code>.</p> <h2>assert.throws(fn[, error][, message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/assert.js#L678">[src]</a><span><a class="mark" href="#assert_assert_throws_fn_error_message" id="assert_assert_throws_fn_error_message">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.2.0</td> <td><p>The <code>error</code> parameter can be an object containing regular expressions now.</p></td></tr> <tr><td>v9.9.0</td> <td><p>The <code>error</code> parameter can now be an object as well.</p></td></tr> <tr><td>v4.2.0</td> <td><p>The <code>error</code> parameter can now be an arrow function.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type"><RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Expects the function <code>fn</code> to throw an error.</p> <p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>, a validation function, a validation object where each property will be tested for strict deep equality, or an instance of error where each property will be tested for strict deep equality including the non-enumerable <code>message</code> and <code>name</code> properties. When using an object, it is also possible to use a regular expression, when validating against a string property. See below for examples.</p> <p>If specified, <code>message</code> will be appended to the message provided by the <code>AssertionError</code> if the <code>fn</code> call fails to throw or in case the error validation fails.</p> <p>Custom validation object/error instance:</p> <pre><code class="language-js">const err = new TypeError('Wrong value'); err.code = 404; err.foo = 'bar'; err.info = { nested: true, baz: 'text' }; err.reg = /abc/i; assert.throws( () => { throw err; }, { name: 'TypeError', message: 'Wrong value', info: { nested: true, baz: 'text' } // Note that only properties on the validation object will be tested for. // Using nested objects requires all properties to be present. Otherwise // the validation is going to fail. } ); // Using regular expressions to validate error properties: assert.throws( () => { throw err; }, { // The `name` and `message` properties are strings and using regular // expressions on those will match against the string. If they fail, an // error is thrown. name: /^TypeError$/, message: /Wrong/, foo: 'bar', info: { nested: true, // It is not possible to use regular expressions for nested properties! baz: 'text' }, // The `reg` property contains a regular expression and only if the // validation object contains an identical regular expression, it is going // to pass. reg: /abc/i } ); // Fails due to the different `message` and `name` properties: assert.throws( () => { const otherErr = new Error('Not found'); otherErr.code = 404; throw otherErr; }, err // This tests for `message`, `name` and `code`. ); </code></pre> <p>Validate instanceof using constructor:</p> <pre><code class="language-js">assert.throws( () => { throw new Error('Wrong value'); }, Error ); </code></pre> <p>Validate error message using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>:</p> <p>Using a regular expression runs <code>.toString</code> on the error object, and will therefore also include the error name.</p> <pre><code class="language-js">assert.throws( () => { throw new Error('Wrong value'); }, /^Error: Wrong value$/ ); </code></pre> <p>Custom error validation:</p> <pre><code class="language-js">assert.throws( () => { throw new Error('Wrong value'); }, function(err) { if ((err instanceof Error) && /value/.test(err)) { return true; } }, 'unexpected error' ); </code></pre> <p>Note that <code>error</code> cannot be a string. If a string is provided as the second argument, then <code>error</code> is assumed to be omitted and the string will be used for <code>message</code> instead. This can lead to easy-to-miss mistakes. Using the same message as the thrown error message is going to result in an <code>ERR_AMBIGUOUS_ARGUMENT</code> error. Please read the example below carefully if using a string as the second argument gets considered:</p> <!-- eslint-disable no-restricted-syntax --> <pre><code class="language-js">function throwingFirst() { throw new Error('First'); } function throwingSecond() { throw new Error('Second'); } function notThrowing() {} // The second argument is a string and the input function threw an Error. // The first case will not throw as it does not match for the error message // thrown by the input function! assert.throws(throwingFirst, 'Second'); // In the next example the message has no benefit over the message from the // error and since it is not clear if the user intended to actually match // against the error message, Node.js thrown an `ERR_AMBIGUOUS_ARGUMENT` error. assert.throws(throwingSecond, 'Second'); // Throws an error: // TypeError [ERR_AMBIGUOUS_ARGUMENT] // The string is only used (as message) in case the function does not throw: assert.throws(notThrowing, 'Second'); // AssertionError [ERR_ASSERTION]: Missing expected exception: Second // If it was intended to match for the error message do this instead: assert.throws(throwingSecond, /Second$/); // Does not throw because the error messages match. assert.throws(throwingFirst, /Second$/); // Throws an error: // Error: First // at throwingFirst (repl:2:9) </code></pre> <p>Due to the confusing notation, it is recommended not to use a string as the second argument. This might lead to difficult-to-spot errors.</p> <h1>Async Hooks<span><a class="mark" href="#async_hooks_async_hooks" id="async_hooks_async_hooks">#</a></span></h1> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>The <code>async_hooks</code> module provides an API to register callbacks tracking the lifetime of asynchronous resources created inside a Node.js application. It can be accessed using:</p> <pre><code class="language-js">const async_hooks = require('async_hooks'); </code></pre> <h2>Terminology<span><a class="mark" href="#async_hooks_terminology" id="async_hooks_terminology">#</a></span></h2> <p>An asynchronous resource represents an object with an associated callback. This callback may be called multiple times, for example, the <code>'connection'</code> event in <code>net.createServer()</code>, or just a single time like in <code>fs.open()</code>. A resource can also be closed before the callback is called. <code>AsyncHook</code> does not explicitly distinguish between these different cases but will represent them as the abstract concept that is a resource.</p> <p>If <a href="#worker_threads_class_worker"><code>Worker</code></a>s are used, each thread has an independent <code>async_hooks</code> interface, and each thread will use a new set of async IDs.</p> <h2>Public API<span><a class="mark" href="#async_hooks_public_api" id="async_hooks_public_api">#</a></span></h2> <h3>Overview<span><a class="mark" href="#async_hooks_overview" id="async_hooks_overview">#</a></span></h3> <p>Following is a simple overview of the public API.</p> <pre><code class="language-js">const async_hooks = require('async_hooks'); // Return the ID of the current execution context. const eid = async_hooks.executionAsyncId(); // Return the ID of the handle responsible for triggering the callback of the // current execution scope to call. const tid = async_hooks.triggerAsyncId(); // Create a new AsyncHook instance. All of these callbacks are optional. const asyncHook = async_hooks.createHook({ init, before, after, destroy, promiseResolve }); // Allow callbacks of this AsyncHook instance to call. This is not an implicit // action after running the constructor, and must be explicitly run to begin // executing callbacks. asyncHook.enable(); // Disable listening for new asynchronous events. asyncHook.disable(); // // The following are the callbacks that can be passed to createHook(). // // init is called during object construction. The resource may not have // completed construction when this callback runs, therefore all fields of the // resource referenced by "asyncId" may not have been populated. function init(asyncId, type, triggerAsyncId, resource) { } // before is called just before the resource's callback is called. It can be // called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1 // time for requests (e.g. FSReqWrap). function before(asyncId) { } // after is called just after the resource's callback has finished. function after(asyncId) { } // destroy is called when an AsyncWrap instance is destroyed. function destroy(asyncId) { } // promiseResolve is called only for promise resources, when the // `resolve` function passed to the `Promise` constructor is invoked // (either directly or through other means of resolving a promise). function promiseResolve(asyncId) { } </code></pre> <h4>async_hooks.createHook(callbacks)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L121">[src]</a><span><a class="mark" href="#async_hooks_async_hooks_createhook_callbacks" id="async_hooks_async_hooks_createhook_callbacks">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.1.0</span> </div> <ul> <li> <p><code>callbacks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#async_hooks_hook_callbacks">Hook Callbacks</a> to register</p> <ul> <li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> callback</a>.</li> <li><code>before</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#async_hooks_before_asyncid"><code>before</code> callback</a>.</li> <li><code>after</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#async_hooks_after_asyncid"><code>after</code> callback</a>.</li> <li><code>destroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The <a href="#async_hooks_destroy_asyncid"><code>destroy</code> callback</a>.</li> </ul> </li> <li>Returns: <a href="#async_hooks_async_hooks_createhook_callbacks" class="type"><AsyncHook></a> Instance used for disabling and enabling hooks</li> </ul> <p>Registers functions to be called for different lifetime events of each async operation.</p> <p>The callbacks <code>init()</code>/<code>before()</code>/<code>after()</code>/<code>destroy()</code> are called for the respective asynchronous event during a resource's lifetime.</p> <p>All callbacks are optional. For example, if only resource cleanup needs to be tracked, then only the <code>destroy</code> callback needs to be passed. The specifics of all functions that can be passed to <code>callbacks</code> is in the <a href="#async_hooks_hook_callbacks">Hook Callbacks</a> section.</p> <pre><code class="language-js">const async_hooks = require('async_hooks'); const asyncHook = async_hooks.createHook({ init(asyncId, type, triggerAsyncId, resource) { }, destroy(asyncId) { } }); </code></pre> <p>Note that the callbacks will be inherited via the prototype chain:</p> <pre><code class="language-js">class MyAsyncCallbacks { init(asyncId, type, triggerAsyncId, resource) { } destroy(asyncId) {} } class MyAddedCallbacks extends MyAsyncCallbacks { before(asyncId) { } after(asyncId) { } } const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); </code></pre> <h5>Error Handling<span><a class="mark" href="#async_hooks_error_handling" id="async_hooks_error_handling">#</a></span></h5> <p>If any <code>AsyncHook</code> callbacks throw, the application will print the stack trace and exit. The exit path does follow that of an uncaught exception, but all <code>'uncaughtException'</code> listeners are removed, thus forcing the process to exit. The <code>'exit'</code> callbacks will still be called unless the application is run with <code>--abort-on-uncaught-exception</code>, in which case a stack trace will be printed and the application exits, leaving a core file.</p> <p>The reason for this error handling behavior is that these callbacks are running at potentially volatile points in an object's lifetime, for example during class construction and destruction. Because of this, it is deemed necessary to bring down the process quickly in order to prevent an unintentional abort in the future. This is subject to change in the future if a comprehensive analysis is performed to ensure an exception can follow the normal control flow without unintentional side effects.</p> <h5>Printing in AsyncHooks callbacks<span><a class="mark" href="#async_hooks_printing_in_asynchooks_callbacks" id="async_hooks_printing_in_asynchooks_callbacks">#</a></span></h5> <p>Because printing to the console is an asynchronous operation, <code>console.log()</code> will cause the AsyncHooks callbacks to be called. Using <code>console.log()</code> or similar asynchronous operations inside an AsyncHooks callback function will thus cause an infinite recursion. An easy solution to this when debugging is to use a synchronous logging operation such as <code>fs.writeFileSync(file, msg, flag)</code>. This will print to the file and will not invoke AsyncHooks recursively because it is synchronous.</p> <pre><code class="language-js">const fs = require('fs'); const util = require('util'); function debug(...args) { // use a function like this one when debugging inside an AsyncHooks callback fs.writeFileSync('log.out', `${util.format(...args)}\n`, { flag: 'a' }); } </code></pre> <p>If an asynchronous operation is needed for logging, it is possible to keep track of what caused the asynchronous operation using the information provided by AsyncHooks itself. The logging should then be skipped when it was the logging itself that caused AsyncHooks callback to call. By doing this the otherwise infinite recursion is broken.</p> <h4>asyncHook.enable()<span><a class="mark" href="#async_hooks_asynchook_enable" id="async_hooks_asynchook_enable">#</a></span></h4> <ul> <li>Returns: <a href="#async_hooks_async_hooks_createhook_callbacks" class="type"><AsyncHook></a> A reference to <code>asyncHook</code>.</li> </ul> <p>Enable the callbacks for a given <code>AsyncHook</code> instance. If no callbacks are provided enabling is a noop.</p> <p>The <code>AsyncHook</code> instance is disabled by default. If the <code>AsyncHook</code> instance should be enabled immediately after creation, the following pattern can be used.</p> <pre><code class="language-js">const async_hooks = require('async_hooks'); const hook = async_hooks.createHook(callbacks).enable(); </code></pre> <h4>asyncHook.disable()<span><a class="mark" href="#async_hooks_asynchook_disable" id="async_hooks_asynchook_disable">#</a></span></h4> <ul> <li>Returns: <a href="#async_hooks_async_hooks_createhook_callbacks" class="type"><AsyncHook></a> A reference to <code>asyncHook</code>.</li> </ul> <p>Disable the callbacks for a given <code>AsyncHook</code> instance from the global pool of <code>AsyncHook</code> callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.</p> <p>For API consistency <code>disable()</code> also returns the <code>AsyncHook</code> instance.</p> <h4>Hook Callbacks<span><a class="mark" href="#async_hooks_hook_callbacks" id="async_hooks_hook_callbacks">#</a></span></h4> <p>Key events in the lifetime of asynchronous events have been categorized into four areas: instantiation, before/after the callback is called, and when the instance is destroyed.</p> <h5>init(asyncId, type, triggerAsyncId, resource)<span><a class="mark" href="#async_hooks_init_asyncid_type_triggerasyncid_resource" id="async_hooks_init_asyncid_type_triggerasyncid_resource">#</a></span></h5> <ul> <li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A unique ID for the async resource.</li> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The type of the async resource.</li> <li><code>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The unique ID of the async resource in whose execution context this async resource was created.</li> <li><code>resource</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Reference to the resource representing the async operation, needs to be released during <em>destroy</em>.</li> </ul> <p>Called when a class is constructed that has the <em>possibility</em> to emit an asynchronous event. This <em>does not</em> mean the instance must call <code>before</code>/<code>after</code> before <code>destroy</code> is called, only that the possibility exists.</p> <p>This behavior can be observed by doing something like opening a resource then closing it before the resource can be used. The following snippet demonstrates this.</p> <pre><code class="language-js">require('net').createServer().listen(function() { this.close(); }); // OR clearTimeout(setTimeout(() => {}, 10)); </code></pre> <p>Every new resource is assigned an ID that is unique within the scope of the current Node.js instance.</p> <h6><code>type</code><span><a class="mark" href="#async_hooks_type" id="async_hooks_type">#</a></span></h6> <p>The <code>type</code> is a string identifying the type of resource that caused <code>init</code> to be called. Generally, it will correspond to the name of the resource's constructor.</p> <pre><code class="language-text">FSEVENTWRAP, FSREQWRAP, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPPARSER, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP, SHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP, TIMERWRAP, TTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST, RANDOMBYTESREQUEST, TLSWRAP, Timeout, Immediate, TickObject </code></pre> <p>There is also the <code>PROMISE</code> resource type, which is used to track <code>Promise</code> instances and asynchronous work scheduled by them.</p> <p>Users are able to define their own <code>type</code> when using the public embedder API.</p> <p>It is possible to have type name collisions. Embedders are encouraged to use unique prefixes, such as the npm package name, to prevent collisions when listening to the hooks.</p> <h6><code>triggerAsyncId</code><span><a class="mark" href="#async_hooks_triggerasyncid" id="async_hooks_triggerasyncid">#</a></span></h6> <p><code>triggerAsyncId</code> is the <code>asyncId</code> of the resource that caused (or "triggered") the new resource to initialize and that caused <code>init</code> to call. This is different from <code>async_hooks.executionAsyncId()</code> that only shows <em>when</em> a resource was created, while <code>triggerAsyncId</code> shows <em>why</em> a resource was created.</p> <p>The following is a simple demonstration of <code>triggerAsyncId</code>:</p> <pre><code class="language-js">async_hooks.createHook({ init(asyncId, type, triggerAsyncId) { const eid = async_hooks.executionAsyncId(); fs.writeSync( 1, `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`); } }).enable(); require('net').createServer((conn) => {}).listen(8080); </code></pre> <p>Output when hitting the server with <code>nc localhost 8080</code>:</p> <pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1 TCPWRAP(7): trigger: 5 execution: 0 </code></pre> <p>The <code>TCPSERVERWRAP</code> is the server which receives the connections.</p> <p>The <code>TCPWRAP</code> is the new connection from the client. When a new connection is made, the <code>TCPWrap</code> instance is immediately constructed. This happens outside of any JavaScript stack. (An <code>executionAsyncId()</code> of <code>0</code> means that it is being executed from C++ with no JavaScript stack above it.) With only that information, it would be impossible to link resources together in terms of what caused them to be created, so <code>triggerAsyncId</code> is given the task of propagating what resource is responsible for the new resource's existence.</p> <h6><code>resource</code><span><a class="mark" href="#async_hooks_resource" id="async_hooks_resource">#</a></span></h6> <p><code>resource</code> is an object that represents the actual async resource that has been initialized. This can contain useful information that can vary based on the value of <code>type</code>. For instance, for the <code>GETADDRINFOREQWRAP</code> resource type, <code>resource</code> provides the hostname used when looking up the IP address for the host in <code>net.Server.listen()</code>. The API for accessing this information is currently not considered public, 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.</p> <p>In the case of Promises, the <code>resource</code> object will have <code>promise</code> property that refers to the <code>Promise</code> that is being initialized, and an <code>isChainedPromise</code> property, set to <code>true</code> if the promise has a parent promise, and <code>false</code> otherwise. For example, in the case of <code>b = a.then(handler)</code>, <code>a</code> is considered a parent <code>Promise</code> of <code>b</code>. Here, <code>b</code> is considered a chained promise.</p> <p>In some cases the resource object is reused for performance reasons, it is thus not safe to use it as a key in a <code>WeakMap</code> or add properties to it.</p> <h6>Asynchronous context example<span><a class="mark" href="#async_hooks_asynchronous_context_example" id="async_hooks_asynchronous_context_example">#</a></span></h6> <p>The following is an example with additional information about the calls to <code>init</code> between the <code>before</code> and <code>after</code> calls, specifically what the callback to <code>listen()</code> will look like. The output formatting is slightly more elaborate to make calling context easier to see.</p> <pre><code class="language-js">let indent = 0; async_hooks.createHook({ init(asyncId, type, triggerAsyncId) { const eid = async_hooks.executionAsyncId(); const indentStr = ' '.repeat(indent); fs.writeSync( 1, `${indentStr}${type}(${asyncId}):` + ` trigger: ${triggerAsyncId} execution: ${eid}\n`); }, before(asyncId) { const indentStr = ' '.repeat(indent); fs.writeFileSync('log.out', `${indentStr}before: ${asyncId}\n`, { flag: 'a' }); indent += 2; }, after(asyncId) { indent -= 2; const indentStr = ' '.repeat(indent); fs.writeFileSync('log.out', `${indentStr}after: ${asyncId}\n`, { flag: 'a' }); }, destroy(asyncId) { const indentStr = ' '.repeat(indent); fs.writeFileSync('log.out', `${indentStr}destroy: ${asyncId}\n`, { flag: 'a' }); }, }).enable(); require('net').createServer(() => {}).listen(8080, () => { // Let's wait 10ms before logging the server started. setTimeout(() => { console.log('>>>', async_hooks.executionAsyncId()); }, 10); }); </code></pre> <p>Output from only starting the server:</p> <pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1 TickObject(6): trigger: 5 execution: 1 before: 6 Timeout(7): trigger: 6 execution: 6 after: 6 destroy: 6 before: 7 >>> 7 TickObject(8): trigger: 7 execution: 7 after: 7 before: 8 after: 8 </code></pre> <p>As illustrated in the example, <code>executionAsyncId()</code> and <code>execution</code> each specify the value of the current execution context; which is delineated by calls to <code>before</code> and <code>after</code>.</p> <p>Only using <code>execution</code> to graph resource allocation results in the following:</p> <pre><code class="language-console">Timeout(7) -> TickObject(6) -> root(1) </code></pre> <p>The <code>TCPSERVERWRAP</code> is not part of this graph, even though it was the reason for <code>console.log()</code> being called. This is because binding to a port without a hostname is a <em>synchronous</em> operation, but to maintain a completely asynchronous API the user's callback is placed in a <code>process.nextTick()</code>.</p> <p>The graph only shows <em>when</em> a resource was created, not <em>why</em>, so to track the <em>why</em> use <code>triggerAsyncId</code>.</p> <h5>before(asyncId)<span><a class="mark" href="#async_hooks_before_asyncid" id="async_hooks_before_asyncid">#</a></span></h5> <ul> <li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>When an asynchronous operation is initiated (such as a TCP server receiving a new connection) or completes (such as writing data to disk) a callback is called to notify the user. The <code>before</code> callback is called just before said callback is executed. <code>asyncId</code> is the unique identifier assigned to the resource about to execute the callback.</p> <p>The <code>before</code> callback will be called 0 to N times. The <code>before</code> callback will typically be called 0 times if the asynchronous operation was cancelled or, for example, if no connections are received by a TCP server. Persistent asynchronous resources like a TCP server will typically call the <code>before</code> callback multiple times, while other operations like <code>fs.open()</code> will call it only once.</p> <h5>after(asyncId)<span><a class="mark" href="#async_hooks_after_asyncid" id="async_hooks_after_asyncid">#</a></span></h5> <ul> <li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Called immediately after the callback specified in <code>before</code> is completed.</p> <p>If an uncaught exception occurs during execution of the callback, then <code>after</code> will run <em>after</em> the <code>'uncaughtException'</code> event is emitted or a <code>domain</code>'s handler runs.</p> <h5>destroy(asyncId)<span><a class="mark" href="#async_hooks_destroy_asyncid" id="async_hooks_destroy_asyncid">#</a></span></h5> <ul> <li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Called after the resource corresponding to <code>asyncId</code> is destroyed. It is also called asynchronously from the embedder API <code>emitDestroy()</code>.</p> <p>Some resources depend on garbage collection for cleanup, so if a reference is made to the <code>resource</code> object passed to <code>init</code> it is possible that <code>destroy</code> will never be called, causing a memory leak in the application. If the resource does not depend on garbage collection, then this will not be an issue.</p> <h5>promiseResolve(asyncId)<span><a class="mark" href="#async_hooks_promiseresolve_asyncid" id="async_hooks_promiseresolve_asyncid">#</a></span></h5> <ul> <li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Called when the <code>resolve</code> function passed to the <code>Promise</code> constructor is invoked (either directly or through other means of resolving a promise).</p> <p>Note that <code>resolve()</code> does not do any observable synchronous work.</p> <p>The <code>Promise</code> is not necessarily fulfilled or rejected at this point if the <code>Promise</code> was resolved by assuming the state of another <code>Promise</code>.</p> <pre><code class="language-js">new Promise((resolve) => resolve(true)).then((a) => {}); </code></pre> <p>calls the following callbacks:</p> <pre><code class="language-text">init for PROMISE with id 5, trigger id: 1 promise resolve 5 # corresponds to resolve(true) init for PROMISE with id 6, trigger id: 5 # the Promise returned by then() before 6 # the then() callback is entered promise resolve 6 # the then() callback resolves the promise by returning after 6 </code></pre> <h4>async_hooks.executionAsyncId()<span><a class="mark" href="#async_hooks_async_hooks_executionasyncid" id="async_hooks_async_hooks_executionasyncid">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.2.0</td> <td><p>Renamed from <code>currentId</code></p></td></tr> <tr><td>v8.1.0</td> <td><p><span>Added in: v8.1.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The <code>asyncId</code> of the current execution context. Useful to track when something calls.</li> </ul> <pre><code class="language-js">const async_hooks = require('async_hooks'); console.log(async_hooks.executionAsyncId()); // 1 - bootstrap fs.open(path, 'r', (err, fd) => { console.log(async_hooks.executionAsyncId()); // 6 - open() }); </code></pre> <p>The ID returned from <code>executionAsyncId()</code> is related to execution timing, not causality (which is covered by <code>triggerAsyncId()</code>):</p> <pre><code class="language-js">const server = net.createServer((conn) => { // Returns the ID of the server, not of the new connection, because the // callback runs in the execution scope of the server's MakeCallback(). async_hooks.executionAsyncId(); }).listen(port, () => { // Returns the ID of a TickObject (i.e. process.nextTick()) because all // callbacks passed to .listen() are wrapped in a nextTick(). async_hooks.executionAsyncId(); }); </code></pre> <p>Note that promise contexts may not get precise <code>executionAsyncIds</code> by default. See the section on <a href="#async_hooks_promise_execution_tracking">promise execution tracking</a>.</p> <h4>async_hooks.triggerAsyncId()<span><a class="mark" href="#async_hooks_async_hooks_triggerasyncid" id="async_hooks_async_hooks_triggerasyncid">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ID of the resource responsible for calling the callback that is currently being executed.</li> </ul> <pre><code class="language-js">const server = net.createServer((conn) => { // The resource that caused (or triggered) this callback to be called // was that of the new connection. Thus the return value of triggerAsyncId() // is the asyncId of "conn". async_hooks.triggerAsyncId(); }).listen(port, () => { // Even though all callbacks passed to .listen() are wrapped in a nextTick() // the callback itself exists because the call to the server's .listen() // was made. So the return value would be the ID of the server. async_hooks.triggerAsyncId(); }); </code></pre> <p>Note that promise contexts may not get valid <code>triggerAsyncId</code>s by default. See the section on <a href="#async_hooks_promise_execution_tracking">promise execution tracking</a>.</p> <h2>Promise execution tracking<span><a class="mark" href="#async_hooks_promise_execution_tracking" id="async_hooks_promise_execution_tracking">#</a></span></h2> <p>By default, promise executions are not assigned <code>asyncId</code>s due to the relatively expensive nature of the <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">promise introspection API</a> provided by V8. This means that programs using promises or <code>async</code>/<code>await</code> will not get correct execution and trigger ids for promise callback contexts by default.</p> <pre><code class="language-js">const ah = require('async_hooks'); Promise.resolve(1729).then(() => { console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`); }); // produces: // eid 1 tid 0 </code></pre> <p>Observe that the <code>then()</code> callback claims to have executed in the context of the outer scope even though there was an asynchronous hop involved. Also note that the <code>triggerAsyncId</code> value is <code>0</code>, which means that we are missing context about the resource that caused (triggered) the <code>then()</code> callback to be executed.</p> <p>Installing async hooks via <code>async_hooks.createHook</code> enables promise execution tracking:</p> <pre><code class="language-js">const ah = require('async_hooks'); ah.createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled. Promise.resolve(1729).then(() => { console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`); }); // produces: // eid 7 tid 6 </code></pre> <p>In this example, adding any actual hook function enabled the tracking of promises. There are two promises in the example above; the promise created by <code>Promise.resolve()</code> and the promise returned by the call to <code>then()</code>. In the example above, the first promise got the <code>asyncId</code> <code>6</code> and the latter got <code>asyncId</code> <code>7</code>. During the execution of the <code>then()</code> callback, we are executing in the context of promise with <code>asyncId</code> <code>7</code>. This promise was triggered by async resource <code>6</code>.</p> <p>Another subtlety with promises is that <code>before</code> and <code>after</code> callbacks are run only on chained promises. That means promises not created by <code>then()</code>/<code>catch()</code> will not have the <code>before</code> and <code>after</code> callbacks fired on them. For more details see the details of the V8 <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">PromiseHooks</a> API.</p> <h2>JavaScript Embedder API<span><a class="mark" href="#async_hooks_javascript_embedder_api" id="async_hooks_javascript_embedder_api">#</a></span></h2> <p>Library developers that handle their own asynchronous resources performing tasks like I/O, connection pooling, or managing callback queues may use the <code>AsyncWrap</code> JavaScript API so that all the appropriate callbacks are called.</p> <h3>Class: AsyncResource<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L141">[src]</a><span><a class="mark" href="#async_hooks_class_asyncresource" id="async_hooks_class_asyncresource">#</a></span></h3> <p>The class <code>AsyncResource</code> is designed to be extended by the embedder's async resources. Using this, users can easily trigger the lifetime events of their own resources.</p> <p>The <code>init</code> hook will trigger when an <code>AsyncResource</code> is instantiated.</p> <p>The following is an overview of the <code>AsyncResource</code> API.</p> <pre><code class="language-js">const { AsyncResource, executionAsyncId } = require('async_hooks'); // AsyncResource() is meant to be extended. Instantiating a // new AsyncResource() also triggers init. If triggerAsyncId is omitted then // async_hook.executionAsyncId() is used. const asyncResource = new AsyncResource( type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false } ); // Run a function in the execution context of the resource. This will // * establish the context of the resource // * trigger the AsyncHooks before callbacks // * call the provided function `fn` with the supplied arguments // * trigger the AsyncHooks after callbacks // * restore the original execution context asyncResource.runInAsyncScope(fn, thisArg, ...args); // Call AsyncHooks destroy callbacks. asyncResource.emitDestroy(); // Return the unique ID assigned to the AsyncResource instance. asyncResource.asyncId(); // Return the trigger ID for the AsyncResource instance. asyncResource.triggerAsyncId(); </code></pre> <h4>new AsyncResource(type[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L142">[src]</a><span><a class="mark" href="#async_hooks_new_asyncresource_type_options" id="async_hooks_new_asyncresource_type_options">#</a></span></h4> <ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The type of async event.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ID of the execution context that created this async event. <strong>Default:</strong> <code>executionAsyncId()</code>.</li> <li><code>requireManualDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Disables automatic <code>emitDestroy</code> when the object is garbage collected. This usually does not need to be set (even if <code>emitDestroy</code> is called manually), unless the resource's <code>asyncId</code> is retrieved and the sensitive API's <code>emitDestroy</code> is called with it. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> </ul> <p>Example usage:</p> <pre><code class="language-js">class DBQuery extends AsyncResource { constructor(db) { super('DBQuery'); this.db = db; } getInfo(query, callback) { this.db.get(query, (err, data) => { this.runInAsyncScope(callback, null, err, data); }); } close() { this.db = null; this.emitDestroy(); } } </code></pre> <h4>asyncResource.runInAsyncScope(fn[, thisArg, ...args])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L184">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args" id="async_hooks_asyncresource_runinasyncscope_fn_thisarg_args">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.6.0</span> </div> <ul> <li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to call in the execution context of this async resource.</li> <li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The receiver to be used for the function call.</li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass to the function.</li> </ul> <p>Call the provided function with the provided arguments in the execution context of the async resource. This will establish the context, trigger the AsyncHooks before callbacks, call the function, trigger the AsyncHooks after callbacks, and then restore the original execution context.</p> <h4>asyncResource.emitBefore()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L172">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_emitbefore" id="async_hooks_asyncresource_emitbefore">#</a></span></h4> <div class="api_metadata"> <span>Deprecated since: v9.6.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args"><code>asyncResource.runInAsyncScope()</code></a> instead.</div><p></p> <p>Call all <code>before</code> callbacks to notify that a new asynchronous execution context is being entered. If nested calls to <code>emitBefore()</code> are made, the stack of <code>asyncId</code>s will be tracked and properly unwound.</p> <p><code>before</code> and <code>after</code> calls must be unwound in the same order that they are called. Otherwise, an unrecoverable exception will occur and the process will abort. For this reason, the <code>emitBefore</code> and <code>emitAfter</code> APIs are considered deprecated. Please use <code>runInAsyncScope</code>, as it provides a much safer alternative.</p> <h4>asyncResource.emitAfter()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L178">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_emitafter" id="async_hooks_asyncresource_emitafter">#</a></span></h4> <div class="api_metadata"> <span>Deprecated since: v9.6.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args"><code>asyncResource.runInAsyncScope()</code></a> instead.</div><p></p> <p>Call all <code>after</code> callbacks. If nested calls to <code>emitBefore()</code> were made, then make sure the stack is unwound properly. Otherwise an error will be thrown.</p> <p>If the user's callback throws an exception, <code>emitAfter()</code> will automatically be called for all <code>asyncId</code>s on the stack if the error is handled by a domain or <code>'uncaughtException'</code> handler.</p> <p><code>before</code> and <code>after</code> calls must be unwound in the same order that they are called. Otherwise, an unrecoverable exception will occur and the process will abort. For this reason, the <code>emitBefore</code> and <code>emitAfter</code> APIs are considered deprecated. Please use <code>runInAsyncScope</code>, as it provides a much safer alternative.</p> <h4>asyncResource.emitDestroy()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L195">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_emitdestroy" id="async_hooks_asyncresource_emitdestroy">#</a></span></h4> <ul> <li>Returns: <a href="#async_hooks_class_asyncresource" class="type"><AsyncResource></a> A reference to <code>asyncResource</code>.</li> </ul> <p>Call all <code>destroy</code> hooks. This should only ever be called once. An error will be thrown if it is called more than once. This <strong>must</strong> be manually called. If the resource is left to be collected by the GC then the <code>destroy</code> hooks will never be called.</p> <h4>asyncResource.asyncId()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L201">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_asyncid" id="async_hooks_asyncresource_asyncid">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The unique <code>asyncId</code> assigned to the resource.</li> </ul> <h4>asyncResource.triggerAsyncId()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/async_hooks.js#L205">[src]</a><span><a class="mark" href="#async_hooks_asyncresource_triggerasyncid" id="async_hooks_asyncresource_triggerasyncid">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The same <code>triggerAsyncId</code> that is passed to the <code>AsyncResource</code> constructor.</li> </ul> <h1>Buffer<span><a class="mark" href="#buffer_buffer" id="buffer_buffer">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>Prior to the introduction of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>, the JavaScript language had no mechanism for reading or manipulating streams of binary data. The <code>Buffer</code> class was introduced as part of the Node.js API to enable interaction with octet streams in TCP streams, file system operations, and other contexts.</p> <p>With <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> now available, the <code>Buffer</code> class implements the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> API in a manner that is more optimized and suitable for Node.js.</p> <p>Instances of the <code>Buffer</code> class are similar to arrays of integers but correspond to fixed-sized, raw memory allocations outside the V8 heap. The size of the <code>Buffer</code> is established when it is created and cannot be changed.</p> <p>The <code>Buffer</code> class is within the global scope, making it unlikely that one would need to ever use <code>require('buffer').Buffer</code>.</p> <pre><code class="language-js">// Creates a zero-filled Buffer of length 10. const buf1 = Buffer.alloc(10); // Creates a Buffer of length 10, filled with 0x1. const buf2 = Buffer.alloc(10, 1); // Creates an uninitialized buffer of length 10. // This is faster than calling Buffer.alloc() but the returned // Buffer instance might contain old data that needs to be // overwritten using either fill() or write(). const buf3 = Buffer.allocUnsafe(10); // Creates a Buffer containing [0x1, 0x2, 0x3]. const buf4 = Buffer.from([1, 2, 3]); // Creates a Buffer containing UTF-8 bytes [0x74, 0xc3, 0xa9, 0x73, 0x74]. const buf5 = Buffer.from('tést'); // Creates a Buffer containing Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. const buf6 = Buffer.from('tést', 'latin1'); </code></pre> <h2><code>Buffer.from()</code>, <code>Buffer.alloc()</code>, and <code>Buffer.allocUnsafe()</code><span><a class="mark" href="#buffer_buffer_from_buffer_alloc_and_buffer_allocunsafe" id="buffer_buffer_from_buffer_alloc_and_buffer_allocunsafe">#</a></span></h2> <p>In versions of Node.js prior to 6.0.0, <code>Buffer</code> instances were created using the <code>Buffer</code> constructor function, which allocates the returned <code>Buffer</code> differently based on what arguments are provided:</p> <ul> <li>Passing a number as the first argument to <code>Buffer()</code> (e.g. <code>new Buffer(10)</code>) allocates a new <code>Buffer</code> object of the specified size. Prior to Node.js 8.0.0, the memory allocated for such <code>Buffer</code> instances is <em>not</em> initialized and <em>can contain sensitive data</em>. Such <code>Buffer</code> instances <em>must</em> be subsequently initialized by using either <a href="#buffer_buf_fill_value_offset_end_encoding"><code>buf.fill(0)</code></a> or by writing to the entire <code>Buffer</code>. While this behavior is <em>intentional</em> to improve performance, development experience has demonstrated that a more explicit distinction is required between creating a fast-but-uninitialized <code>Buffer</code> versus creating a slower-but-safer <code>Buffer</code>. Starting in Node.js 8.0.0, <code>Buffer(num)</code> and <code>new Buffer(num)</code> will return a <code>Buffer</code> with initialized memory.</li> <li>Passing a string, array, or <code>Buffer</code> as the first argument copies the passed object's data into the <code>Buffer</code>.</li> <li>Passing an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> returns a <code>Buffer</code> that shares allocated memory with the given array buffer.</li> </ul> <p>Because the behavior of <code>new Buffer()</code> is different depending on the type of the first argument, security and reliability issues can be inadvertently introduced into applications when argument validation or <code>Buffer</code> initialization is not performed.</p> <p>To make the creation of <code>Buffer</code> instances more reliable and less error-prone, the various forms of the <code>new Buffer()</code> constructor have been <strong>deprecated</strong> and replaced by separate <code>Buffer.from()</code>, <a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc()</code></a>, and <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> methods.</p> <p><em>Developers should migrate all existing uses of the <code>new Buffer()</code> constructors to one of these new APIs.</em></p> <ul> <li><a href="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a> returns a new <code>Buffer</code> that <em>contains a copy</em> of the provided octets.</li> <li><a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a> returns a new <code>Buffer</code> that <em>shares the same allocated memory</em> as the given <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>.</li> <li><a href="#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a> returns a new <code>Buffer</code> that <em>contains a copy</em> of the contents of the given <code>Buffer</code>.</li> <li><a href="#buffer_class_method_buffer_from_string_encoding"><code>Buffer.from(string[, encoding])</code></a> returns a new <code>Buffer</code> that <em>contains a copy</em> of the provided string.</li> <li><a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc(size[, fill[, encoding]])</code></a> returns a new initialized <code>Buffer</code> of the specified size. This method is slower than <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe(size)</code></a> but guarantees that newly created <code>Buffer</code> instances never contain old data that is potentially sensitive.</li> <li><a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe(size)</code></a> and <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow(size)</code></a> each return a new uninitialized <code>Buffer</code> of the specified <code>size</code>. Because the <code>Buffer</code> is uninitialized, the allocated segment of memory might contain old data that is potentially sensitive.</li> </ul> <p><code>Buffer</code> instances returned by <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> <em>may</em> be allocated off a shared internal memory pool if <code>size</code> is less than or equal to half <a href="#buffer_class_property_buffer_poolsize"><code>Buffer.poolSize</code></a>. Instances returned by <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow()</code></a> <em>never</em> use the shared internal memory pool.</p> <h3>The <code>--zero-fill-buffers</code> command line option<span><a class="mark" href="#buffer_the_zero_fill_buffers_command_line_option" id="buffer_the_zero_fill_buffers_command_line_option">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.10.0</span> </div> <p>Node.js can be started using the <code>--zero-fill-buffers</code> command line option to cause all newly allocated <code>Buffer</code> instances to be zero-filled upon creation by default, including buffers returned by <code>new Buffer(size)</code>, <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a>, <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow()</code></a>, and <code>new SlowBuffer(size)</code>. Use of this flag can have a significant negative impact on performance. Use of the <code>--zero-fill-buffers</code> option is recommended only when necessary to enforce that newly allocated <code>Buffer</code> instances cannot contain old data that is potentially sensitive.</p> <pre><code class="language-txt">$ node --zero-fill-buffers > Buffer.allocUnsafe(5); <Buffer 00 00 00 00 00> </code></pre> <h3>What makes <code>Buffer.allocUnsafe()</code> and <code>Buffer.allocUnsafeSlow()</code> "unsafe"?<span><a class="mark" href="#buffer_what_makes_buffer_allocunsafe_and_buffer_allocunsafeslow_unsafe" id="buffer_what_makes_buffer_allocunsafe_and_buffer_allocunsafeslow_unsafe">#</a></span></h3> <p>When calling <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> and <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow()</code></a>, the segment of allocated memory is <em>uninitialized</em> (it is not zeroed-out). While this design makes the allocation of memory quite fast, the allocated segment of memory might contain old data that is potentially sensitive. Using a <code>Buffer</code> created by <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> without <em>completely</em> overwriting the memory can allow this old data to be leaked when the <code>Buffer</code> memory is read.</p> <p>While there are clear performance advantages to using <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a>, extra care <em>must</em> be taken in order to avoid introducing security vulnerabilities into an application.</p> <h2>Buffers and Character Encodings<span><a class="mark" href="#buffer_buffers_and_character_encodings" id="buffer_buffers_and_character_encodings">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.4.0</td> <td><p>Introduced <code>latin1</code> as an alias for <code>binary</code>.</p></td></tr> <tr><td>v5.0.0</td> <td><p>Removed the deprecated <code>raw</code> and <code>raws</code> encodings.</p></td></tr> </tbody></table> </details> </div> <p>When string data is stored in or extracted out of a <code>Buffer</code> instance, a character encoding may be specified.</p> <pre><code class="language-js">const buf = Buffer.from('hello world', 'ascii'); console.log(buf.toString('hex')); // Prints: 68656c6c6f20776f726c64 console.log(buf.toString('base64')); // Prints: aGVsbG8gd29ybGQ= console.log(Buffer.from('fhqwhgads', 'ascii')); // Prints: <Buffer 66 68 71 77 68 67 61 64 73> console.log(Buffer.from('fhqwhgads', 'utf16le')); // Prints: <Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00> </code></pre> <p>The character encodings currently supported by Node.js include:</p> <ul> <li> <p><code>'ascii'</code> - For 7-bit ASCII data only. This encoding is fast and will strip the high bit if set.</p> </li> <li> <p><code>'utf8'</code> - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.</p> </li> <li> <p><code>'utf16le'</code> - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.</p> </li> <li> <p><code>'ucs2'</code> - Alias of <code>'utf16le'</code>.</p> </li> <li> <p><code>'base64'</code> - Base64 encoding. When creating a <code>Buffer</code> from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in <a href="https://tools.ietf.org/html/rfc4648#section-5">RFC4648, Section 5</a>.</p> </li> <li> <p><code>'latin1'</code> - A way of encoding the <code>Buffer</code> into a one-byte encoded string (as defined by the IANA in <a href="https://tools.ietf.org/html/rfc1345">RFC1345</a>, page 63, to be the Latin-1 supplement block and C0/C1 control codes).</p> </li> <li> <p><code>'binary'</code> - Alias for <code>'latin1'</code>.</p> </li> <li> <p><code>'hex'</code> - Encode each byte as two hexadecimal characters.</p> </li> </ul> <p>Modern Web browsers follow the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a> which aliases both <code>'latin1'</code> and <code>'ISO-8859-1'</code> to <code>'win-1252'</code>. This means that while doing something like <code>http.get()</code>, if the returned charset is one of those listed in the WHATWG specification it is possible that the server actually returned <code>'win-1252'</code>-encoded data, and using <code>'latin1'</code> encoding may incorrectly decode the characters.</p> <h2>Buffers and TypedArray<span><a class="mark" href="#buffer_buffers_and_typedarray" id="buffer_buffers_and_typedarray">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v3.0.0</td> <td><p>The <code>Buffer</code>s class now inherits from <code>Uint8Array</code>.</p></td></tr> </tbody></table> </details> </div> <p><code>Buffer</code> instances are also <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> instances. However, there are subtle incompatibilities with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>. For example, while <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/slice"><code>ArrayBuffer#slice()</code></a> creates a copy of the slice, the implementation of <a href="#buffer_buf_slice_start_end"><code>Buffer#slice()</code></a> creates a view over the existing <code>Buffer</code> without copying, making <a href="#buffer_buf_slice_start_end"><code>Buffer#slice()</code></a> far more efficient.</p> <p>It is also possible to create new <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instances from a <code>Buffer</code> with the following caveats:</p> <ol> <li> <p>The <code>Buffer</code> object's memory is copied to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>, not shared.</p> </li> <li> <p>The <code>Buffer</code> object's memory is interpreted as an array of distinct elements, and not as a byte array of the target type. That is, <code>new Uint32Array(Buffer.from([1, 2, 3, 4]))</code> creates a 4-element <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array"><code>Uint32Array</code></a> with elements <code>[1, 2, 3, 4]</code>, not a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array"><code>Uint32Array</code></a> with a single element <code>[0x1020304]</code> or <code>[0x4030201]</code>.</p> </li> </ol> <p>It is possible to create a new <code>Buffer</code> that shares the same allocated memory as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instance by using the <code>TypedArray</code> object's <code>.buffer</code> property.</p> <pre><code class="language-js">const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; // Copies the contents of `arr` const buf1 = Buffer.from(arr); // Shares memory with `arr` const buf2 = Buffer.from(arr.buffer); console.log(buf1); // Prints: <Buffer 88 a0> console.log(buf2); // Prints: <Buffer 88 13 a0 0f> arr[1] = 6000; console.log(buf1); // Prints: <Buffer 88 a0> console.log(buf2); // Prints: <Buffer 88 13 70 17> </code></pre> <p>Note that when creating a <code>Buffer</code> using a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>'s <code>.buffer</code>, it is possible to use only a portion of the underlying <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> by passing in <code>byteOffset</code> and <code>length</code> parameters.</p> <pre><code class="language-js">const arr = new Uint16Array(20); const buf = Buffer.from(arr.buffer, 0, 16); console.log(buf.length); // Prints: 16 </code></pre> <p>The <code>Buffer.from()</code> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from"><code>TypedArray.from()</code></a> have different signatures and implementations. Specifically, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> variants accept a second argument that is a mapping function that is invoked on every element of the typed array:</p> <ul> <li><code>TypedArray.from(source[, mapFn[, thisArg]])</code></li> </ul> <p>The <code>Buffer.from()</code> method, however, does not support the use of a mapping function:</p> <ul> <li><a href="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a></li> <li><a href="#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a></li> <li><a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a></li> <li><a href="#buffer_class_method_buffer_from_string_encoding"><code>Buffer.from(string[, encoding])</code></a></li> </ul> <h2>Buffers and iteration<span><a class="mark" href="#buffer_buffers_and_iteration" id="buffer_buffers_and_iteration">#</a></span></h2> <p><code>Buffer</code> instances can be iterated over using <code>for..of</code> syntax:</p> <pre><code class="language-js">const buf = Buffer.from([1, 2, 3]); // Prints: // 1 // 2 // 3 for (const b of buf) { console.log(b); } </code></pre> <p>Additionally, the <a href="#buffer_buf_values"><code>buf.values()</code></a>, <a href="#buffer_buf_keys"><code>buf.keys()</code></a>, and <a href="#buffer_buf_entries"><code>buf.entries()</code></a> methods can be used to create iterators.</p> <h2>Class: Buffer<span><a class="mark" href="#buffer_class_buffer" id="buffer_class_buffer">#</a></span></h2> <p>The <code>Buffer</code> class is a global type for dealing with binary data directly. It can be constructed in a variety of ways.</p> <h3>new Buffer(array)<span><a class="mark" href="#buffer_new_buffer_array" id="buffer_new_buffer_array">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr> <tr><td>v7.2.1</td> <td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr> <tr><td>v7.0.0</td> <td><p>Calling this constructor emits a deprecation warning now.</p></td></tr> <tr><td>v6.0.0</td> <td><p><span>Deprecated since: v6.0.0</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a> instead.</div><p></p> <ul> <li><code>array</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a> An array of bytes to copy from.</li> </ul> <p>Allocates a new <code>Buffer</code> using an <code>array</code> of octets.</p> <pre><code class="language-js">// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer' const buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); </code></pre> <h3>new Buffer(arrayBuffer[, byteOffset[, length]])<span><a class="mark" href="#buffer_new_buffer_arraybuffer_byteoffset_length" id="buffer_new_buffer_arraybuffer_byteoffset_length">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr> <tr><td>v7.2.1</td> <td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr> <tr><td>v7.0.0</td> <td><p>Calling this constructor emits a deprecation warning now.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The <code>byteOffset</code> and <code>length</code> parameters are supported now.</p></td></tr> <tr><td>v6.0.0</td> <td><p><span>Deprecated since: v6.0.0</span></p></td></tr> <tr><td>v3.0.0</td> <td><p><span>Added in: v3.0.0</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a> instead.</div><p></p> <ul> <li><code>arrayBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> An <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> or the <code>.buffer</code> property of a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>.</li> <li><code>byteOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Index of first byte to expose. <strong>Default:</strong> <code>0</code>.</li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to expose. <strong>Default:</strong> <code>arrayBuffer.length - byteOffset</code>.</li> </ul> <p>This creates a view of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> without copying the underlying memory. For example, when passed a reference to the <code>.buffer</code> property of a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instance, the newly created <code>Buffer</code> will share the same allocated memory as the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>.</p> <p>The optional <code>byteOffset</code> and <code>length</code> arguments specify a memory range within the <code>arrayBuffer</code> that will be shared by the <code>Buffer</code>.</p> <pre><code class="language-js">const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; // Shares memory with `arr` const buf = new Buffer(arr.buffer); console.log(buf); // Prints: <Buffer 88 13 a0 0f> // Changing the original Uint16Array changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> </code></pre> <h3>new Buffer(buffer)<span><a class="mark" href="#buffer_new_buffer_buffer" id="buffer_new_buffer_buffer">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr> <tr><td>v7.2.1</td> <td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr> <tr><td>v7.0.0</td> <td><p>Calling this constructor emits a deprecation warning now.</p></td></tr> <tr><td>v6.0.0</td> <td><p><span>Deprecated since: v6.0.0</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a> instead.</div><p></p> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> An existing <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> from which to copy data.</li> </ul> <p>Copies the passed <code>buffer</code> data onto a new <code>Buffer</code> instance.</p> <pre><code class="language-js">const buf1 = new Buffer('buffer'); const buf2 = new Buffer(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // Prints: auffer console.log(buf2.toString()); // Prints: buffer </code></pre> <h3>new Buffer(size)<span><a class="mark" href="#buffer_new_buffer_size" id="buffer_new_buffer_size">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>new Buffer(size)</code> will return zero-filled memory by default.</p></td></tr> <tr><td>v7.2.1</td> <td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr> <tr><td>v7.0.0</td> <td><p>Calling this constructor emits a deprecation warning now.</p></td></tr> <tr><td>v6.0.0</td> <td><p><span>Deprecated since: v6.0.0</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc()</code></a> instead (also see <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a>).</div><p></p> <ul> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The desired length of the new <code>Buffer</code>.</li> </ul> <p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If <code>size</code> is larger than <a href="#buffer_buffer_constants_max_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#ERR_INVALID_OPT_VALUE"><code>ERR_INVALID_OPT_VALUE</code></a> is thrown. A zero-length <code>Buffer</code> is created if <code>size</code> is 0.</p> <p>Prior to Node.js 8.0.0, the underlying memory for <code>Buffer</code> instances created in this way is <em>not initialized</em>. The contents of a newly created <code>Buffer</code> are unknown and <em>may contain sensitive data</em>. Use <a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc(size)</code></a> instead to initialize a <code>Buffer</code> with zeroes.</p> <pre><code class="language-js">const buf = new Buffer(10); console.log(buf); // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00> </code></pre> <h3>new Buffer(string[, encoding])<span><a class="mark" href="#buffer_new_buffer_string_encoding" id="buffer_new_buffer_string_encoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr> <tr><td>v7.2.1</td> <td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr> <tr><td>v7.0.0</td> <td><p>Calling this constructor emits a deprecation warning now.</p></td></tr> <tr><td>v6.0.0</td> <td><p><span>Deprecated since: v6.0.0</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_from_string_encoding"><code>Buffer.from(string[, encoding])</code></a> instead.</div><p></p> <ul> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> String to encode.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding of <code>string</code>. <strong>Default:</strong> <code>'utf8'</code>.</li> </ul> <p>Creates a new <code>Buffer</code> containing <code>string</code>. The <code>encoding</code> parameter identifies the character encoding of <code>string</code>.</p> <pre><code class="language-js">const buf1 = new Buffer('this is a tést'); const buf2 = new Buffer('7468697320697320612074c3a97374', 'hex'); console.log(buf1.toString()); // Prints: this is a tést console.log(buf2.toString()); // Prints: this is a tést console.log(buf1.toString('ascii')); // Prints: this is a tC)st </code></pre> <h3>Class Method: Buffer.alloc(size[, fill[, encoding]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L277">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_alloc_size_fill_encoding" id="buffer_class_method_buffer_alloc_size_fill_encoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception.</p></td></tr> <tr><td>v10.0.0</td> <td><p>Specifying an invalid string for <code>fill</code> triggers a thrown exception.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Specifying an invalid string for <code>fill</code> now results in a zero-filled buffer.</p></td></tr> <tr><td>v5.10.0</td> <td><p><span>Added in: v5.10.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The desired length of the new <code>Buffer</code>.</li> <li><code>fill</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> A value to pre-fill the new <code>Buffer</code> with. <strong>Default:</strong> <code>0</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If <code>fill</code> is a string, this is its encoding. <strong>Default:</strong> <code>'utf8'</code>.</li> </ul> <p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If <code>fill</code> is <code>undefined</code>, the <code>Buffer</code> will be <em>zero-filled</em>.</p> <pre><code class="language-js">const buf = Buffer.alloc(5); console.log(buf); // Prints: <Buffer 00 00 00 00 00> </code></pre> <p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If <code>size</code> is larger than <a href="#buffer_buffer_constants_max_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#ERR_INVALID_OPT_VALUE"><code>ERR_INVALID_OPT_VALUE</code></a> is thrown. A zero-length <code>Buffer</code> is created if <code>size</code> is 0.</p> <p>If <code>fill</code> is specified, the allocated <code>Buffer</code> will be initialized by calling <a href="#buffer_buf_fill_value_offset_end_encoding"><code>buf.fill(fill)</code></a>.</p> <pre><code class="language-js">const buf = Buffer.alloc(5, 'a'); console.log(buf); // Prints: <Buffer 61 61 61 61 61> </code></pre> <p>If both <code>fill</code> and <code>encoding</code> are specified, the allocated <code>Buffer</code> will be initialized by calling <a href="#buffer_buf_fill_value_offset_end_encoding"><code>buf.fill(fill, encoding)</code></a>.</p> <pre><code class="language-js">const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> </code></pre> <p>Calling <a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc()</code></a> can be significantly slower than the alternative <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> but ensures that the newly created <code>Buffer</code> instance contents will <em>never contain sensitive data</em>.</p> <p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p> <h3>Class Method: Buffer.allocUnsafe(size)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L290">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_allocunsafe_size" id="buffer_class_method_buffer_allocunsafe_size">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.0.0</td> <td><p>Passing a negative <code>size</code> will now throw an error.</p></td></tr> <tr><td>v5.10.0</td> <td><p><span>Added in: v5.10.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The desired length of the new <code>Buffer</code>.</li> </ul> <p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If <code>size</code> is larger than <a href="#buffer_buffer_constants_max_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#ERR_INVALID_OPT_VALUE"><code>ERR_INVALID_OPT_VALUE</code></a> is thrown. A zero-length <code>Buffer</code> is created if <code>size</code> is 0.</p> <p>The underlying memory for <code>Buffer</code> instances created in this way is <em>not initialized</em>. The contents of the newly created <code>Buffer</code> are unknown and <em>may contain sensitive data</em>. Use <a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc()</code></a> instead to initialize <code>Buffer</code> instances with zeroes.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(10); console.log(buf); // Prints: (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32> buf.fill(0); console.log(buf); // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00> </code></pre> <p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p> <p>Note that the <code>Buffer</code> module pre-allocates an internal <code>Buffer</code> instance of size <a href="#buffer_class_property_buffer_poolsize"><code>Buffer.poolSize</code></a> that is used as a pool for the fast allocation of new <code>Buffer</code> instances created using <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> and the deprecated <code>new Buffer(size)</code> constructor only when <code>size</code> is less than or equal to <code>Buffer.poolSize >> 1</code> (floor of <a href="#buffer_class_property_buffer_poolsize"><code>Buffer.poolSize</code></a> divided by two).</p> <p>Use of this pre-allocated internal memory pool is a key difference between calling <code>Buffer.alloc(size, fill)</code> vs. <code>Buffer.allocUnsafe(size).fill(fill)</code>. Specifically, <code>Buffer.alloc(size, fill)</code> will <em>never</em> use the internal <code>Buffer</code> pool, while <code>Buffer.allocUnsafe(size).fill(fill)</code> <em>will</em> use the internal <code>Buffer</code> pool if <code>size</code> is less than or equal to half <a href="#buffer_class_property_buffer_poolsize"><code>Buffer.poolSize</code></a>. The difference is subtle but can be important when an application requires the additional performance that <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> provides.</p> <h3>Class Method: Buffer.allocUnsafeSlow(size)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L300">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_allocunsafeslow_size" id="buffer_class_method_buffer_allocunsafeslow_size">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.12.0</span> </div> <ul> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The desired length of the new <code>Buffer</code>.</li> </ul> <p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If <code>size</code> is larger than <a href="#buffer_buffer_constants_max_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#ERR_INVALID_OPT_VALUE"><code>ERR_INVALID_OPT_VALUE</code></a> is thrown. A zero-length <code>Buffer</code> is created if <code>size</code> is 0.</p> <p>The underlying memory for <code>Buffer</code> instances created in this way is <em>not initialized</em>. The contents of the newly created <code>Buffer</code> are unknown and <em>may contain sensitive data</em>. Use <a href="#buffer_buf_fill_value_offset_end_encoding"><code>buf.fill(0)</code></a> to initialize such <code>Buffer</code> instances with zeroes.</p> <p>When using <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> to allocate new <code>Buffer</code> instances, allocations under 4KB are sliced from a single pre-allocated <code>Buffer</code>. This allows applications to avoid the garbage collection overhead of creating many individually allocated <code>Buffer</code> instances. This approach improves both performance and memory usage by eliminating the need to track and clean up as many persistent objects.</p> <p>However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled <code>Buffer</code> instance using <code>Buffer.allocUnsafeSlow()</code> and then copying out the relevant bits.</p> <pre><code class="language-js">// Need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { let data; while (null !== (data = readable.read())) { // Allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // Copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); } }); </code></pre> <p><code>Buffer.allocUnsafeSlow()</code> should be used only as a last resort after a developer has observed undue memory retention in their applications.</p> <p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p> <h3>Class Method: Buffer.byteLength(string[, encoding])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L509">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_bytelength_string_encoding" id="buffer_class_method_buffer_bytelength_string_encoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.0.0</td> <td><p>Passing invalid input will now throw an error.</p></td></tr> <tr><td>v5.10.0</td> <td><p>The <code>string</code> parameter can now be any <code>TypedArray</code>, <code>DataView</code> or <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v0.1.90</td> <td><p><span>Added in: v0.1.90</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> A value to calculate the length of.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If <code>string</code> is a string, this is its encoding. <strong>Default:</strong> <code>'utf8'</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes contained within <code>string</code>.</li> </ul> <p>Returns the actual byte length of a string. This is not the same as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length"><code>String.prototype.length</code></a> since that returns the number of <em>characters</em> in a string.</p> <p>For <code>'base64'</code> and <code>'hex'</code>, this function assumes valid input. For strings that contain non-Base64/Hex-encoded data (e.g. whitespace), the return value might be greater than the length of a <code>Buffer</code> created from the string.</p> <pre><code class="language-js">const str = '\u00bd + \u00bc = \u00be'; console.log(`${str}: ${str.length} characters, ` + `${Buffer.byteLength(str, 'utf8')} bytes`); // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes </code></pre> <p>When <code>string</code> is a <code>Buffer</code>/<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><code>DataView</code></a>/<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>/<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>/ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a>, the actual byte length is returned.</p> <h3>Class Method: Buffer.compare(buf1, buf2)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L433">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_compare_buf1_buf2" id="buffer_class_method_buffer_compare_buf1_buf2">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The arguments can now be <code>Uint8Array</code>s.</p></td></tr> <tr><td>v0.11.13</td> <td><p><span>Added in: v0.11.13</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buf1</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> <li><code>buf2</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Compares <code>buf1</code> to <code>buf2</code> typically for the purpose of sorting arrays of <code>Buffer</code> instances. This is equivalent to calling <a href="#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend"><code>buf1.compare(buf2)</code></a>.</p> <pre><code class="language-js">const buf1 = Buffer.from('1234'); const buf2 = Buffer.from('0123'); const arr = [buf1, buf2]; console.log(arr.sort(Buffer.compare)); // Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ] // (This result is equal to: [buf2, buf1]) </code></pre> <h3>Class Method: Buffer.concat(list[, totalLength])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L455">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_concat_list_totallength" id="buffer_class_method_buffer_concat_list_totallength">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The elements of <code>list</code> can now be <code>Uint8Array</code>s.</p></td></tr> <tr><td>v0.7.11</td> <td><p><span>Added in: v0.7.11</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>list</code> <a href="#buffer_class_buffer" class="type"><Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array[]></a> List of <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> instances to concat.</li> <li><code>totalLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Total length of the <code>Buffer</code> instances in <code>list</code> when concatenated.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Returns a new <code>Buffer</code> which is the result of concatenating all the <code>Buffer</code> instances in the <code>list</code> together.</p> <p>If the list has no items, or if the <code>totalLength</code> is 0, then a new zero-length <code>Buffer</code> is returned.</p> <p>If <code>totalLength</code> is not provided, it is calculated from the <code>Buffer</code> instances in <code>list</code>. This however causes an additional loop to be executed in order to calculate the <code>totalLength</code>, so it is faster to provide the length explicitly if it is already known.</p> <p>If <code>totalLength</code> is provided, it is coerced to an unsigned integer. If the combined length of the <code>Buffer</code>s in <code>list</code> exceeds <code>totalLength</code>, the result is truncated to <code>totalLength</code>.</p> <pre><code class="language-js">// Create a single `Buffer` from a list of three `Buffer` instances. const buf1 = Buffer.alloc(10); const buf2 = Buffer.alloc(14); const buf3 = Buffer.alloc(18); const totalLength = buf1.length + buf2.length + buf3.length; console.log(totalLength); // Prints: 42 const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); console.log(bufA); // Prints: <Buffer 00 00 00 00 ...> console.log(bufA.length); // Prints: 42 </code></pre> <h3>Class Method: Buffer.from(array)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L199">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_from_array" id="buffer_class_method_buffer_from_array">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.10.0</span> </div> <ul> <li><code>array</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a></li> </ul> <p>Allocates a new <code>Buffer</code> using an <code>array</code> of octets.</p> <pre><code class="language-js">// Creates a new Buffer containing UTF-8 bytes of the string 'buffer' const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); </code></pre> <p>A <code>TypeError</code> will be thrown if <code>array</code> is not an <code>Array</code>.</p> <h3>Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L199">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length" id="buffer_class_method_buffer_from_arraybuffer_byteoffset_length">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.10.0</span> </div> <ul> <li><code>arrayBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> An <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a>, or the <code>.buffer</code> property of a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>.</li> <li><code>byteOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Index of first byte to expose. <strong>Default:</strong> <code>0</code>.</li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to expose. <strong>Default:</strong> <code>arrayBuffer.length - byteOffset</code>.</li> </ul> <p>This creates a view of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> without copying the underlying memory. For example, when passed a reference to the <code>.buffer</code> property of a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instance, the newly created <code>Buffer</code> will share the same allocated memory as the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>.</p> <pre><code class="language-js">const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; // Shares memory with `arr` const buf = Buffer.from(arr.buffer); console.log(buf); // Prints: <Buffer 88 13 a0 0f> // Changing the original Uint16Array changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> </code></pre> <p>The optional <code>byteOffset</code> and <code>length</code> arguments specify a memory range within the <code>arrayBuffer</code> that will be shared by the <code>Buffer</code>.</p> <pre><code class="language-js">const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 </code></pre> <p>A <code>TypeError</code> will be thrown if <code>arrayBuffer</code> is not an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a>.</p> <h3>Class Method: Buffer.from(buffer)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L199">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_from_buffer" id="buffer_class_method_buffer_from_buffer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.10.0</span> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> An existing <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> from which to copy data.</li> </ul> <p>Copies the passed <code>buffer</code> data onto a new <code>Buffer</code> instance.</p> <pre><code class="language-js">const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // Prints: auffer console.log(buf2.toString()); // Prints: buffer </code></pre> <p>A <code>TypeError</code> will be thrown if <code>buffer</code> is not a <code>Buffer</code>.</p> <h3>Class Method: Buffer.from(object[, offsetOrEncoding[, length]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L199">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_from_object_offsetorencoding_length" id="buffer_class_method_buffer_from_object_offsetorencoding_length">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.2.0</span> </div> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object supporting <code>Symbol.toPrimitive</code> or <code>valueOf()</code></li> <li><code>offsetOrEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A byte-offset or encoding, depending on the value returned either by <code>object.valueOf()</code> or <code>object[Symbol.toPrimitive]()</code>.</li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A length, depending on the value returned either by <code>object.valueOf()</code> or <code>object[Symbol.toPrimitive]()</code>.</li> </ul> <p>For objects whose <code>valueOf()</code> function returns a value not strictly equal to <code>object</code>, returns <code>Buffer.from(object.valueOf(), offsetOrEncoding, length)</code>.</p> <pre><code class="language-js">const buf = Buffer.from(new String('this is a test')); // Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74> </code></pre> <p>For objects that support <code>Symbol.toPrimitive</code>, returns <code>Buffer.from(object[Symbol.toPrimitive](), offsetOrEncoding, length)</code>.</p> <pre><code class="language-js">class Foo { [Symbol.toPrimitive]() { return 'this is a test'; } } const buf = Buffer.from(new Foo(), 'utf8'); // Prints: <Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74> </code></pre> <h3>Class Method: Buffer.from(string[, encoding])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L199">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_from_string_encoding" id="buffer_class_method_buffer_from_string_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.10.0</span> </div> <ul> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string to encode.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding of <code>string</code>. <strong>Default:</strong> <code>'utf8'</code>.</li> </ul> <p>Creates a new <code>Buffer</code> containing <code>string</code>. The <code>encoding</code> parameter identifies the character encoding of <code>string</code>.</p> <pre><code class="language-js">const buf1 = Buffer.from('this is a tést'); const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf1.toString()); // Prints: this is a tést console.log(buf2.toString()); // Prints: this is a tést console.log(buf1.toString('ascii')); // Prints: this is a tC)st </code></pre> <p>A <code>TypeError</code> will be thrown if <code>string</code> is not a string.</p> <h3>Class Method: Buffer.isBuffer(obj)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L429">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_isbuffer_obj" id="buffer_class_method_buffer_isbuffer_obj">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.101</span> </div> <ul> <li><code>obj</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if <code>obj</code> is a <code>Buffer</code>, <code>false</code> otherwise.</p> <h3>Class Method: Buffer.isEncoding(encoding)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L449">[src]</a><span><a class="mark" href="#buffer_class_method_buffer_isencoding_encoding" id="buffer_class_method_buffer_isencoding_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A character encoding name to check.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if <code>encoding</code> contains a supported character encoding, or <code>false</code> otherwise.</p> <h3>Class Property: Buffer.poolSize<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L102">[src]</a><span><a class="mark" href="#buffer_class_property_buffer_poolsize" id="buffer_class_property_buffer_poolsize">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.3</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>8192</code></li> </ul> <p>This is the size (in bytes) of pre-allocated internal <code>Buffer</code> instances used for pooling. This value may be modified.</p> <h3>buf[index]<span><a class="mark" href="#buffer_buf_index" id="buffer_buf_index">#</a></span></h3> <div class="api_metadata"> </div> <p>The index operator <code>[index]</code> can be used to get and set the octet at position <code>index</code> in <code>buf</code>. The values refer to individual bytes, so the legal value range is between <code>0x00</code> and <code>0xFF</code> (hex) or <code>0</code> and <code>255</code> (decimal).</p> <p>This operator is inherited from <code>Uint8Array</code>, so its behavior on out-of-bounds access is the same as <code>UInt8Array</code> - that is, getting returns <code>undefined</code> and setting does nothing.</p> <pre><code class="language-js">// Copy an ASCII string into a `Buffer` one byte at a time. const str = 'Node.js'; const buf = Buffer.allocUnsafe(str.length); for (let i = 0; i < str.length; i++) { buf[i] = str.charCodeAt(i); } console.log(buf.toString('ascii')); // Prints: Node.js </code></pre> <h3>buf.buffer<span><a class="mark" href="#buffer_buf_buffer" id="buffer_buf_buffer">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> The underlying <code>ArrayBuffer</code> object based on which this <code>Buffer</code> object is created.</li> </ul> <pre><code class="language-js">const arrayBuffer = new ArrayBuffer(16); const buffer = Buffer.from(arrayBuffer); console.log(buffer.buffer === arrayBuffer); // Prints: true </code></pre> <h3>buf.byteOffset<span><a class="mark" href="#buffer_buf_byteoffset" id="buffer_buf_byteoffset">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The <code>byteOffset</code> on the underlying <code>ArrayBuffer</code> object based on which this <code>Buffer</code> object is created.</li> </ul> <p>When setting <code>byteOffset</code> in <code>Buffer.from(ArrayBuffer, byteOffset, length)</code> or sometimes when allocating a buffer smaller than <code>Buffer.poolSize</code> the buffer doesn't start from a zero offset on the underlying <code>ArrayBuffer</code>.</p> <p>This can cause problems when accessing the underlying <code>ArrayBuffer</code> directly using <code>buf.buffer</code>, as the first bytes in this <code>ArrayBuffer</code> may be unrelated to the <code>buf</code> object itself.</p> <p>A common issue is when casting a <code>Buffer</code> object to a <code>TypedArray</code> object, in this case one needs to specify the <code>byteOffset</code> correctly:</p> <pre><code class="language-js">// Create a buffer smaller than `Buffer.poolSize`. const nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); // When casting the Node.js Buffer to an Int8 TypedArray remember to use the // byteOffset. new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length); </code></pre> <h3>buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L692">[src]</a><span><a class="mark" href="#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend" id="buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>target</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v5.11.0</td> <td><p>Additional parameters for specifying offsets are supported now.</p></td></tr> <tr><td>v0.11.13</td> <td><p><span>Added in: v0.11.13</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>target</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> A <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> with which to compare <code>buf</code>.</li> <li><code>targetStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>target</code> at which to begin comparison. <strong>Default:</strong> <code>0</code>.</li> <li><code>targetEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset with <code>target</code> at which to end comparison (not inclusive). <strong>Default:</strong> <code>target.length</code>.</li> <li><code>sourceStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>buf</code> at which to begin comparison. <strong>Default:</strong> <code>0</code>.</li> <li><code>sourceEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>buf</code> at which to end comparison (not inclusive). <strong>Default:</strong> <a href="#buffer_buf_length"><code>buf.length</code></a>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Compares <code>buf</code> with <code>target</code> and returns a number indicating whether <code>buf</code> comes before, after, or is the same as <code>target</code> in sort order. Comparison is based on the actual sequence of bytes in each <code>Buffer</code>.</p> <ul> <li><code>0</code> is returned if <code>target</code> is the same as <code>buf</code></li> <li><code>1</code> is returned if <code>target</code> should come <em>before</em> <code>buf</code> when sorted.</li> <li><code>-1</code> is returned if <code>target</code> should come <em>after</em> <code>buf</code> when sorted.</li> </ul> <pre><code class="language-js">const buf1 = Buffer.from('ABC'); const buf2 = Buffer.from('BCD'); const buf3 = Buffer.from('ABCD'); console.log(buf1.compare(buf1)); // Prints: 0 console.log(buf1.compare(buf2)); // Prints: -1 console.log(buf1.compare(buf3)); // Prints: -1 console.log(buf2.compare(buf1)); // Prints: 1 console.log(buf2.compare(buf3)); // Prints: 1 console.log([buf1, buf2, buf3].sort(Buffer.compare)); // Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ] // (This result is equal to: [buf1, buf3, buf2]) </code></pre> <p>The optional <code>targetStart</code>, <code>targetEnd</code>, <code>sourceStart</code>, and <code>sourceEnd</code> arguments can be used to limit the comparison to specific ranges within <code>target</code> and <code>buf</code> respectively.</p> <pre><code class="language-js">const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); console.log(buf1.compare(buf2, 5, 9, 0, 4)); // Prints: 0 console.log(buf1.compare(buf2, 0, 6, 4)); // Prints: -1 console.log(buf1.compare(buf2, 5, 6, 5)); // Prints: 1 </code></pre> <p><a href="#ERR_INDEX_OUT_OF_RANGE"><code>ERR_INDEX_OUT_OF_RANGE</code></a> is thrown if <code>targetStart < 0</code>, <code>sourceStart < 0</code>, <code>targetEnd > target.byteLength</code>, or <code>sourceEnd > source.byteLength</code>.</p> <h3>buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L634">[src]</a><span><a class="mark" href="#buffer_buf_copy_target_targetstart_sourcestart_sourceend" id="buffer_buf_copy_target_targetstart_sourcestart_sourceend">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>target</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> A <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> to copy into.</li> <li><code>targetStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>target</code> at which to begin writing. <strong>Default:</strong> <code>0</code>.</li> <li><code>sourceStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>buf</code> from which to begin copying. <strong>Default:</strong> <code>0</code>.</li> <li><code>sourceEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The offset within <code>buf</code> at which to stop copying (not inclusive). <strong>Default:</strong> <a href="#buffer_buf_length"><code>buf.length</code></a>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of bytes copied.</li> </ul> <p>Copies data from a region of <code>buf</code> to a region in <code>target</code> even if the <code>target</code> memory region overlaps with <code>buf</code>.</p> <pre><code class="language-js">// Create two `Buffer` instances. const buf1 = Buffer.allocUnsafe(26); const buf2 = Buffer.allocUnsafe(26).fill('!'); for (let i = 0; i < 26; i++) { // 97 is the decimal ASCII value for 'a' buf1[i] = i + 97; } // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2` buf1.copy(buf2, 8, 16, 20); console.log(buf2.toString('ascii', 0, 25)); // Prints: !!!!!!!!qrst!!!!!!!!!!!!! </code></pre> <pre><code class="language-js">// Create a `Buffer` and copy data from one region to an overlapping region // within the same `Buffer`. const buf = Buffer.allocUnsafe(26); for (let i = 0; i < 26; i++) { // 97 is the decimal ASCII value for 'a' buf[i] = i + 97; } buf.copy(buf, 0, 4, 10); console.log(buf.toString()); // Prints: efghijghijklmnopqrstuvwxyz </code></pre> <h3>buf.entries()<span><a class="mark" href="#buffer_buf_entries" id="buffer_buf_entries">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.1.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li> </ul> <p>Creates and returns an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterator</a> of <code>[index, byte]</code> pairs from the contents of <code>buf</code>.</p> <pre><code class="language-js">// Log the entire contents of a `Buffer`. const buf = Buffer.from('buffer'); for (const pair of buf.entries()) { console.log(pair); } // Prints: // [0, 98] // [1, 117] // [2, 102] // [3, 102] // [4, 101] // [5, 114] </code></pre> <h3>buf.equals(otherBuffer)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L670">[src]</a><span><a class="mark" href="#buffer_buf_equals_otherbuffer" id="buffer_buf_equals_otherbuffer">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The arguments can now be <code>Uint8Array</code>s.</p></td></tr> <tr><td>v0.11.13</td> <td><p><span>Added in: v0.11.13</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>otherBuffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> A <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> with which to compare <code>buf</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if both <code>buf</code> and <code>otherBuffer</code> have exactly the same bytes, <code>false</code> otherwise.</p> <pre><code class="language-js">const buf1 = Buffer.from('ABC'); const buf2 = Buffer.from('414243', 'hex'); const buf3 = Buffer.from('ABCD'); console.log(buf1.equals(buf2)); // Prints: true console.log(buf1.equals(buf3)); // Prints: false </code></pre> <h3>buf.fill(value[, offset[, end]][, encoding])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L828">[src]</a><span><a class="mark" href="#buffer_buf_fill_value_offset_end_encoding" id="buffer_buf_fill_value_offset_end_encoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Negative <code>end</code> values throw an <code>ERR_INDEX_OUT_OF_RANGE</code> error.</p></td></tr> <tr><td>v10.0.0</td> <td><p>Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception.</p></td></tr> <tr><td>v10.0.0</td> <td><p>Specifying an invalid string for <code>value</code> triggers a thrown exception.</p></td></tr> <tr><td>v5.7.0</td> <td><p>The <code>encoding</code> parameter is supported now.</p></td></tr> <tr><td>v0.5.0</td> <td><p><span>Added in: v0.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The value with which to fill <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to fill <code>buf</code>. <strong>Default:</strong> <code>0</code>.</li> <li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where to stop filling <code>buf</code> (not inclusive). <strong>Default:</strong> <a href="#buffer_buf_length"><code>buf.length</code></a>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding for <code>value</code> if <code>value</code> is a string. <strong>Default:</strong> <code>'utf8'</code>.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> A reference to <code>buf</code>.</li> </ul> <p>Fills <code>buf</code> with the specified <code>value</code>. If the <code>offset</code> and <code>end</code> are not given, the entire <code>buf</code> will be filled:</p> <pre><code class="language-js">// Fill a `Buffer` with the ASCII character 'h'. const b = Buffer.allocUnsafe(50).fill('h'); console.log(b.toString()); // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh </code></pre> <p><code>value</code> is coerced to a <code>uint32</code> value if it is not a string, <code>Buffer</code>, or integer. If the resulting integer is greater than <code>255</code> (decimal), <code>buf</code> will be filled with <code>value & 255</code>.</p> <p>If the final write of a <code>fill()</code> operation falls on a multi-byte character, then only the bytes of that character that fit into <code>buf</code> are written:</p> <pre><code class="language-js">// Fill a `Buffer` with a two-byte character. console.log(Buffer.allocUnsafe(3).fill('\u0222')); // Prints: <Buffer c8 a2 c8> </code></pre> <p>If <code>value</code> contains invalid characters, it is truncated; if no valid fill data remains, an exception is thrown:</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(5); console.log(buf.fill('a')); // Prints: <Buffer 61 61 61 61 61> console.log(buf.fill('aazz', 'hex')); // Prints: <Buffer aa aa aa aa aa> console.log(buf.fill('zz', 'hex')); // Throws an exception. </code></pre> <h3>buf.includes(value[, byteOffset][, encoding])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L820">[src]</a><span><a class="mark" href="#buffer_buf_includes_value_byteoffset_encoding" id="buffer_buf_includes_value_byteoffset_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.3.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> What to search for.</li> <li><code>byteOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where to begin searching in <code>buf</code>. <strong>Default:</strong> <code>0</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If <code>value</code> is a string, this is its encoding. <strong>Default:</strong> <code>'utf8'</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if <code>value</code> was found in <code>buf</code>, <code>false</code> otherwise.</li> </ul> <p>Equivalent to <a href="#buffer_buf_indexof_value_byteoffset_encoding"><code>buf.indexOf() !== -1</code></a>.</p> <pre><code class="language-js">const buf = Buffer.from('this is a buffer'); console.log(buf.includes('this')); // Prints: true console.log(buf.includes('is')); // Prints: true console.log(buf.includes(Buffer.from('a buffer'))); // Prints: true console.log(buf.includes(97)); // Prints: true (97 is the decimal ASCII value for 'a') console.log(buf.includes(Buffer.from('a buffer example'))); // Prints: false console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); // Prints: true console.log(buf.includes('this', 4)); // Prints: false </code></pre> <h3>buf.indexOf(value[, byteOffset][, encoding])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L812">[src]</a><span><a class="mark" href="#buffer_buf_indexof_value_byteoffset_encoding" id="buffer_buf_indexof_value_byteoffset_encoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>value</code> can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v5.7.0, v4.4.0</td> <td><p>When <code>encoding</code> is being passed, the <code>byteOffset</code> parameter is no longer required.</p></td></tr> <tr><td>v1.5.0</td> <td><p><span>Added in: v1.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> What to search for.</li> <li><code>byteOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where to begin searching in <code>buf</code>. <strong>Default:</strong> <code>0</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If <code>value</code> is a string, this is the encoding used to determine the binary representation of the string that will be searched for in <code>buf</code>. <strong>Default:</strong> <code>'utf8'</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The index of the first occurrence of <code>value</code> in <code>buf</code>, or <code>-1</code> if <code>buf</code> does not contain <code>value</code>.</li> </ul> <p>If <code>value</code> is:</p> <ul> <li>a string, <code>value</code> is interpreted according to the character encoding in <code>encoding</code>.</li> <li>a <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>, <code>value</code> will be used in its entirety. To compare a partial <code>Buffer</code>, use <a href="#buffer_buf_slice_start_end"><code>buf.slice()</code></a>.</li> <li>a number, <code>value</code> will be interpreted as an unsigned 8-bit integer value between <code>0</code> and <code>255</code>.</li> </ul> <pre><code class="language-js">const buf = Buffer.from('this is a buffer'); console.log(buf.indexOf('this')); // Prints: 0 console.log(buf.indexOf('is')); // Prints: 2 console.log(buf.indexOf(Buffer.from('a buffer'))); // Prints: 8 console.log(buf.indexOf(97)); // Prints: 8 (97 is the decimal ASCII value for 'a') console.log(buf.indexOf(Buffer.from('a buffer example'))); // Prints: -1 console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); // Prints: 8 const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); // Prints: 4 console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); // Prints: 6 </code></pre> <p>If <code>value</code> is not a string, number, or <code>Buffer</code>, this method will throw a <code>TypeError</code>. If <code>value</code> is a number, it will be coerced to a valid byte value, an integer between 0 and 255.</p> <p>If <code>byteOffset</code> is not a number, it will be coerced to a number. If the result of coercion is <code>NaN</code> or <code>0</code>, then the entire buffer will be searched. This behavior matches <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf"><code>String#indexOf()</code></a>.</p> <pre><code class="language-js">const b = Buffer.from('abcdef'); // Passing a value that's a number, but not a valid byte // Prints: 2, equivalent to searching for 99 or 'c' console.log(b.indexOf(99.9)); console.log(b.indexOf(256 + 99)); // Passing a byteOffset that coerces to NaN or 0 // Prints: 1, searching the whole buffer console.log(b.indexOf('b', undefined)); console.log(b.indexOf('b', {})); console.log(b.indexOf('b', null)); console.log(b.indexOf('b', [])); </code></pre> <p>If <code>value</code> is an empty string or empty <code>Buffer</code> and <code>byteOffset</code> is less than <code>buf.length</code>, <code>byteOffset</code> will be returned. If <code>value</code> is empty and <code>byteOffset</code> is at least <code>buf.length</code>, <code>buf.length</code> will be returned.</p> <h3>buf.keys()<span><a class="mark" href="#buffer_buf_keys" id="buffer_buf_keys">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.1.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li> </ul> <p>Creates and returns an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterator</a> of <code>buf</code> keys (indices).</p> <pre><code class="language-js">const buf = Buffer.from('buffer'); for (const key of buf.keys()) { console.log(key); } // Prints: // 0 // 1 // 2 // 3 // 4 // 5 </code></pre> <h3>buf.lastIndexOf(value[, byteOffset][, encoding])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L816">[src]</a><span><a class="mark" href="#buffer_buf_lastindexof_value_byteoffset_encoding" id="buffer_buf_lastindexof_value_byteoffset_encoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>value</code> can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v6.0.0</td> <td><p><span>Added in: v6.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> What to search for.</li> <li><code>byteOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where to begin searching in <code>buf</code>. <strong>Default:</strong> <a href="#buffer_buf_length"><code>buf.length</code></a><code>- 1</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If <code>value</code> is a string, this is the encoding used to determine the binary representation of the string that will be searched for in <code>buf</code>. <strong>Default:</strong> <code>'utf8'</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The index of the last occurrence of <code>value</code> in <code>buf</code>, or <code>-1</code> if <code>buf</code> does not contain <code>value</code>.</li> </ul> <p>Identical to <a href="#buffer_buf_indexof_value_byteoffset_encoding"><code>buf.indexOf()</code></a>, except the last occurrence of <code>value</code> is found rather than the first occurrence.</p> <pre><code class="language-js">const buf = Buffer.from('this buffer is a buffer'); console.log(buf.lastIndexOf('this')); // Prints: 0 console.log(buf.lastIndexOf('buffer')); // Prints: 17 console.log(buf.lastIndexOf(Buffer.from('buffer'))); // Prints: 17 console.log(buf.lastIndexOf(97)); // Prints: 15 (97 is the decimal ASCII value for 'a') console.log(buf.lastIndexOf(Buffer.from('yolo'))); // Prints: -1 console.log(buf.lastIndexOf('buffer', 5)); // Prints: 5 console.log(buf.lastIndexOf('buffer', 4)); // Prints: -1 const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); // Prints: 6 console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); // Prints: 4 </code></pre> <p>If <code>value</code> is not a string, number, or <code>Buffer</code>, this method will throw a <code>TypeError</code>. If <code>value</code> is a number, it will be coerced to a valid byte value, an integer between 0 and 255.</p> <p>If <code>byteOffset</code> is not a number, it will be coerced to a number. Any arguments that coerce to <code>NaN</code>, like <code>{}</code> or <code>undefined</code>, will search the whole buffer. This behavior matches <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf"><code>String#lastIndexOf()</code></a>.</p> <pre><code class="language-js">const b = Buffer.from('abcdef'); // Passing a value that's a number, but not a valid byte // Prints: 2, equivalent to searching for 99 or 'c' console.log(b.lastIndexOf(99.9)); console.log(b.lastIndexOf(256 + 99)); // Passing a byteOffset that coerces to NaN // Prints: 1, searching the whole buffer console.log(b.lastIndexOf('b', undefined)); console.log(b.lastIndexOf('b', {})); // Passing a byteOffset that coerces to 0 // Prints: -1, equivalent to passing 0 console.log(b.lastIndexOf('b', null)); console.log(b.lastIndexOf('b', [])); </code></pre> <p>If <code>value</code> is an empty string or empty <code>Buffer</code>, <code>byteOffset</code> will be returned.</p> <h3>buf.length<span><a class="mark" href="#buffer_buf_length" id="buffer_buf_length">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Returns the amount of memory allocated for <code>buf</code> in bytes. Note that this does not necessarily reflect the amount of "usable" data within <code>buf</code>.</p> <pre><code class="language-js">// Create a `Buffer` and write a shorter ASCII string to it. const buf = Buffer.alloc(1234); console.log(buf.length); // Prints: 1234 buf.write('some string', 0, 'ascii'); console.log(buf.length); // Prints: 1234 </code></pre> <p>While the <code>length</code> property is not immutable, changing the value of <code>length</code> can result in undefined and inconsistent behavior. Applications that wish to modify the length of a <code>Buffer</code> should therefore treat <code>length</code> as read-only and use <a href="#buffer_buf_slice_start_end"><code>buf.slice()</code></a> to create a new <code>Buffer</code>.</p> <pre><code class="language-js">let buf = Buffer.allocUnsafe(10); buf.write('abcdefghj', 0, 'ascii'); console.log(buf.length); // Prints: 10 buf = buf.slice(0, 5); console.log(buf.length); // Prints: 5 </code></pre> <h3>buf.parent<span><a class="mark" href="#buffer_buf_parent" id="buffer_buf_parent">#</a></span></h3> <div class="api_metadata"> <span>Deprecated since: v8.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_buf_buffer"><code>buf.buffer</code></a> instead.</div><p></p> <p>The <code>buf.parent</code> property is a deprecated alias for <code>buf.buffer</code>.</p> <h3>buf.readBigInt64BE(offset)<span><a class="mark" href="#buffer_buf_readbigint64be_offset" id="buffer_buf_readbigint64be_offset">#</a></span></h3> <h3>buf.readBigInt64LE(offset)<span><a class="mark" href="#buffer_buf_readbigint64le_offset" id="buffer_buf_readbigint64le_offset">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li> <li>Returns: <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>Reads a signed 64-bit integer from <code>buf</code> at the specified <code>offset</code> with the specified endian format (<code>readBigInt64BE()</code> returns big endian, <code>readBigInt64LE()</code> returns little endian).</p> <p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p> <h3>buf.readBigUInt64BE(offset)<span><a class="mark" href="#buffer_buf_readbiguint64be_offset" id="buffer_buf_readbiguint64be_offset">#</a></span></h3> <h3>buf.readBigUInt64LE(offset)<span><a class="mark" href="#buffer_buf_readbiguint64le_offset" id="buffer_buf_readbiguint64le_offset">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li> <li>Returns: <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>Reads an unsigned 64-bit integer from <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>readBigUInt64BE()</code> returns big endian, <code>readBigUInt64LE()</code> returns little endian).</p> <pre><code class="language-js">const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); console.log(buf.readBigUInt64BE(0)); // Prints: 4294967295n console.log(buf.readBigUInt64LE(0)); // Prints: 18446744069414584320n </code></pre> <h3>buf.readDoubleBE(offset)<span><a class="mark" href="#buffer_buf_readdoublebe_offset" id="buffer_buf_readdoublebe_offset">#</a></span></h3> <h3>buf.readDoubleLE(offset)<span><a class="mark" href="#buffer_buf_readdoublele_offset" id="buffer_buf_readdoublele_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.11.15</td> <td><p><span>Added in: v0.11.15</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy <code>0 <= offset <= buf.length - 8</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Reads a 64-bit double from <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>readDoubleBE()</code> returns big endian, <code>readDoubleLE()</code> returns little endian).</p> <pre><code class="language-js">const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); console.log(buf.readDoubleBE(0)); // Prints: 8.20788039913184e-304 console.log(buf.readDoubleLE(0)); // Prints: 5.447603722011605e-270 console.log(buf.readDoubleLE(1)); // Throws ERR_OUT_OF_RANGE </code></pre> <h3>buf.readFloatBE(offset)<span><a class="mark" href="#buffer_buf_readfloatbe_offset" id="buffer_buf_readfloatbe_offset">#</a></span></h3> <h3>buf.readFloatLE(offset)<span><a class="mark" href="#buffer_buf_readfloatle_offset" id="buffer_buf_readfloatle_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.11.15</td> <td><p><span>Added in: v0.11.15</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy <code>0 <= offset <= buf.length - 4</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Reads a 32-bit float from <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>readFloatBE()</code> returns big endian, <code>readFloatLE()</code> returns little endian).</p> <pre><code class="language-js">const buf = Buffer.from([1, 2, 3, 4]); console.log(buf.readFloatBE(0)); // Prints: 2.387939260590663e-38 console.log(buf.readFloatLE(0)); // Prints: 1.539989614439558e-36 console.log(buf.readFloatLE(1)); // Throws ERR_OUT_OF_RANGE </code></pre> <h3>buf.readInt8(offset)<span><a class="mark" href="#buffer_buf_readint8_offset" id="buffer_buf_readint8_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.0</td> <td><p><span>Added in: v0.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy <code>0 <= offset <= buf.length - 1</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Reads a signed 8-bit integer from <code>buf</code> at the specified <code>offset</code>.</p> <p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p> <pre><code class="language-js">const buf = Buffer.from([-1, 5]); console.log(buf.readInt8(0)); // Prints: -1 console.log(buf.readInt8(1)); // Prints: 5 console.log(buf.readInt8(2)); // Throws ERR_OUT_OF_RANGE </code></pre> <h3>buf.readInt16BE(offset)<span><a class="mark" href="#buffer_buf_readint16be_offset" id="buffer_buf_readint16be_offset">#</a></span></h3> <h3>buf.readInt16LE(offset)<span><a class="mark" href="#buffer_buf_readint16le_offset" id="buffer_buf_readint16le_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.5</td> <td><p><span>Added in: v0.5.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy <code>0 <= offset <= buf.length - 2</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Reads a signed 16-bit integer from <code>buf</code> at the specified <code>offset</code> with the specified endian format (<code>readInt16BE()</code> returns big endian, <code>readInt16LE()</code> returns little endian).</p> <p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p> <pre><code class="language-js">const buf = Buffer.from([0, 5]); console.log(buf.readInt16BE(0)); // Prints: 5 console.log(buf.readInt16LE(0)); // Prints: 1280 console.log(buf.readInt16LE(1)); // Throws ERR_OUT_OF_RANGE </code></pre> <h3>buf.readInt32BE(offset)<span><a class="mark" href="#buffer_buf_readint32be_offset" id="buffer_buf_readint32be_offset">#</a></span></h3> <h3>buf.readInt32LE(offset)<span><a class="mark" href="#buffer_buf_readint32le_offset" id="buffer_buf_readint32le_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.5</td> <td><p><span>Added in: v0.5.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy <code>0 <= offset <= buf.length - 4</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Reads a signed 32-bit integer from <code>buf</code> at the specified <code>offset</code> with the specified endian format (<code>readInt32BE()</code> returns big endian, <code>readInt32LE()</code> returns little endian).</p> <p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p> <pre><code class="language-js">const buf = Buffer.from([0, 0, 0, 5]); console.log(buf.readInt32BE(0)); // Prints: 5 console.log(buf.readInt32LE(0)); // Prints: 83886080 console.log(buf.readInt32LE(1)); // Throws ERR_OUT_OF_RANGE </code></pre> <h3>buf.readIntBE(offset, byteLength)<span><a class="mark" href="#buffer_buf_readintbe_offset_bytelength" id="buffer_buf_readintbe_offset_bytelength">#</a></span></h3> <h3>buf.readIntLE(offset, byteLength)<span><a class="mark" href="#buffer_buf_readintle_offset_bytelength" id="buffer_buf_readintle_offset_bytelength">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.11.15</td> <td><p><span>Added in: v0.11.15</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li> <li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to read. Must satisfy <code>0 < byteLength <= 6</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Reads <code>byteLength</code> number of bytes from <code>buf</code> at the specified <code>offset</code> and interprets the result as a two's complement signed value. Supports up to 48 bits of accuracy.</p> <pre><code class="language-js">const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); console.log(buf.readIntLE(0, 6).toString(16)); // Prints: -546f87a9cbee console.log(buf.readIntBE(0, 6).toString(16)); // Prints: 1234567890ab console.log(buf.readIntBE(1, 6).toString(16)); // Throws ERR_INDEX_OUT_OF_RANGE console.log(buf.readIntBE(1, 0).toString(16)); // Throws ERR_OUT_OF_RANGE </code></pre> <h3>buf.readUInt8(offset)<span><a class="mark" href="#buffer_buf_readuint8_offset" id="buffer_buf_readuint8_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.0</td> <td><p><span>Added in: v0.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy <code>0 <= offset <= buf.length - 1</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Reads an unsigned 8-bit integer from <code>buf</code> at the specified <code>offset</code>.</p> <pre><code class="language-js">const buf = Buffer.from([1, -2]); console.log(buf.readUInt8(0)); // Prints: 1 console.log(buf.readUInt8(1)); // Prints: 254 console.log(buf.readUInt8(2)); // Throws ERR_OUT_OF_RANGE </code></pre> <h3>buf.readUInt16BE(offset)<span><a class="mark" href="#buffer_buf_readuint16be_offset" id="buffer_buf_readuint16be_offset">#</a></span></h3> <h3>buf.readUInt16LE(offset)<span><a class="mark" href="#buffer_buf_readuint16le_offset" id="buffer_buf_readuint16le_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.5</td> <td><p><span>Added in: v0.5.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy <code>0 <= offset <= buf.length - 2</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Reads an unsigned 16-bit integer from <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>readUInt16BE()</code> returns big endian, <code>readUInt16LE()</code> returns little endian).</p> <pre><code class="language-js">const buf = Buffer.from([0x12, 0x34, 0x56]); console.log(buf.readUInt16BE(0).toString(16)); // Prints: 1234 console.log(buf.readUInt16LE(0).toString(16)); // Prints: 3412 console.log(buf.readUInt16BE(1).toString(16)); // Prints: 3456 console.log(buf.readUInt16LE(1).toString(16)); // Prints: 5634 console.log(buf.readUInt16LE(2).toString(16)); // Throws ERR_OUT_OF_RANGE </code></pre> <h3>buf.readUInt32BE(offset)<span><a class="mark" href="#buffer_buf_readuint32be_offset" id="buffer_buf_readuint32be_offset">#</a></span></h3> <h3>buf.readUInt32LE(offset)<span><a class="mark" href="#buffer_buf_readuint32le_offset" id="buffer_buf_readuint32le_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.5</td> <td><p><span>Added in: v0.5.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy <code>0 <= offset <= buf.length - 4</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Reads an unsigned 32-bit integer from <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>readUInt32BE()</code> returns big endian, <code>readUInt32LE()</code> returns little endian).</p> <pre><code class="language-js">const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); console.log(buf.readUInt32BE(0).toString(16)); // Prints: 12345678 console.log(buf.readUInt32LE(0).toString(16)); // Prints: 78563412 console.log(buf.readUInt32LE(1).toString(16)); // Throws ERR_OUT_OF_RANGE </code></pre> <h3>buf.readUIntBE(offset, byteLength)<span><a class="mark" href="#buffer_buf_readuintbe_offset_bytelength" id="buffer_buf_readuintbe_offset_bytelength">#</a></span></h3> <h3>buf.readUIntLE(offset, byteLength)<span><a class="mark" href="#buffer_buf_readuintle_offset_bytelength" id="buffer_buf_readuintle_offset_bytelength">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.11.15</td> <td><p><span>Added in: v0.11.15</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to read. Must satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li> <li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to read. Must satisfy <code>0 < byteLength <= 6</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Reads <code>byteLength</code> number of bytes from <code>buf</code> at the specified <code>offset</code> and interprets the result as an unsigned integer. Supports up to 48 bits of accuracy.</p> <pre><code class="language-js">const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); console.log(buf.readUIntBE(0, 6).toString(16)); // Prints: 1234567890ab console.log(buf.readUIntLE(0, 6).toString(16)); // Prints: ab9078563412 console.log(buf.readUIntBE(1, 6).toString(16)); // Throws ERR_OUT_OF_RANGE </code></pre> <h3>buf.slice([start[, end]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L1007">[src]</a><span><a class="mark" href="#buffer_buf_slice_start_end" id="buffer_buf_slice_start_end">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.1.0, v6.9.2</td> <td><p>Coercing the offsets to integers now handles values outside the 32-bit integer range properly.</p></td></tr> <tr><td>v7.0.0</td> <td><p>All offsets are now coerced to integers before doing any calculations with them.</p></td></tr> <tr><td>v0.3.0</td> <td><p><span>Added in: v0.3.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where the new <code>Buffer</code> will start. <strong>Default:</strong> <code>0</code>.</li> <li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Where the new <code>Buffer</code> will end (not inclusive). <strong>Default:</strong> <a href="#buffer_buf_length"><code>buf.length</code></a>.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Returns a new <code>Buffer</code> that references the same memory as the original, but offset and cropped by the <code>start</code> and <code>end</code> indices.</p> <p>Specifying <code>end</code> greater than <a href="#buffer_buf_length"><code>buf.length</code></a> will return the same result as that of <code>end</code> equal to <a href="#buffer_buf_length"><code>buf.length</code></a>.</p> <p>Modifying the new <code>Buffer</code> slice will modify the memory in the original <code>Buffer</code> because the allocated memory of the two objects overlap.</p> <pre><code class="language-js">// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte // from the original `Buffer`. const buf1 = Buffer.allocUnsafe(26); for (let i = 0; i < 26; i++) { // 97 is the decimal ASCII value for 'a' buf1[i] = i + 97; } const buf2 = buf1.slice(0, 3); console.log(buf2.toString('ascii', 0, buf2.length)); // Prints: abc buf1[0] = 33; console.log(buf2.toString('ascii', 0, buf2.length)); // Prints: !bc </code></pre> <p>Specifying negative indexes causes the slice to be generated relative to the end of <code>buf</code> rather than the beginning.</p> <pre><code class="language-js">const buf = Buffer.from('buffer'); console.log(buf.slice(-6, -1).toString()); // Prints: buffe // (Equivalent to buf.slice(0, 5)) console.log(buf.slice(-6, -2).toString()); // Prints: buff // (Equivalent to buf.slice(0, 4)) console.log(buf.slice(-5, -2).toString()); // Prints: uff // (Equivalent to buf.slice(1, 4)) </code></pre> <h3>buf.swap16()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L1021">[src]</a><span><a class="mark" href="#buffer_buf_swap16" id="buffer_buf_swap16">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.10.0</span> </div> <ul> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> A reference to <code>buf</code>.</li> </ul> <p>Interprets <code>buf</code> as an array of unsigned 16-bit integers and swaps the byte order <em>in-place</em>. Throws <a href="#ERR_INVALID_BUFFER_SIZE"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#buffer_buf_length"><code>buf.length</code></a> is not a multiple of 2.</p> <pre><code class="language-js">const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); console.log(buf1); // Prints: <Buffer 01 02 03 04 05 06 07 08> buf1.swap16(); console.log(buf1); // Prints: <Buffer 02 01 04 03 06 05 08 07> const buf2 = Buffer.from([0x1, 0x2, 0x3]); buf2.swap16(); // Throws ERR_INVALID_BUFFER_SIZE </code></pre> <p>One convenient use of <code>buf.swap16()</code> is to perform a fast in-place conversion between UTF-16 little-endian and UTF-16 big-endian:</p> <pre><code class="language-js">const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); buf.swap16(); // Convert to big-endian UTF-16 text. </code></pre> <h3>buf.swap32()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L1036">[src]</a><span><a class="mark" href="#buffer_buf_swap32" id="buffer_buf_swap32">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.10.0</span> </div> <ul> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> A reference to <code>buf</code>.</li> </ul> <p>Interprets <code>buf</code> as an array of unsigned 32-bit integers and swaps the byte order <em>in-place</em>. Throws <a href="#ERR_INVALID_BUFFER_SIZE"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#buffer_buf_length"><code>buf.length</code></a> is not a multiple of 4.</p> <pre><code class="language-js">const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); console.log(buf1); // Prints: <Buffer 01 02 03 04 05 06 07 08> buf1.swap32(); console.log(buf1); // Prints: <Buffer 04 03 02 01 08 07 06 05> const buf2 = Buffer.from([0x1, 0x2, 0x3]); buf2.swap32(); // Throws ERR_INVALID_BUFFER_SIZE </code></pre> <h3>buf.swap64()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L1053">[src]</a><span><a class="mark" href="#buffer_buf_swap64" id="buffer_buf_swap64">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.3.0</span> </div> <ul> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> A reference to <code>buf</code>.</li> </ul> <p>Interprets <code>buf</code> as an array of 64-bit numbers and swaps byte order <em>in-place</em>. Throws <a href="#ERR_INVALID_BUFFER_SIZE"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#buffer_buf_length"><code>buf.length</code></a> is not a multiple of 8.</p> <pre><code class="language-js">const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); console.log(buf1); // Prints: <Buffer 01 02 03 04 05 06 07 08> buf1.swap64(); console.log(buf1); // Prints: <Buffer 08 07 06 05 04 03 02 01> const buf2 = Buffer.from([0x1, 0x2, 0x3]); buf2.swap64(); // Throws ERR_INVALID_BUFFER_SIZE </code></pre> <p>Note that JavaScript cannot encode 64-bit integers. This method is intended for working with 64-bit floats.</p> <h3>buf.toJSON()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L979">[src]</a><span><a class="mark" href="#buffer_buf_tojson" id="buffer_buf_tojson">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.2</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns a JSON representation of <code>buf</code>. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify"><code>JSON.stringify()</code></a> implicitly calls this function when stringifying a <code>Buffer</code> instance.</p> <pre><code class="language-js">const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); const json = JSON.stringify(buf); console.log(json); // Prints: {"type":"Buffer","data":[1,2,3,4,5]} const copy = JSON.parse(json, (key, value) => { return value && value.type === 'Buffer' ? Buffer.from(value.data) : value; }); console.log(copy); // Prints: <Buffer 01 02 03 04 05> </code></pre> <h3>buf.toString([encoding[, start[, end]]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L643">[src]</a><span><a class="mark" href="#buffer_buf_tostring_encoding_start_end" id="buffer_buf_tostring_encoding_start_end">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The character encoding to use. <strong>Default:</strong> <code>'utf8'</code>.</li> <li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The byte offset to start decoding at. <strong>Default:</strong> <code>0</code>.</li> <li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The byte offset to stop decoding at (not inclusive). <strong>Default:</strong> <a href="#buffer_buf_length"><code>buf.length</code></a>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Decodes <code>buf</code> to a string according to the specified character encoding in <code>encoding</code>. <code>start</code> and <code>end</code> may be passed to decode only a subset of <code>buf</code>.</p> <p>The maximum length of a string instance (in UTF-16 code units) is available as <a href="#buffer_buffer_constants_max_string_length"><code>buffer.constants.MAX_STRING_LENGTH</code></a>.</p> <pre><code class="language-js">const buf1 = Buffer.allocUnsafe(26); for (let i = 0; i < 26; i++) { // 97 is the decimal ASCII value for 'a' buf1[i] = i + 97; } console.log(buf1.toString('ascii')); // Prints: abcdefghijklmnopqrstuvwxyz console.log(buf1.toString('ascii', 0, 5)); // Prints: abcde const buf2 = Buffer.from('tést'); console.log(buf2.toString('hex')); // Prints: 74c3a97374 console.log(buf2.toString('utf8', 0, 3)); // Prints: té console.log(buf2.toString(undefined, 0, 3)); // Prints: té </code></pre> <h3>buf.values()<span><a class="mark" href="#buffer_buf_values" id="buffer_buf_values">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.1.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li> </ul> <p>Creates and returns an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterator</a> for <code>buf</code> values (bytes). This function is called automatically when a <code>Buffer</code> is used in a <code>for..of</code> statement.</p> <pre><code class="language-js">const buf = Buffer.from('buffer'); for (const value of buf.values()) { console.log(value); } // Prints: // 98 // 117 // 102 // 102 // 101 // 114 for (const value of buf) { console.log(value); } // Prints: // 98 // 117 // 102 // 102 // 101 // 114 </code></pre> <h3>buf.write(string[, offset[, length]][, encoding])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/buffer.js#L896">[src]</a><span><a class="mark" href="#buffer_buf_write_string_offset_length_encoding" id="buffer_buf_write_string_offset_length_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> String to write to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write <code>string</code>. <strong>Default:</strong> <code>0</code>.</li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to write. <strong>Default:</strong> <code>buf.length - offset</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The character encoding of <code>string</code>. <strong>Default:</strong> <code>'utf8'</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes written.</li> </ul> <p>Writes <code>string</code> to <code>buf</code> at <code>offset</code> according to the character encoding in <code>encoding</code>. The <code>length</code> parameter is the number of bytes to write. If <code>buf</code> did not contain enough space to fit the entire string, only part of <code>string</code> will be written. However, partially encoded characters will not be written.</p> <pre><code class="language-js">const buf = Buffer.alloc(256); const len = buf.write('\u00bd + \u00bc = \u00be', 0); console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); // Prints: 12 bytes: ½ + ¼ = ¾ </code></pre> <h3>buf.writeBigInt64BE(value, offset)<span><a class="mark" href="#buffer_buf_writebigint64be_value_offset" id="buffer_buf_writebigint64be_value_offset">#</a></span></h3> <h3>buf.writeBigInt64LE(value, offset)<span><a class="mark" href="#buffer_buf_writebigint64le_value_offset" id="buffer_buf_writebigint64le_value_offset">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> </div> <ul> <li><code>value</code> <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>writeBigInt64BE()</code> writes big endian, <code>writeBigInt64LE()</code> writes little endian).</p> <p><code>value</code> is interpreted and written as a two's complement signed integer.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(8); buf.writeBigInt64BE(0x0102030405060708n, 0); console.log(buf); // Prints: <Buffer 01 02 03 04 05 06 07 08> </code></pre> <h3>buf.writeBigUInt64BE(value, offset)<span><a class="mark" href="#buffer_buf_writebiguint64be_value_offset" id="buffer_buf_writebiguint64be_value_offset">#</a></span></h3> <h3>buf.writeBigUInt64LE(value, offset)<span><a class="mark" href="#buffer_buf_writebiguint64le_value_offset" id="buffer_buf_writebiguint64le_value_offset">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> </div> <ul> <li><code>value</code> <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy: <code>0 <= offset <= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>writeBigUInt64BE()</code> writes big endian, <code>writeBigUInt64LE()</code> writes little endian).</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(8); buf.writeBigUInt64LE(0xdecafafecacefaden, 0); console.log(buf); // Prints: <Buffer de fa ce ca fe fa ca de> </code></pre> <h3>buf.writeDoubleBE(value, offset)<span><a class="mark" href="#buffer_buf_writedoublebe_value_offset" id="buffer_buf_writedoublebe_value_offset">#</a></span></h3> <h3>buf.writeDoubleLE(value, offset)<span><a class="mark" href="#buffer_buf_writedoublele_value_offset" id="buffer_buf_writedoublele_value_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.11.15</td> <td><p><span>Added in: v0.11.15</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy <code>0 <= offset <= buf.length - 8</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>writeDoubleBE()</code> writes big endian, <code>writeDoubleLE()</code> writes little endian). <code>value</code> <em>should</em> be a valid 64-bit double. Behavior is undefined when <code>value</code> is anything other than a 64-bit double.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(8); buf.writeDoubleBE(123.456, 0); console.log(buf); // Prints: <Buffer 40 5e dd 2f 1a 9f be 77> buf.writeDoubleLE(123.456, 0); console.log(buf); // Prints: <Buffer 77 be 9f 1a 2f dd 5e 40> </code></pre> <h3>buf.writeFloatBE(value, offset)<span><a class="mark" href="#buffer_buf_writefloatbe_value_offset" id="buffer_buf_writefloatbe_value_offset">#</a></span></h3> <h3>buf.writeFloatLE(value, offset)<span><a class="mark" href="#buffer_buf_writefloatle_value_offset" id="buffer_buf_writefloatle_value_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.11.15</td> <td><p><span>Added in: v0.11.15</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy <code>0 <= offset <= buf.length - 4</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>writeFloatBE()</code> writes big endian, <code>writeFloatLE()</code> writes little endian). <code>value</code> <em>should</em> be a valid 32-bit float. Behavior is undefined when <code>value</code> is anything other than a 32-bit float.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(4); buf.writeFloatBE(0xcafebabe, 0); console.log(buf); // Prints: <Buffer 4f 4a fe bb> buf.writeFloatLE(0xcafebabe, 0); console.log(buf); // Prints: <Buffer bb fe 4a 4f> </code></pre> <h3>buf.writeInt8(value, offset)<span><a class="mark" href="#buffer_buf_writeint8_value_offset" id="buffer_buf_writeint8_value_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.0</td> <td><p><span>Added in: v0.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy <code>0 <= offset <= buf.length - 1</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code>. <code>value</code> <em>should</em> be a valid signed 8-bit integer. Behavior is undefined when <code>value</code> is anything other than a signed 8-bit integer.</p> <p><code>value</code> is interpreted and written as a two's complement signed integer.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(2); buf.writeInt8(2, 0); buf.writeInt8(-2, 1); console.log(buf); // Prints: <Buffer 02 fe> </code></pre> <h3>buf.writeInt16BE(value, offset)<span><a class="mark" href="#buffer_buf_writeint16be_value_offset" id="buffer_buf_writeint16be_value_offset">#</a></span></h3> <h3>buf.writeInt16LE(value, offset)<span><a class="mark" href="#buffer_buf_writeint16le_value_offset" id="buffer_buf_writeint16le_value_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.5</td> <td><p><span>Added in: v0.5.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy <code>0 <= offset <= buf.length - 2</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>writeInt16BE()</code> writes big endian, <code>writeInt16LE()</code> writes little endian). <code>value</code> <em>should</em> be a valid signed 16-bit integer. Behavior is undefined when <code>value</code> is anything other than a signed 16-bit integer.</p> <p><code>value</code> is interpreted and written as a two's complement signed integer.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(4); buf.writeInt16BE(0x0102, 0); buf.writeInt16LE(0x0304, 2); console.log(buf); // Prints: <Buffer 01 02 04 03> </code></pre> <h3>buf.writeInt32BE(value, offset)<span><a class="mark" href="#buffer_buf_writeint32be_value_offset" id="buffer_buf_writeint32be_value_offset">#</a></span></h3> <h3>buf.writeInt32LE(value, offset)<span><a class="mark" href="#buffer_buf_writeint32le_value_offset" id="buffer_buf_writeint32le_value_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.5</td> <td><p><span>Added in: v0.5.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy <code>0 <= offset <= buf.length - 4</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>writeInt32BE()</code> writes big endian, <code>writeInt32LE()</code> writes little endian). <code>value</code> <em>should</em> be a valid signed 32-bit integer. Behavior is undefined when <code>value</code> is anything other than a signed 32-bit integer.</p> <p><code>value</code> is interpreted and written as a two's complement signed integer.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(8); buf.writeInt32BE(0x01020304, 0); buf.writeInt32LE(0x05060708, 4); console.log(buf); // Prints: <Buffer 01 02 03 04 08 07 06 05> </code></pre> <h3>buf.writeIntBE(value, offset, byteLength)<span><a class="mark" href="#buffer_buf_writeintbe_value_offset_bytelength" id="buffer_buf_writeintbe_value_offset_bytelength">#</a></span></h3> <h3>buf.writeIntLE(value, offset, byteLength)<span><a class="mark" href="#buffer_buf_writeintle_value_offset_bytelength" id="buffer_buf_writeintle_value_offset_bytelength">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.11.15</td> <td><p><span>Added in: v0.11.15</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li> <li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to write. Must satisfy <code>0 < byteLength <= 6</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>byteLength</code> bytes of <code>value</code> to <code>buf</code> at the specified <code>offset</code>. Supports up to 48 bits of accuracy. Behavior is undefined when <code>value</code> is anything other than a signed integer.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(6); buf.writeIntBE(0x1234567890ab, 0, 6); console.log(buf); // Prints: <Buffer 12 34 56 78 90 ab> buf.writeIntLE(0x1234567890ab, 0, 6); console.log(buf); // Prints: <Buffer ab 90 78 56 34 12> </code></pre> <h3>buf.writeUInt8(value, offset)<span><a class="mark" href="#buffer_buf_writeuint8_value_offset" id="buffer_buf_writeuint8_value_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.0</td> <td><p><span>Added in: v0.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy <code>0 <= offset <= buf.length - 1</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code>. <code>value</code> <em>should</em> be a valid unsigned 8-bit integer. Behavior is undefined when <code>value</code> is anything other than an unsigned 8-bit integer.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(4); buf.writeUInt8(0x3, 0); buf.writeUInt8(0x4, 1); buf.writeUInt8(0x23, 2); buf.writeUInt8(0x42, 3); console.log(buf); // Prints: <Buffer 03 04 23 42> </code></pre> <h3>buf.writeUInt16BE(value, offset)<span><a class="mark" href="#buffer_buf_writeuint16be_value_offset" id="buffer_buf_writeuint16be_value_offset">#</a></span></h3> <h3>buf.writeUInt16LE(value, offset)<span><a class="mark" href="#buffer_buf_writeuint16le_value_offset" id="buffer_buf_writeuint16le_value_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.5</td> <td><p><span>Added in: v0.5.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy <code>0 <= offset <= buf.length - 2</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>writeUInt16BE()</code> writes big endian, <code>writeUInt16LE()</code> writes little endian). <code>value</code> should be a valid unsigned 16-bit integer. Behavior is undefined when <code>value</code> is anything other than an unsigned 16-bit integer.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(4); buf.writeUInt16BE(0xdead, 0); buf.writeUInt16BE(0xbeef, 2); console.log(buf); // Prints: <Buffer de ad be ef> buf.writeUInt16LE(0xdead, 0); buf.writeUInt16LE(0xbeef, 2); console.log(buf); // Prints: <Buffer ad de ef be> </code></pre> <h3>buf.writeUInt32BE(value, offset)<span><a class="mark" href="#buffer_buf_writeuint32be_value_offset" id="buffer_buf_writeuint32be_value_offset">#</a></span></h3> <h3>buf.writeUInt32LE(value, offset)<span><a class="mark" href="#buffer_buf_writeuint32le_value_offset" id="buffer_buf_writeuint32le_value_offset">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.5</td> <td><p><span>Added in: v0.5.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy <code>0 <= offset <= buf.length - 4</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>value</code> to <code>buf</code> at the specified <code>offset</code> with specified endian format (<code>writeUInt32BE()</code> writes big endian, <code>writeUInt32LE()</code> writes little endian). <code>value</code> should be a valid unsigned 32-bit integer. Behavior is undefined when <code>value</code> is anything other than an unsigned 32-bit integer.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(4); buf.writeUInt32BE(0xfeedface, 0); console.log(buf); // Prints: <Buffer fe ed fa ce> buf.writeUInt32LE(0xfeedface, 0); console.log(buf); // Prints: <Buffer ce fa ed fe> </code></pre> <h3>buf.writeUIntBE(value, offset, byteLength)<span><a class="mark" href="#buffer_buf_writeuintbe_value_offset_bytelength" id="buffer_buf_writeuintbe_value_offset_bytelength">#</a></span></h3> <h3>buf.writeUIntLE(value, offset, byteLength)<span><a class="mark" href="#buffer_buf_writeuintle_value_offset_bytelength" id="buffer_buf_writeuintle_value_offset_bytelength">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</p></td></tr> <tr><td>v0.5.5</td> <td><p><span>Added in: v0.5.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number to be written to <code>buf</code>.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to skip before starting to write. Must satisfy <code>0 <= offset <= buf.length - byteLength</code>.</li> <li><code>byteLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes to write. Must satisfy <code>0 < byteLength <= 6</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>offset</code> plus the number of bytes written.</li> </ul> <p>Writes <code>byteLength</code> bytes of <code>value</code> to <code>buf</code> at the specified <code>offset</code>. Supports up to 48 bits of accuracy. Behavior is undefined when <code>value</code> is anything other than an unsigned integer.</p> <pre><code class="language-js">const buf = Buffer.allocUnsafe(6); buf.writeUIntBE(0x1234567890ab, 0, 6); console.log(buf); // Prints: <Buffer 12 34 56 78 90 ab> buf.writeUIntLE(0x1234567890ab, 0, 6); console.log(buf); // Prints: <Buffer ab 90 78 56 34 12> </code></pre> <h2>buffer.INSPECT_MAX_BYTES<span><a class="mark" href="#buffer_buffer_inspect_max_bytes" id="buffer_buffer_inspect_max_bytes">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.4</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>50</code></li> </ul> <p>Returns the maximum number of bytes that will be returned when <code>buf.inspect()</code> is called. This can be overridden by user modules. See <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> for more details on <code>buf.inspect()</code> behavior.</p> <p>Note that this is a property on the <code>buffer</code> module returned by <code>require('buffer')</code>, not on the <code>Buffer</code> global or a <code>Buffer</code> instance.</p> <h2>buffer.kMaxLength<span><a class="mark" href="#buffer_buffer_kmaxlength" id="buffer_buffer_kmaxlength">#</a></span></h2> <div class="api_metadata"> <span>Added in: v3.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The largest size allowed for a single <code>Buffer</code> instance.</li> </ul> <p>An alias for <a href="#buffer_buffer_constants_max_length"><code>buffer.constants.MAX_LENGTH</code></a>.</p> <p>Note that this is a property on the <code>buffer</code> module returned by <code>require('buffer')</code>, not on the <code>Buffer</code> global or a <code>Buffer</code> instance.</p> <h2>buffer.transcode(source, fromEnc, toEnc)<span><a class="mark" href="#buffer_buffer_transcode_source_fromenc_toenc" id="buffer_buffer_transcode_source_fromenc_toenc">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>source</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v7.1.0</td> <td><p><span>Added in: v7.1.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>source</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> A <code>Buffer</code> or <code>Uint8Array</code> instance.</li> <li><code>fromEnc</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The current encoding.</li> <li><code>toEnc</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> To target encoding.</li> </ul> <p>Re-encodes the given <code>Buffer</code> or <code>Uint8Array</code> instance from one character encoding to another. Returns a new <code>Buffer</code> instance.</p> <p>Throws if the <code>fromEnc</code> or <code>toEnc</code> specify invalid character encodings or if conversion from <code>fromEnc</code> to <code>toEnc</code> is not permitted.</p> <p>Encodings supported by <code>buffer.transcode()</code> are: <code>'ascii'</code>, <code>'utf8'</code>, <code>'utf16le'</code>, <code>'ucs2'</code>, <code>'latin1'</code>, and <code>'binary'</code>.</p> <p>The transcoding process will use substitution characters if a given byte sequence cannot be adequately represented in the target encoding. For instance:</p> <pre><code class="language-js">const buffer = require('buffer'); const newBuf = buffer.transcode(Buffer.from('€'), 'utf8', 'ascii'); console.log(newBuf.toString('ascii')); // Prints: '?' </code></pre> <p>Because the Euro (<code>€</code>) sign is not representable in US-ASCII, it is replaced with <code>?</code> in the transcoded <code>Buffer</code>.</p> <p>Note that this is a property on the <code>buffer</code> module returned by <code>require('buffer')</code>, not on the <code>Buffer</code> global or a <code>Buffer</code> instance.</p> <h2>Class: SlowBuffer<span><a class="mark" href="#buffer_class_slowbuffer" id="buffer_class_slowbuffer">#</a></span></h2> <div class="api_metadata"> <span>Deprecated since: v6.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow()</code></a> instead.</div><p></p> <p>Returns an un-pooled <code>Buffer</code>.</p> <p>In order to avoid the garbage collection overhead of creating many individually allocated <code>Buffer</code> instances, by default allocations under 4KB are sliced from a single larger allocated object.</p> <p>In the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled <code>Buffer</code> instance using <code>SlowBuffer</code> then copy out the relevant bits.</p> <pre><code class="language-js">// Need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { let data; while (null !== (data = readable.read())) { // Allocate for retained data const sb = SlowBuffer(10); // Copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); } }); </code></pre> <p>Use of <code>SlowBuffer</code> should be used only as a last resort <em>after</em> a developer has observed undue memory retention in their applications.</p> <h3>new SlowBuffer(size)<span><a class="mark" href="#buffer_new_slowbuffer_size" id="buffer_new_slowbuffer_size">#</a></span></h3> <div class="api_metadata"> <span>Deprecated since: v6.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow()</code></a> instead.</div><p></p> <ul> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The desired length of the new <code>SlowBuffer</code>.</li> </ul> <p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If <code>size</code> is larger than <a href="#buffer_buffer_constants_max_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#ERR_INVALID_OPT_VALUE"><code>ERR_INVALID_OPT_VALUE</code></a> is thrown. A zero-length <code>Buffer</code> is created if <code>size</code> is 0.</p> <p>The underlying memory for <code>SlowBuffer</code> instances is <em>not initialized</em>. The contents of a newly created <code>SlowBuffer</code> are unknown and may contain sensitive data. Use <a href="#buffer_buf_fill_value_offset_end_encoding"><code>buf.fill(0)</code></a> to initialize a <code>SlowBuffer</code> with zeroes.</p> <pre><code class="language-js">const { SlowBuffer } = require('buffer'); const buf = new SlowBuffer(5); console.log(buf); // Prints: (contents may vary): <Buffer 78 e0 82 02 01> buf.fill(0); console.log(buf); // Prints: <Buffer 00 00 00 00 00> </code></pre> <h2>Buffer Constants<span><a class="mark" href="#buffer_buffer_constants" id="buffer_buffer_constants">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.2.0</span> </div> <p>Note that <code>buffer.constants</code> is a property on the <code>buffer</code> module returned by <code>require('buffer')</code>, not on the <code>Buffer</code> global or a <code>Buffer</code> instance.</p> <h3>buffer.constants.MAX_LENGTH<span><a class="mark" href="#buffer_buffer_constants_max_length" id="buffer_buffer_constants_max_length">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.2.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The largest size allowed for a single <code>Buffer</code> instance.</li> </ul> <p>On 32-bit architectures, this value is <code>(2^30)-1</code> (~1GB). On 64-bit architectures, this value is <code>(2^31)-1</code> (~2GB).</p> <p>This value is also available as <a href="#buffer_buffer_kmaxlength"><code>buffer.kMaxLength</code></a>.</p> <h3>buffer.constants.MAX_STRING_LENGTH<span><a class="mark" href="#buffer_buffer_constants_max_string_length" id="buffer_buffer_constants_max_string_length">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.2.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The largest length allowed for a single <code>string</code> instance.</li> </ul> <p>Represents the largest <code>length</code> that a <code>string</code> primitive can have, counted in UTF-16 code units.</p> <p>This value may depend on the JS engine that is being used.</p> <h1>C++ Addons<span><a class="mark" href="#addons_c_addons" id="addons_c_addons">#</a></span></h1> <p>Node.js Addons are dynamically-linked shared objects, written in C++, that can be loaded into Node.js using the <a href="#modules_require"><code>require()</code></a> function, and used just as if they were an ordinary Node.js module. They are used primarily to provide an interface between JavaScript running in Node.js and C/C++ libraries.</p> <p>At the moment, the method for implementing Addons is rather complicated, involving knowledge of several components and APIs:</p> <ul> <li> <p>V8: the C++ library Node.js currently uses to provide the JavaScript implementation. V8 provides the mechanisms for creating objects, calling functions, etc. V8's API is documented mostly in the <code>v8.h</code> header file (<code>deps/v8/include/v8.h</code> in the Node.js source tree), which is also available <a href="https://v8docs.nodesource.com/">online</a>.</p> </li> <li> <p><a href="https://github.com/libuv/libuv">libuv</a>: The C library that implements the Node.js event loop, its worker threads and all of the asynchronous behaviors of the platform. It also serves as a cross-platform abstraction library, giving easy, POSIX-like access across all major operating systems to many common system tasks, such as interacting with the filesystem, sockets, timers, and system events. libuv also provides a pthreads-like threading abstraction that may be used to power more sophisticated asynchronous Addons that need to move beyond the standard event loop. Addon authors are encouraged to think about how to avoid blocking the event loop with I/O or other time-intensive tasks by off-loading work via libuv to non-blocking system operations, worker threads or a custom use of libuv's threads.</p> </li> <li> <p>Internal Node.js libraries. Node.js itself exports a number of C++ APIs that Addons can use — the most important of which is the <code>node::ObjectWrap</code> class.</p> </li> <li> <p>Node.js includes a number of other statically linked libraries including OpenSSL. These other libraries are located in the <code>deps/</code> directory in the Node.js source tree. Only the libuv, OpenSSL, V8 and zlib symbols are purposefully re-exported by Node.js and may be used to various extents by Addons. See <a href="#addons_linking_to_node_js_own_dependencies">Linking to Node.js' own dependencies</a> for additional information.</p> </li> </ul> <p>All of the following examples are available for <a href="https://github.com/nodejs/node-addon-examples">download</a> and may be used as the starting-point for an Addon.</p> <h2>Hello world<span><a class="mark" href="#addons_hello_world" id="addons_hello_world">#</a></span></h2> <p>This "Hello world" example is a simple Addon, written in C++, that is the equivalent of the following JavaScript code:</p> <pre><code class="language-js">module.exports.hello = () => 'world'; </code></pre> <p>First, create the file <code>hello.cc</code>:</p> <pre><code class="language-cpp">// hello.cc #include <node.h> namespace demo { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Object; using v8::String; using v8::Value; void Method(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8( isolate, "world", NewStringType::kNormal).ToLocalChecked()); } void Initialize(Local<Object> exports) { NODE_SET_METHOD(exports, "hello", Method); } NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) } // namespace demo </code></pre> <p>Note that all Node.js Addons must export an initialization function following the pattern:</p> <pre><code class="language-cpp">void Initialize(Local<Object> exports); NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize) </code></pre> <p>There is no semi-colon after <code>NODE_MODULE</code> as it's not a function (see <code>node.h</code>).</p> <p>The <code>module_name</code> must match the filename of the final binary (excluding the <code>.node</code> suffix).</p> <p>In the <code>hello.cc</code> example, then, the initialization function is <code>Initialize</code> and the addon module name is <code>addon</code>.</p> <p>When building addons with <code>node-gyp</code>, using the macro <code>NODE_GYP_MODULE_NAME</code> as the first parameter of <code>NODE_MODULE()</code> will ensure that the name of the final binary will be passed to <code>NODE_MODULE()</code>.</p> <h3>Context-aware addons<span><a class="mark" href="#addons_context_aware_addons" id="addons_context_aware_addons">#</a></span></h3> <p>There are environments in which Node.js addons may need to be loaded multiple times in multiple contexts. For example, the <a href="https://electronjs.org/">Electron</a> runtime runs multiple instances of Node.js in a single process. Each instance will have its own <code>require()</code> cache, and thus each instance will need a native addon to behave correctly when loaded via <code>require()</code>. From the addon's perspective, this means that it must support multiple initializations.</p> <p>A context-aware addon can be constructed by using the macro <code>NODE_MODULE_INITIALIZER</code>, which expands to the name of a function which Node.js will expect to find when it loads an addon. An addon can thus be initialized as in the following example:</p> <pre><code class="language-cpp">using namespace v8; extern "C" NODE_MODULE_EXPORT void NODE_MODULE_INITIALIZER(Local<Object> exports, Local<Value> module, Local<Context> context) { /* Perform addon initialization steps here. */ } </code></pre> <p>Another option is to use the macro <code>NODE_MODULE_INIT()</code>, which will also construct a context-aware addon. Unlike <code>NODE_MODULE()</code>, which is used to construct an addon around a given addon initializer function, <code>NODE_MODULE_INIT()</code> serves as the declaration of such an initializer to be followed by a function body.</p> <p>The following three variables may be used inside the function body following an invocation of <code>NODE_MODULE_INIT()</code>:</p> <ul> <li><code>Local<Object> exports</code>,</li> <li><code>Local<Value> module</code>, and</li> <li><code>Local<Context> context</code></li> </ul> <p>The choice to build a context-aware addon carries with it the responsibility of carefully managing global static data. Since the addon may be loaded multiple times, potentially even from different threads, any global static data stored in the addon must be properly protected, and must not contain any persistent references to JavaScript objects. The reason for this is that JavaScript objects are only valid in one context, and will likely cause a crash when accessed from the wrong context or from a different thread than the one on which they were created.</p> <p>The context-aware addon can be structured to avoid global static data by performing the following steps:</p> <ul> <li>defining a class which will hold per-addon-instance data. Such a class should include a <code>v8::Persistent<v8::Object></code> which will hold a weak reference to the addon's <code>exports</code> object. The callback associated with the weak reference will then destroy the instance of the class.</li> <li>constructing an instance of this class in the addon initializer such that the <code>v8::Persistent<v8::Object></code> is set to the <code>exports</code> object.</li> <li>storing the instance of the class in a <code>v8::External</code>, and</li> <li>passing the <code>v8::External</code> to all methods exposed to JavaScript by passing it to the <code>v8::FunctionTemplate</code> constructor which creates the native-backed JavaScript functions. The <code>v8::FunctionTemplate</code> constructor's third parameter accepts the <code>v8::External</code>.</li> </ul> <p>This will ensure that the per-addon-instance data reaches each binding that can be called from JavaScript. The per-addon-instance data must also be passed into any asynchronous callbacks the addon may create.</p> <p>The following example illustrates the implementation of a context-aware addon:</p> <pre><code class="language-cpp">#include <node.h> using namespace v8; class AddonData { public: AddonData(Isolate* isolate, Local<Object> exports): call_count(0) { // Link the existence of this object instance to the existence of exports. exports_.Reset(isolate, exports); exports_.SetWeak(this, DeleteMe, WeakCallbackType::kParameter); } ~AddonData() { if (!exports_.IsEmpty()) { // Reset the reference to avoid leaking data. exports_.ClearWeak(); exports_.Reset(); } } // Per-addon data. int call_count; private: // Method to call when "exports" is about to be garbage-collected. static void DeleteMe(const WeakCallbackInfo<AddonData>& info) { delete info.GetParameter(); } // Weak handle to the "exports" object. An instance of this class will be // destroyed along with the exports object to which it is weakly bound. v8::Persistent<v8::Object> exports_; }; static void Method(const v8::FunctionCallbackInfo<v8::Value>& info) { // Retrieve the per-addon-instance data. AddonData* data = reinterpret_cast<AddonData*>(info.Data().As<External>()->Value()); data->call_count++; info.GetReturnValue().Set((double)data->call_count); } // Initialize this addon to be context-aware. NODE_MODULE_INIT(/* exports, module, context */) { Isolate* isolate = context->GetIsolate(); // Create a new instance of AddonData for this instance of the addon. AddonData* data = new AddonData(isolate, exports); // Wrap the data in a v8::External so we can pass it to the method we expose. Local<External> external = External::New(isolate, data); // Expose the method "Method" to JavaScript, and make sure it receives the // per-addon-instance data we created above by passing `external` as the // third parameter to the FunctionTemplate constructor. exports->Set(context, String::NewFromUtf8(isolate, "method", NewStringType::kNormal) .ToLocalChecked(), FunctionTemplate::New(isolate, Method, external) ->GetFunction(context).ToLocalChecked()).FromJust(); } </code></pre> <h3>Building<span><a class="mark" href="#addons_building" id="addons_building">#</a></span></h3> <p>Once the source code has been written, it must be compiled into the binary <code>addon.node</code> file. To do so, create a file called <code>binding.gyp</code> in the top-level of the project describing the build configuration of the module using a JSON-like format. This file is used by <a href="https://github.com/nodejs/node-gyp">node-gyp</a>, a tool written specifically to compile Node.js Addons.</p> <pre><code class="language-json">{ "targets": [ { "target_name": "addon", "sources": [ "hello.cc" ] } ] } </code></pre> <p>A version of the <code>node-gyp</code> utility is bundled and distributed with Node.js as part of <code>npm</code>. This version is not made directly available for developers to use and is intended only to support the ability to use the <code>npm install</code> command to compile and install Addons. Developers who wish to use <code>node-gyp</code> directly can install it using the command <code>npm install -g node-gyp</code>. See the <code>node-gyp</code> <a href="https://github.com/nodejs/node-gyp#installation">installation instructions</a> for more information, including platform-specific requirements.</p> <p>Once the <code>binding.gyp</code> file has been created, use <code>node-gyp configure</code> to generate the appropriate project build files for the current platform. This will generate either a <code>Makefile</code> (on Unix platforms) or a <code>vcxproj</code> file (on Windows) in the <code>build/</code> directory.</p> <p>Next, invoke the <code>node-gyp build</code> command to generate the compiled <code>addon.node</code> file. This will be put into the <code>build/Release/</code> directory.</p> <p>When using <code>npm install</code> to install a Node.js Addon, npm uses its own bundled version of <code>node-gyp</code> to perform this same set of actions, generating a compiled version of the Addon for the user's platform on demand.</p> <p>Once built, the binary Addon can be used from within Node.js by pointing <a href="#modules_require"><code>require()</code></a> to the built <code>addon.node</code> module:</p> <pre><code class="language-js">// hello.js const addon = require('./build/Release/addon'); console.log(addon.hello()); // Prints: 'world' </code></pre> <p>Please see the examples below for further information or <a href="https://github.com/arturadib/node-qt">https://github.com/arturadib/node-qt</a> for an example in production.</p> <p>Because the exact path to the compiled Addon binary can vary depending on how it is compiled (i.e. sometimes it may be in <code>./build/Debug/</code>), Addons can use the <a href="https://github.com/TooTallNate/node-bindings">bindings</a> package to load the compiled module.</p> <p>Note that while the <code>bindings</code> package implementation is more sophisticated in how it locates Addon modules, it is essentially using a try-catch pattern similar to:</p> <pre><code class="language-js">try { return require('./build/Release/addon.node'); } catch (err) { return require('./build/Debug/addon.node'); } </code></pre> <h3>Linking to Node.js' own dependencies<span><a class="mark" href="#addons_linking_to_node_js_own_dependencies" id="addons_linking_to_node_js_own_dependencies">#</a></span></h3> <p>Node.js uses a number of statically linked libraries such as V8, libuv and OpenSSL. All Addons are required to link to V8 and may link to any of the other dependencies as well. Typically, this is as simple as including the appropriate <code>#include <...></code> statements (e.g. <code>#include <v8.h></code>) and <code>node-gyp</code> will locate the appropriate headers automatically. However, there are a few caveats to be aware of:</p> <ul> <li> <p>When <code>node-gyp</code> runs, it will detect the specific release version of Node.js and download either the full source tarball or just the headers. If the full source is downloaded, Addons will have complete access to the full set of Node.js dependencies. However, if only the Node.js headers are downloaded, then only the symbols exported by Node.js will be available.</p> </li> <li> <p><code>node-gyp</code> can be run using the <code>--nodedir</code> flag pointing at a local Node.js source image. Using this option, the Addon will have access to the full set of dependencies.</p> </li> </ul> <h3>Loading Addons using require()<span><a class="mark" href="#addons_loading_addons_using_require" id="addons_loading_addons_using_require">#</a></span></h3> <p>The filename extension of the compiled Addon binary is <code>.node</code> (as opposed to <code>.dll</code> or <code>.so</code>). The <a href="#modules_require"><code>require()</code></a> function is written to look for files with the <code>.node</code> file extension and initialize those as dynamically-linked libraries.</p> <p>When calling <a href="#modules_require"><code>require()</code></a>, the <code>.node</code> extension can usually be omitted and Node.js will still find and initialize the Addon. One caveat, however, is that Node.js will first attempt to locate and load modules or JavaScript files that happen to share the same base name. For instance, if there is a file <code>addon.js</code> in the same directory as the binary <code>addon.node</code>, then <a href="#modules_require"><code>require('addon')</code></a> will give precedence to the <code>addon.js</code> file and load it instead.</p> <h2>Native Abstractions for Node.js<span><a class="mark" href="#addons_native_abstractions_for_node_js" id="addons_native_abstractions_for_node_js">#</a></span></h2> <p>Each of the examples illustrated in this document make direct use of the Node.js and V8 APIs for implementing Addons. It is important to understand that the V8 API can, and has, changed dramatically from one V8 release to the next (and one major Node.js release to the next). With each change, Addons may need to be updated and recompiled in order to continue functioning. The Node.js release schedule is designed to minimize the frequency and impact of such changes but there is little that Node.js can do currently to ensure stability of the V8 APIs.</p> <p>The <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a> (or <code>nan</code>) provide a set of tools that Addon developers are recommended to use to keep compatibility between past and future releases of V8 and Node.js. See the <code>nan</code> <a href="https://github.com/nodejs/nan/tree/master/examples/">examples</a> for an illustration of how it can be used.</p> <h2>N-API<span><a class="mark" href="#addons_n_api" id="addons_n_api">#</a></span></h2> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>N-API is an API for building native Addons. It is independent from the underlying JavaScript runtime (e.g. V8) and is maintained as part of Node.js itself. This API will be Application Binary Interface (ABI) stable across versions of Node.js. It is intended to insulate Addons from changes in the underlying JavaScript engine and allow modules compiled for one version to run on later versions of Node.js without recompilation. Addons are built/packaged with the same approach/tools outlined in this document (node-gyp, etc.). The only difference is the set of APIs that are used by the native code. Instead of using the V8 or <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a> APIs, the functions available in the N-API are used.</p> <p>Creating and maintaining an addon that benefits from the ABI stability provided by N-API carries with it certain <a href="#n_api_implications_of_abi_stability">implementation considerations</a>.</p> <p>To use N-API in the above "Hello world" example, replace the content of <code>hello.cc</code> with the following. All other instructions remain the same.</p> <pre><code class="language-cpp">// hello.cc using N-API #include <node_api.h> namespace demo { napi_value Method(napi_env env, napi_callback_info args) { napi_value greeting; napi_status status; status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting); if (status != napi_ok) return nullptr; return greeting; } napi_value init(napi_env env, napi_value exports) { napi_status status; napi_value fn; status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn); if (status != napi_ok) return nullptr; status = napi_set_named_property(env, exports, "hello", fn); if (status != napi_ok) return nullptr; return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, init) } // namespace demo </code></pre> <p>The functions available and how to use them are documented in the section titled <a href="n-api.html">C/C++ Addons - N-API</a>.</p> <h2>Addon examples<span><a class="mark" href="#addons_addon_examples" id="addons_addon_examples">#</a></span></h2> <p>Following are some example Addons intended to help developers get started. The examples make use of the V8 APIs. Refer to the online <a href="https://v8docs.nodesource.com/">V8 reference</a> for help with the various V8 calls, and V8's <a href="https://github.com/v8/v8/wiki/Embedder's%20Guide">Embedder's Guide</a> for an explanation of several concepts used such as handles, scopes, function templates, etc.</p> <p>Each of these examples using the following <code>binding.gyp</code> file:</p> <pre><code class="language-json">{ "targets": [ { "target_name": "addon", "sources": [ "addon.cc" ] } ] } </code></pre> <p>In cases where there is more than one <code>.cc</code> file, simply add the additional filename to the <code>sources</code> array:</p> <pre><code class="language-json">"sources": ["addon.cc", "myexample.cc"] </code></pre> <p>Once the <code>binding.gyp</code> file is ready, the example Addons can be configured and built using <code>node-gyp</code>:</p> <pre><code class="language-console">$ node-gyp configure build </code></pre> <h3>Function arguments<span><a class="mark" href="#addons_function_arguments" id="addons_function_arguments">#</a></span></h3> <p>Addons will typically expose objects and functions that can be accessed from JavaScript running within Node.js. When functions are invoked from JavaScript, the input arguments and return value must be mapped to and from the C/C++ code.</p> <p>The following example illustrates how to read function arguments passed from JavaScript and how to return a result:</p> <pre><code class="language-cpp">// addon.cc #include <node.h> namespace demo { using v8::Exception; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Number; using v8::Object; using v8::String; using v8::Value; // This is the implementation of the "add" method // Input arguments are passed using the // const FunctionCallbackInfo<Value>& args struct void Add(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); // Check the number of arguments passed. if (args.Length() < 2) { // Throw an Error that is passed back to JavaScript isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Wrong number of arguments", NewStringType::kNormal).ToLocalChecked())); return; } // Check the argument types if (!args[0]->IsNumber() || !args[1]->IsNumber()) { isolate->ThrowException(Exception::TypeError( String::NewFromUtf8(isolate, "Wrong arguments", NewStringType::kNormal).ToLocalChecked())); return; } // Perform the operation double value = args[0].As<Number>()->Value() + args[1].As<Number>()->Value(); Local<Number> num = Number::New(isolate, value); // Set the return value (using the passed in // FunctionCallbackInfo<Value>&) args.GetReturnValue().Set(num); } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "add", Add); } NODE_MODULE(NODE_GYP_MODULE_NAME, Init) } // namespace demo </code></pre> <p>Once compiled, the example Addon can be required and used from within Node.js:</p> <pre><code class="language-js">// test.js const addon = require('./build/Release/addon'); console.log('This should be eight:', addon.add(3, 5)); </code></pre> <h3>Callbacks<span><a class="mark" href="#addons_callbacks" id="addons_callbacks">#</a></span></h3> <p>It is common practice within Addons to pass JavaScript functions to a C++ function and execute them from there. The following example illustrates how to invoke such callbacks:</p> <pre><code class="language-cpp">// addon.cc #include <node.h> namespace demo { using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Null; using v8::Object; using v8::String; using v8::Value; void RunCallback(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Context> context = isolate->GetCurrentContext(); Local<Function> cb = Local<Function>::Cast(args[0]); const unsigned argc = 1; Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world", NewStringType::kNormal).ToLocalChecked() }; cb->Call(context, Null(isolate), argc, argv).ToLocalChecked(); } void Init(Local<Object> exports, Local<Object> module) { NODE_SET_METHOD(module, "exports", RunCallback); } NODE_MODULE(NODE_GYP_MODULE_NAME, Init) } // namespace demo </code></pre> <p>Note that this example uses a two-argument form of <code>Init()</code> that receives the full <code>module</code> object as the second argument. This allows the Addon to completely overwrite <code>exports</code> with a single function instead of adding the function as a property of <code>exports</code>.</p> <p>To test it, run the following JavaScript:</p> <pre><code class="language-js">// test.js const addon = require('./build/Release/addon'); addon((msg) => { console.log(msg); // Prints: 'hello world' }); </code></pre> <p>Note that, in this example, the callback function is invoked synchronously.</p> <h3>Object factory<span><a class="mark" href="#addons_object_factory" id="addons_object_factory">#</a></span></h3> <p>Addons can create and return new objects from within a C++ function as illustrated in the following example. An object is created and returned with a property <code>msg</code> that echoes the string passed to <code>createObject()</code>:</p> <pre><code class="language-cpp">// addon.cc #include <node.h> namespace demo { using v8::Context; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Object; using v8::String; using v8::Value; void CreateObject(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Context> context = isolate->GetCurrentContext(); Local<Object> obj = Object::New(isolate); obj->Set(context, String::NewFromUtf8(isolate, "msg", NewStringType::kNormal).ToLocalChecked(), args[0]->ToString(context).ToLocalChecked()) .FromJust(); args.GetReturnValue().Set(obj); } void Init(Local<Object> exports, Local<Object> module) { NODE_SET_METHOD(module, "exports", CreateObject); } NODE_MODULE(NODE_GYP_MODULE_NAME, Init) } // namespace demo </code></pre> <p>To test it in JavaScript:</p> <pre><code class="language-js">// test.js const addon = require('./build/Release/addon'); const obj1 = addon('hello'); const obj2 = addon('world'); console.log(obj1.msg, obj2.msg); // Prints: 'hello world' </code></pre> <h3>Function factory<span><a class="mark" href="#addons_function_factory" id="addons_function_factory">#</a></span></h3> <p>Another common scenario is creating JavaScript functions that wrap C++ functions and returning those back to JavaScript:</p> <pre><code class="language-cpp">// addon.cc #include <node.h> namespace demo { using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Object; using v8::String; using v8::Value; void MyFunction(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); args.GetReturnValue().Set(String::NewFromUtf8( isolate, "hello world", NewStringType::kNormal).ToLocalChecked()); } void CreateFunction(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Context> context = isolate->GetCurrentContext(); Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction); Local<Function> fn = tpl->GetFunction(context).ToLocalChecked(); // omit this to make it anonymous fn->SetName(String::NewFromUtf8( isolate, "theFunction", NewStringType::kNormal).ToLocalChecked()); args.GetReturnValue().Set(fn); } void Init(Local<Object> exports, Local<Object> module) { NODE_SET_METHOD(module, "exports", CreateFunction); } NODE_MODULE(NODE_GYP_MODULE_NAME, Init) } // namespace demo </code></pre> <p>To test:</p> <pre><code class="language-js">// test.js const addon = require('./build/Release/addon'); const fn = addon(); console.log(fn()); // Prints: 'hello world' </code></pre> <h3>Wrapping C++ objects<span><a class="mark" href="#addons_wrapping_c_objects" id="addons_wrapping_c_objects">#</a></span></h3> <p>It is also possible to wrap C++ objects/classes in a way that allows new instances to be created using the JavaScript <code>new</code> operator:</p> <pre><code class="language-cpp">// addon.cc #include <node.h> #include "myobject.h" namespace demo { using v8::Local; using v8::Object; void InitAll(Local<Object> exports) { MyObject::Init(exports); } NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll) } // namespace demo </code></pre> <p>Then, in <code>myobject.h</code>, the wrapper class inherits from <code>node::ObjectWrap</code>:</p> <pre><code class="language-cpp">// myobject.h #ifndef MYOBJECT_H #define MYOBJECT_H #include <node.h> #include <node_object_wrap.h> namespace demo { class MyObject : public node::ObjectWrap { public: static void Init(v8::Local<v8::Object> exports); private: explicit MyObject(double value = 0); ~MyObject(); static void New(const v8::FunctionCallbackInfo<v8::Value>& args); static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args); static v8::Persistent<v8::Function> constructor; double value_; }; } // namespace demo #endif </code></pre> <p>In <code>myobject.cc</code>, implement the various methods that are to be exposed. Below, the method <code>plusOne()</code> is exposed by adding it to the constructor's prototype:</p> <pre><code class="language-cpp">// myobject.cc #include "myobject.h" namespace demo { using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Number; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; Persistent<Function> MyObject::constructor; MyObject::MyObject(double value) : value_(value) { } MyObject::~MyObject() { } void MyObject::Init(Local<Object> exports) { Isolate* isolate = exports->GetIsolate(); // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(String::NewFromUtf8( isolate, "MyObject", NewStringType::kNormal).ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne); Local<Context> context = isolate->GetCurrentContext(); constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked()); exports->Set(context, String::NewFromUtf8( isolate, "MyObject", NewStringType::kNormal).ToLocalChecked(), tpl->GetFunction(context).ToLocalChecked()).FromJust(); } void MyObject::New(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Context> context = isolate->GetCurrentContext(); if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(context).FromMaybe(0); MyObject* obj = new MyObject(value); obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = Local<Function>::New(isolate, constructor); Local<Object> result = cons->NewInstance(context, argc, argv).ToLocalChecked(); args.GetReturnValue().Set(result); } } void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder()); obj->value_ += 1; args.GetReturnValue().Set(Number::New(isolate, obj->value_)); } } // namespace demo </code></pre> <p>To build this example, the <code>myobject.cc</code> file must be added to the <code>binding.gyp</code>:</p> <pre><code class="language-json">{ "targets": [ { "target_name": "addon", "sources": [ "addon.cc", "myobject.cc" ] } ] } </code></pre> <p>Test it with:</p> <pre><code class="language-js">// test.js const addon = require('./build/Release/addon'); const obj = new addon.MyObject(10); console.log(obj.plusOne()); // Prints: 11 console.log(obj.plusOne()); // Prints: 12 console.log(obj.plusOne()); // Prints: 13 </code></pre> <p>The destructor for a wrapper object will run when the object is garbage-collected. For destructor testing, there are command-line flags that can be used to make it possible to force garbage collection. These flags are provided by the underlying V8 JavaScript engine. They are subject to change or removal at any time. They are not documented by Node.js or V8, and they should never be used outside of testing.</p> <h3>Factory of wrapped objects<span><a class="mark" href="#addons_factory_of_wrapped_objects" id="addons_factory_of_wrapped_objects">#</a></span></h3> <p>Alternatively, it is possible to use a factory pattern to avoid explicitly creating object instances using the JavaScript <code>new</code> operator:</p> <pre><code class="language-js">const obj = addon.createObject(); // instead of: // const obj = new addon.Object(); </code></pre> <p>First, the <code>createObject()</code> method is implemented in <code>addon.cc</code>:</p> <pre><code class="language-cpp">// addon.cc #include <node.h> #include "myobject.h" namespace demo { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; void CreateObject(const FunctionCallbackInfo<Value>& args) { MyObject::NewInstance(args); } void InitAll(Local<Object> exports, Local<Object> module) { MyObject::Init(exports->GetIsolate()); NODE_SET_METHOD(module, "exports", CreateObject); } NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll) } // namespace demo </code></pre> <p>In <code>myobject.h</code>, the static method <code>NewInstance()</code> is added to handle instantiating the object. This method takes the place of using <code>new</code> in JavaScript:</p> <pre><code class="language-cpp">// myobject.h #ifndef MYOBJECT_H #define MYOBJECT_H #include <node.h> #include <node_object_wrap.h> namespace demo { class MyObject : public node::ObjectWrap { public: static void Init(v8::Isolate* isolate); static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args); private: explicit MyObject(double value = 0); ~MyObject(); static void New(const v8::FunctionCallbackInfo<v8::Value>& args); static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args); static v8::Persistent<v8::Function> constructor; double value_; }; } // namespace demo #endif </code></pre> <p>The implementation in <code>myobject.cc</code> is similar to the previous example:</p> <pre><code class="language-cpp">// myobject.cc #include <node.h> #include "myobject.h" namespace demo { using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Number; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; Persistent<Function> MyObject::constructor; MyObject::MyObject(double value) : value_(value) { } MyObject::~MyObject() { } void MyObject::Init(Isolate* isolate) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(String::NewFromUtf8( isolate, "MyObject", NewStringType::kNormal).ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne); Local<Context> context = isolate->GetCurrentContext(); constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked()); } void MyObject::New(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Context> context = isolate->GetCurrentContext(); if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(context).FromMaybe(0); MyObject* obj = new MyObject(value); obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = Local<Function>::New(isolate, constructor); Local<Object> instance = cons->NewInstance(context, argc, argv).ToLocalChecked(); args.GetReturnValue().Set(instance); } } void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); const unsigned argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = Local<Function>::New(isolate, constructor); Local<Context> context = isolate->GetCurrentContext(); Local<Object> instance = cons->NewInstance(context, argc, argv).ToLocalChecked(); args.GetReturnValue().Set(instance); } void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder()); obj->value_ += 1; args.GetReturnValue().Set(Number::New(isolate, obj->value_)); } } // namespace demo </code></pre> <p>Once again, to build this example, the <code>myobject.cc</code> file must be added to the <code>binding.gyp</code>:</p> <pre><code class="language-json">{ "targets": [ { "target_name": "addon", "sources": [ "addon.cc", "myobject.cc" ] } ] } </code></pre> <p>Test it with:</p> <pre><code class="language-js">// test.js const createObject = require('./build/Release/addon'); const obj = createObject(10); console.log(obj.plusOne()); // Prints: 11 console.log(obj.plusOne()); // Prints: 12 console.log(obj.plusOne()); // Prints: 13 const obj2 = createObject(20); console.log(obj2.plusOne()); // Prints: 21 console.log(obj2.plusOne()); // Prints: 22 console.log(obj2.plusOne()); // Prints: 23 </code></pre> <h3>Passing wrapped objects around<span><a class="mark" href="#addons_passing_wrapped_objects_around" id="addons_passing_wrapped_objects_around">#</a></span></h3> <p>In addition to wrapping and returning C++ objects, it is possible to pass wrapped objects around by unwrapping them with the Node.js helper function <code>node::ObjectWrap::Unwrap</code>. The following examples shows a function <code>add()</code> that can take two <code>MyObject</code> objects as input arguments:</p> <pre><code class="language-cpp">// addon.cc #include <node.h> #include <node_object_wrap.h> #include "myobject.h" namespace demo { using v8::Context; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Number; using v8::Object; using v8::String; using v8::Value; void CreateObject(const FunctionCallbackInfo<Value>& args) { MyObject::NewInstance(args); } void Add(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Context> context = isolate->GetCurrentContext(); MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>( args[0]->ToObject(context).ToLocalChecked()); MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>( args[1]->ToObject(context).ToLocalChecked()); double sum = obj1->value() + obj2->value(); args.GetReturnValue().Set(Number::New(isolate, sum)); } void InitAll(Local<Object> exports) { MyObject::Init(exports->GetIsolate()); NODE_SET_METHOD(exports, "createObject", CreateObject); NODE_SET_METHOD(exports, "add", Add); } NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll) } // namespace demo </code></pre> <p>In <code>myobject.h</code>, a new public method is added to allow access to private values after unwrapping the object.</p> <pre><code class="language-cpp">// myobject.h #ifndef MYOBJECT_H #define MYOBJECT_H #include <node.h> #include <node_object_wrap.h> namespace demo { class MyObject : public node::ObjectWrap { public: static void Init(v8::Isolate* isolate); static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args); inline double value() const { return value_; } private: explicit MyObject(double value = 0); ~MyObject(); static void New(const v8::FunctionCallbackInfo<v8::Value>& args); static v8::Persistent<v8::Function> constructor; double value_; }; } // namespace demo #endif </code></pre> <p>The implementation of <code>myobject.cc</code> is similar to before:</p> <pre><code class="language-cpp">// myobject.cc #include <node.h> #include "myobject.h" namespace demo { using v8::Context; using v8::Function; using v8::FunctionCallbackInfo; using v8::FunctionTemplate; using v8::Isolate; using v8::Local; using v8::NewStringType; using v8::Object; using v8::Persistent; using v8::String; using v8::Value; Persistent<Function> MyObject::constructor; MyObject::MyObject(double value) : value_(value) { } MyObject::~MyObject() { } void MyObject::Init(Isolate* isolate) { // Prepare constructor template Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New); tpl->SetClassName(String::NewFromUtf8( isolate, "MyObject", NewStringType::kNormal).ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Local<Context> context = isolate->GetCurrentContext(); constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked()); } void MyObject::New(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); Local<Context> context = isolate->GetCurrentContext(); if (args.IsConstructCall()) { // Invoked as constructor: `new MyObject(...)` double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue(context).FromMaybe(0); MyObject* obj = new MyObject(value); obj->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } else { // Invoked as plain function `MyObject(...)`, turn into construct call. const int argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = Local<Function>::New(isolate, constructor); Local<Object> instance = cons->NewInstance(context, argc, argv).ToLocalChecked(); args.GetReturnValue().Set(instance); } } void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); const unsigned argc = 1; Local<Value> argv[argc] = { args[0] }; Local<Function> cons = Local<Function>::New(isolate, constructor); Local<Context> context = isolate->GetCurrentContext(); Local<Object> instance = cons->NewInstance(context, argc, argv).ToLocalChecked(); args.GetReturnValue().Set(instance); } } // namespace demo </code></pre> <p>Test it with:</p> <pre><code class="language-js">// test.js const addon = require('./build/Release/addon'); const obj1 = addon.createObject(10); const obj2 = addon.createObject(20); const result = addon.add(obj1, obj2); console.log(result); // Prints: 30 </code></pre> <h3>AtExit hooks<span><a class="mark" href="#addons_atexit_hooks" id="addons_atexit_hooks">#</a></span></h3> <p>An <code>AtExit</code> hook is a function that is invoked after the Node.js event loop has ended but before the JavaScript VM is terminated and Node.js shuts down. <code>AtExit</code> hooks are registered using the <code>node::AtExit</code> API.</p> <h4>void AtExit(callback, args)<span><a class="mark" href="#addons_void_atexit_callback_args" id="addons_void_atexit_callback_args">#</a></span></h4> <ul> <li><code>callback</code> <span class="type"><void (*)(void*)></span> A pointer to the function to call at exit.</li> <li><code>args</code> <span class="type"><void*></span> A pointer to pass to the callback at exit.</li> </ul> <p>Registers exit hooks that run after the event loop has ended but before the VM is killed.</p> <p><code>AtExit</code> takes two parameters: a pointer to a callback function to run at exit, and a pointer to untyped context data to be passed to that callback.</p> <p>Callbacks are run in last-in first-out order.</p> <p>The following <code>addon.cc</code> implements <code>AtExit</code>:</p> <pre><code class="language-cpp">// addon.cc #include <assert.h> #include <stdlib.h> #include <node.h> namespace demo { using node::AtExit; using v8::HandleScope; using v8::Isolate; using v8::Local; using v8::Object; static char cookie[] = "yum yum"; static int at_exit_cb1_called = 0; static int at_exit_cb2_called = 0; static void at_exit_cb1(void* arg) { Isolate* isolate = static_cast<Isolate*>(arg); HandleScope scope(isolate); Local<Object> obj = Object::New(isolate); assert(!obj.IsEmpty()); // assert VM is still alive assert(obj->IsObject()); at_exit_cb1_called++; } static void at_exit_cb2(void* arg) { assert(arg == static_cast<void*>(cookie)); at_exit_cb2_called++; } static void sanity_check(void*) { assert(at_exit_cb1_called == 1); assert(at_exit_cb2_called == 2); } void init(Local<Object> exports) { AtExit(at_exit_cb2, cookie); AtExit(at_exit_cb2, cookie); AtExit(at_exit_cb1, exports->GetIsolate()); AtExit(sanity_check); } NODE_MODULE(NODE_GYP_MODULE_NAME, init) } // namespace demo </code></pre> <p>Test in JavaScript by running:</p> <pre><code class="language-js">// test.js require('./build/Release/addon'); </code></pre> <h1>N-API<span><a class="mark" href="#n_api_n_api" id="n_api_n_api">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>N-API (pronounced N as in the letter, followed by API) is an API for building native Addons. It is independent from the underlying JavaScript runtime (ex V8) and is maintained as part of Node.js itself. This API will be Application Binary Interface (ABI) stable across versions of Node.js. It is intended to insulate Addons from changes in the underlying JavaScript engine and allow modules compiled for one major version to run on later major versions of Node.js without recompilation. The <a href="https://nodejs.org/en/docs/guides/abi-stability/">ABI Stability</a> guide provides a more in-depth explanation.</p> <p>Addons are built/packaged with the same approach/tools outlined in the section titled <a href="addons.html">C++ Addons</a>. The only difference is the set of APIs that are used by the native code. Instead of using the V8 or <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a> APIs, the functions available in the N-API are used.</p> <p>APIs exposed by N-API are generally used to create and manipulate JavaScript values. Concepts and operations generally map to ideas specified in the ECMA262 Language Specification. The APIs have the following properties:</p> <ul> <li>All N-API calls return a status code of type <code>napi_status</code>. This status indicates whether the API call succeeded or failed.</li> <li>The API's return value is passed via an out parameter.</li> <li>All JavaScript values are abstracted behind an opaque type named <code>napi_value</code>.</li> <li>In case of an error status code, additional information can be obtained using <code>napi_get_last_error_info</code>. More information can be found in the error handling section <a href="#n_api_error_handling">Error Handling</a>.</li> </ul> <p>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. To support using C++, the project maintains a C++ wrapper module called <a href="https://github.com/nodejs/node-addon-api">node-addon-api</a>. This wrapper provides an inlineable C++ API. Binaries built with <code>node-addon-api</code> will depend on the symbols for the N-API C-based functions exported by Node.js. <code>node-addon-api</code> is a more efficient way to write code that calls N-API. Take, for example, the following <code>node-addon-api</code> code. The first section shows the <code>node-addon-api</code> code and the second section shows what actually gets used in the addon.</p> <pre><code class="language-C++">Object obj = Object::New(env); obj["foo"] = String::New(env, "bar"); </code></pre> <pre><code class="language-C++">napi_status status; napi_value object, string; status = napi_create_object(env, &object); if (status != napi_ok) { napi_throw_error(env, ...); return; } status = napi_create_string_utf8(env, "bar", NAPI_AUTO_LENGTH, &string); if (status != napi_ok) { napi_throw_error(env, ...); return; } status = napi_set_named_property(env, object, "foo", string); if (status != napi_ok) { napi_throw_error(env, ...); return; } </code></pre> <p>The end result is that the addon only uses the exported C APIs. As a result, it still gets the benefits of the ABI stability provided by the C API.</p> <p>When using <code>node-addon-api</code> instead of the C APIs, start with the API <a href="https://github.com/nodejs/node-addon-api#api-documentation">docs</a> for <code>node-addon-api</code>.</p> <h2>Implications of ABI Stability<span><a class="mark" href="#n_api_implications_of_abi_stability" id="n_api_implications_of_abi_stability">#</a></span></h2> <p>Although N-API provides an ABI stability guarantee, other parts of Node.js do not, and any external libraries used from the addon may not. In particular, none of the following APIs provide an ABI stability guarantee across major versions:</p> <ul> <li> <p>the Node.js C++ APIs available via any of</p> <pre><code class="language-C++">#include <node.h> #include <node_buffer.h> #include <node_version.h> #include <node_object_wrap.h> </code></pre> </li> <li> <p>the libuv APIs which are also included with Node.js and available via</p> <pre><code class="language-C++">#include <uv.h> </code></pre> </li> <li> <p>the V8 API available via</p> <pre><code class="language-C++">#include <v8.h> </code></pre> </li> </ul> <p>Thus, for an addon to remain ABI-compatible across Node.js major versions, it must make use exclusively of N-API by restricting itself to using</p> <pre><code class="language-C">#include <node_api.h> </code></pre> <p>and by checking, for all external libraries that it uses, that the external library makes ABI stability guarantees similar to N-API.</p> <h2>Usage<span><a class="mark" href="#n_api_usage" id="n_api_usage">#</a></span></h2> <p>In order to use the N-API functions, include the file <a href="https://github.com/nodejs/node/blob/master/src/node_api.h"><code>node_api.h</code></a> which is located in the src directory in the node development tree:</p> <pre><code class="language-C">#include <node_api.h> </code></pre> <p>This will opt into the default <code>NAPI_VERSION</code> for the given release of Node.js. In order to ensure compatibility with specific versions of N-API, the version can be specified explicitly when including the header:</p> <pre><code class="language-C">#define NAPI_VERSION 3 #include <node_api.h> </code></pre> <p>This restricts the N-API surface to just the functionality that was available in the specified (and earlier) versions.</p> <p>Some of the N-API surface is considered experimental and requires explicit opt-in to access those APIs:</p> <pre><code class="language-C">#define NAPI_EXPERIMENTAL #include <node_api.h> </code></pre> <p>In this case the entire API surface, including any experimental APIs, will be available to the module code.</p> <h2>N-API Version Matrix<span><a class="mark" href="#n_api_n_api_version_matrix" id="n_api_n_api_version_matrix">#</a></span></h2> <table><thead><tr><th align="center"></th><th align="center">1</th><th align="center">2</th><th align="center">3</th><th align="center">4</th><th align="center">5</th></tr></thead><tbody><tr><td align="center">v6.x</td><td align="center"></td><td align="center"></td><td align="center">v6.14.2*</td><td align="center"></td><td align="center"></td></tr><tr><td align="center">v8.x</td><td align="center">v8.0.0*</td><td align="center">v8.10.0*</td><td align="center">v8.11.2</td><td align="center"></td><td align="center"></td></tr><tr><td align="center">v9.x</td><td align="center">v9.0.0*</td><td align="center">v9.3.0*</td><td align="center">v9.11.0*</td><td align="center"></td><td align="center"></td></tr><tr><td align="center">v10.x</td><td align="center"></td><td align="center"></td><td align="center">v10.0.0</td><td align="center">v10.16.0</td><td align="center">v10.17.0</td></tr><tr><td align="center">v11.x</td><td align="center"></td><td align="center"></td><td align="center">v11.0.0</td><td align="center">v11.8.0</td><td align="center"></td></tr><tr><td align="center">v12.x</td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center">v12.0.0</td><td align="center"></td></tr><tr><td align="center">v13.x</td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td><td align="center"></td></tr></tbody></table> <p>* Indicates that the N-API version was released as experimental</p> <h2>Environment Life Cycle APIs<span><a class="mark" href="#n_api_environment_life_cycle_apis" id="n_api_environment_life_cycle_apis">#</a></span></h2> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p><a href="https://tc39.es/ecma262/#sec-agents">Section 8.7</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a> defines the concept of an "Agent" as a self-contained environment in which JavaScript code runs. Multiple such Agents may be started and terminated either concurrently or in sequence by the process.</p> <p>A Node.js environment corresponds to an ECMAScript Agent. In the main process, an environment is created at startup, and additional environments can be created on separate threads to serve as <a href="https://nodejs.org/api/worker_threads.html">worker threads</a>. When Node.js is embedded in another application, the main thread of the application may also construct and destroy a Node.js environment multiple times during the life cycle of the application process such that each Node.js environment created by the application may, in turn, during its life cycle create and destroy additional environments as worker threads.</p> <p>From the perspective of a native addon this means that the bindings it provides may be called multiple times, from multiple contexts, and even concurrently from multiple threads.</p> <p>Native addons may need to allocate global state of which they make use during their entire life cycle such that the state must be unique to each instance of the addon.</p> <p>To this env, N-API provides a way to allocate data such that its life cycle is tied to the life cycle of the Agent.</p> <h3>napi_set_instance_data<span><a class="mark" href="#n_api_napi_set_instance_data" id="n_api_napi_set_instance_data">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">napi_status napi_set_instance_data(napi_env env, void* data, napi_finalize finalize_cb, void* finalize_hint); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] data</code>: The data item to make available to bindings of this instance.</li> <li><code>[in] finalize_cb</code>: The function to call when the environment is being torn down. The function receives <code>data</code> so that it might free it.</li> <li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during collection.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API associates <code>data</code> with the currently running Agent. <code>data</code> can later be retrieved using <code>napi_get_instance_data()</code>. Any existing data associated with the currently running Agent which was set by means of a previous call to <code>napi_set_instance_data()</code> will be overwritten. If a <code>finalize_cb</code> was provided by the previous call, it will not be called.</p> <h3>napi_get_instance_data<span><a class="mark" href="#n_api_napi_get_instance_data" id="n_api_napi_get_instance_data">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">napi_status napi_get_instance_data(napi_env env, void** data); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[out] data</code>: The data item that was previously associated with the currently running Agent by a call to <code>napi_set_instance_data()</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API retrieves data that was previously associated with the currently running Agent via <code>napi_set_instance_data()</code>. If no data is set, the call will succeed and <code>data</code> will be set to <code>NULL</code>.</p> <h2>Basic N-API Data Types<span><a class="mark" href="#n_api_basic_n_api_data_types" id="n_api_basic_n_api_data_types">#</a></span></h2> <p>N-API exposes the following fundamental datatypes as abstractions that are consumed by the various APIs. These APIs should be treated as opaque, introspectable only with other N-API calls.</p> <h3>napi_status<span><a class="mark" href="#n_api_napi_status" id="n_api_napi_status">#</a></span></h3> <p>Integral status code indicating the success or failure of a N-API call. Currently, the following status codes are supported.</p> <pre><code class="language-C">typedef enum { napi_ok, napi_invalid_arg, napi_object_expected, napi_string_expected, napi_name_expected, napi_function_expected, napi_number_expected, napi_boolean_expected, napi_array_expected, napi_generic_failure, napi_pending_exception, napi_cancelled, napi_escape_called_twice, napi_handle_scope_mismatch, napi_callback_scope_mismatch, napi_queue_full, napi_closing, napi_bigint_expected, napi_date_expected, napi_arraybuffer_expected, napi_detachable_arraybuffer_expected, } napi_status; </code></pre> <p>If additional information is required upon an API returning a failed status, it can be obtained by calling <code>napi_get_last_error_info</code>.</p> <h3>napi_extended_error_info<span><a class="mark" href="#n_api_napi_extended_error_info" id="n_api_napi_extended_error_info">#</a></span></h3> <pre><code class="language-C">typedef struct { const char* error_message; void* engine_reserved; uint32_t engine_error_code; napi_status error_code; } napi_extended_error_info; </code></pre> <ul> <li><code>error_message</code>: UTF8-encoded string containing a VM-neutral description of the error.</li> <li><code>engine_reserved</code>: Reserved for VM-specific error details. This is currently not implemented for any VM.</li> <li><code>engine_error_code</code>: VM-specific error code. This is currently not implemented for any VM.</li> <li><code>error_code</code>: The N-API status code that originated with the last error.</li> </ul> <p>See the <a href="#n_api_error_handling">Error Handling</a> section for additional information.</p> <h3>napi_env<span><a class="mark" href="#n_api_napi_env" id="n_api_napi_env">#</a></span></h3> <p><code>napi_env</code> is used to represent a context that the underlying N-API implementation can use to persist VM-specific state. This structure is passed to native functions when they're invoked, and it must be passed back when making N-API calls. Specifically, the same <code>napi_env</code> that was passed in when the initial native function was called must be passed to any subsequent nested N-API calls. Caching the <code>napi_env</code> for the purpose of general reuse is not allowed.</p> <h3>napi_value<span><a class="mark" href="#n_api_napi_value" id="n_api_napi_value">#</a></span></h3> <p>This is an opaque pointer that is used to represent a JavaScript value.</p> <h3>napi_threadsafe_function<span><a class="mark" href="#n_api_napi_threadsafe_function" id="n_api_napi_threadsafe_function">#</a></span></h3> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>This is an opaque pointer that represents a JavaScript function which can be called asynchronously from multiple threads via <code>napi_call_threadsafe_function()</code>.</p> <h3>napi_threadsafe_function_release_mode<span><a class="mark" href="#n_api_napi_threadsafe_function_release_mode" id="n_api_napi_threadsafe_function_release_mode">#</a></span></h3> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>A value to be given to <code>napi_release_threadsafe_function()</code> to indicate whether the thread-safe function is to be closed immediately (<code>napi_tsfn_abort</code>) or merely released (<code>napi_tsfn_release</code>) and thus available for subsequent use via <code>napi_acquire_threadsafe_function()</code> and <code>napi_call_threadsafe_function()</code>.</p> <pre><code class="language-C">typedef enum { napi_tsfn_release, napi_tsfn_abort } napi_threadsafe_function_release_mode; </code></pre> <h3>napi_threadsafe_function_call_mode<span><a class="mark" href="#n_api_napi_threadsafe_function_call_mode" id="n_api_napi_threadsafe_function_call_mode">#</a></span></h3> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>A value to be given to <code>napi_call_threadsafe_function()</code> to indicate whether the call should block whenever the queue associated with the thread-safe function is full.</p> <pre><code class="language-C">typedef enum { napi_tsfn_nonblocking, napi_tsfn_blocking } napi_threadsafe_function_call_mode; </code></pre> <h3>N-API Memory Management types<span><a class="mark" href="#n_api_n_api_memory_management_types" id="n_api_n_api_memory_management_types">#</a></span></h3> <h4>napi_handle_scope<span><a class="mark" href="#n_api_napi_handle_scope" id="n_api_napi_handle_scope">#</a></span></h4> <p>This is an abstraction used to control and modify the lifetime of objects created within a particular scope. In general, N-API values are created within the context of a handle scope. When a native method is called from JavaScript, a default handle scope will exist. If the user does not explicitly create a new handle scope, N-API values will be created in the default handle scope. For any invocations of code outside the execution of a native method (for instance, during a libuv callback invocation), the module is required to create a scope before invoking any functions that can result in the creation of JavaScript values.</p> <p>Handle scopes are created using <a href="#n_api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and are destroyed using <a href="#n_api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a>. Closing the scope can indicate to the GC that all <code>napi_value</code>s created during the lifetime of the handle scope are no longer referenced from the current stack frame.</p> <p>For more details, review the <a href="#n_api_object_lifetime_management">Object Lifetime Management</a>.</p> <h4>napi_escapable_handle_scope<span><a class="mark" href="#n_api_napi_escapable_handle_scope" id="n_api_napi_escapable_handle_scope">#</a></span></h4> <p>Escapable handle scopes are a special type of handle scope to return values created within a particular handle scope to a parent scope.</p> <h4>napi_ref<span><a class="mark" href="#n_api_napi_ref" id="n_api_napi_ref">#</a></span></h4> <p>This is the abstraction to use to reference a <code>napi_value</code>. This allows for users to manage the lifetimes of JavaScript values, including defining their minimum lifetimes explicitly.</p> <p>For more details, review the <a href="#n_api_object_lifetime_management">Object Lifetime Management</a>.</p> <h3>N-API Callback types<span><a class="mark" href="#n_api_n_api_callback_types" id="n_api_n_api_callback_types">#</a></span></h3> <h4>napi_callback_info<span><a class="mark" href="#n_api_napi_callback_info" id="n_api_napi_callback_info">#</a></span></h4> <p>Opaque datatype that is passed to a callback function. It can be used for getting additional information about the context in which the callback was invoked.</p> <h4>napi_callback<span><a class="mark" href="#n_api_napi_callback" id="n_api_napi_callback">#</a></span></h4> <p>Function pointer type for user-provided native functions which are to be exposed to JavaScript via N-API. Callback functions should satisfy the following signature:</p> <pre><code class="language-C">typedef napi_value (*napi_callback)(napi_env, napi_callback_info); </code></pre> <h4>napi_finalize<span><a class="mark" href="#n_api_napi_finalize" id="n_api_napi_finalize">#</a></span></h4> <p>Function pointer type for add-on provided functions that allow the user to be notified when externally-owned data is ready to be cleaned up because the object with which it was associated with, has been garbage-collected. The user must provide a function satisfying the following signature which would get called upon the object's collection. Currently, <code>napi_finalize</code> can be used for finding out when objects that have external data are collected.</p> <pre><code class="language-C">typedef void (*napi_finalize)(napi_env env, void* finalize_data, void* finalize_hint); </code></pre> <h4>napi_async_execute_callback<span><a class="mark" href="#n_api_napi_async_execute_callback" id="n_api_napi_async_execute_callback">#</a></span></h4> <p>Function pointer used with functions that support asynchronous operations. Callback functions must statisfy the following signature:</p> <pre><code class="language-C">typedef void (*napi_async_execute_callback)(napi_env env, void* data); </code></pre> <p>Implementations of this type of function should avoid making any N-API calls that could result in the execution of JavaScript or interaction with JavaScript objects. Most often, any code that needs to make N-API calls should be made in <code>napi_async_complete_callback</code> instead.</p> <h4>napi_async_complete_callback<span><a class="mark" href="#n_api_napi_async_complete_callback" id="n_api_napi_async_complete_callback">#</a></span></h4> <p>Function pointer used with functions that support asynchronous operations. Callback functions must statisfy the following signature:</p> <pre><code class="language-C">typedef void (*napi_async_complete_callback)(napi_env env, napi_status status, void* data); </code></pre> <h4>napi_threadsafe_function_call_js<span><a class="mark" href="#n_api_napi_threadsafe_function_call_js" id="n_api_napi_threadsafe_function_call_js">#</a></span></h4> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>Function pointer used with asynchronous thread-safe function calls. The callback will be called on the main thread. Its purpose is to use a data item arriving via the queue from one of the secondary threads to construct the parameters necessary for a call into JavaScript, usually via <code>napi_call_function</code>, and then make the call into JavaScript.</p> <p>The data arriving from the secondary thread via the queue is given in the <code>data</code> parameter and the JavaScript function to call is given in the <code>js_callback</code> parameter.</p> <p>N-API sets up the environment prior to calling this callback, so it is sufficient to call the JavaScript function via <code>napi_call_function</code> rather than via <code>napi_make_callback</code>.</p> <p>Callback functions must satisfy the following signature:</p> <pre><code class="language-C">typedef void (*napi_threadsafe_function_call_js)(napi_env env, napi_value js_callback, void* context, void* data); </code></pre> <ul> <li><code>[in] env</code>: The environment to use for API calls, or <code>NULL</code> if the thread-safe function is being torn down and <code>data</code> may need to be freed.</li> <li><code>[in] js_callback</code>: The JavaScript function to call, or <code>NULL</code> if the thread-safe function is being torn down and <code>data</code> may need to be freed. It may also be <code>NULL</code> if the thread-safe function was created without <code>js_callback</code>.</li> <li><code>[in] context</code>: The optional data with which the thread-safe function was created.</li> <li><code>[in] data</code>: Data created by the secondary thread. It is the responsibility of the callback to convert this native data to JavaScript values (with N-API functions) that can be passed as parameters when <code>js_callback</code> is invoked. This pointer is managed entirely by the threads and this callback. Thus this callback should free the data.</li> </ul> <h2>Error Handling<span><a class="mark" href="#n_api_error_handling" id="n_api_error_handling">#</a></span></h2> <p>N-API uses both return values and JavaScript exceptions for error handling. The following sections explain the approach for each case.</p> <h3>Return values<span><a class="mark" href="#n_api_return_values" id="n_api_return_values">#</a></span></h3> <p>All of the N-API functions share the same error handling pattern. The return type of all API functions is <code>napi_status</code>.</p> <p>The return value will be <code>napi_ok</code> if the request was successful and no uncaught JavaScript exception was thrown. If an error occurred AND an exception was thrown, the <code>napi_status</code> value for the error will be returned. If an exception was thrown, and no error occurred, <code>napi_pending_exception</code> will be returned.</p> <p>In cases where a return value other than <code>napi_ok</code> or <code>napi_pending_exception</code> is returned, <a href="#n_api_napi_is_exception_pending"><code>napi_is_exception_pending</code></a> must be called to check if an exception is pending. See the section on exceptions for more details.</p> <p>The full set of possible <code>napi_status</code> values is defined in <code>napi_api_types.h</code>.</p> <p>The <code>napi_status</code> return value provides a VM-independent representation of the error which occurred. In some cases it is useful to be able to get more detailed information, including a string representing the error as well as VM (engine)-specific information.</p> <p>In order to retrieve this information <a href="#n_api_napi_get_last_error_info"><code>napi_get_last_error_info</code></a> is provided which returns a <code>napi_extended_error_info</code> structure. The format of the <code>napi_extended_error_info</code> structure is as follows:</p> <pre><code class="language-C">typedef struct napi_extended_error_info { const char* error_message; void* engine_reserved; uint32_t engine_error_code; napi_status error_code; }; </code></pre> <ul> <li><code>error_message</code>: Textual representation of the error that occurred.</li> <li><code>engine_reserved</code>: Opaque handle reserved for engine use only.</li> <li><code>engine_error_code</code>: VM specific error code.</li> <li><code>error_code</code>: n-api status code for the last error.</li> </ul> <p><a href="#n_api_napi_get_last_error_info"><code>napi_get_last_error_info</code></a> returns the information for the last N-API call that was made.</p> <p>Do not rely on the content or format of any of the extended information as it is not subject to SemVer and may change at any time. It is intended only for logging purposes.</p> <h4>napi_get_last_error_info<span><a class="mark" href="#n_api_napi_get_last_error_info" id="n_api_napi_get_last_error_info">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_last_error_info(napi_env env, const napi_extended_error_info** result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] result</code>: The <code>napi_extended_error_info</code> structure with more information about the error.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API retrieves a <code>napi_extended_error_info</code> structure with information about the last error that occurred.</p> <p>The content of the <code>napi_extended_error_info</code> returned is only valid up until an n-api function is called on the same <code>env</code>.</p> <p>Do not rely on the content or format of any of the extended information as it is not subject to SemVer and may change at any time. It is intended only for logging purposes.</p> <p>This API can be called even if there is a pending JavaScript exception.</p> <h3>Exceptions<span><a class="mark" href="#n_api_exceptions" id="n_api_exceptions">#</a></span></h3> <p>Any N-API function call may result in a pending JavaScript exception. This is obviously the case for any function that may cause the execution of JavaScript, but N-API specifies that an exception may be pending on return from any of the API functions.</p> <p>If the <code>napi_status</code> returned by a function is <code>napi_ok</code> then no exception is pending and no additional action is required. If the <code>napi_status</code> returned is anything other than <code>napi_ok</code> or <code>napi_pending_exception</code>, in order to try to recover and continue instead of simply returning immediately, <a href="#n_api_napi_is_exception_pending"><code>napi_is_exception_pending</code></a> must be called in order to determine if an exception is pending or not.</p> <p>In many cases when an N-API function is called and an exception is already pending, the function will return immediately with a <code>napi_status</code> of <code>napi_pending_exception</code>. However, this is not the case for all functions. N-API allows a subset of the functions to be called to allow for some minimal cleanup before returning to JavaScript. In that case, <code>napi_status</code> will reflect the status for the function. It will not reflect previous pending exceptions. To avoid confusion, check the error status after every function call.</p> <p>When an exception is pending one of two approaches can be employed.</p> <p>The first approach is to do any appropriate cleanup and then return so that execution will return to JavaScript. As part of the transition back to JavaScript the exception will be thrown at the point in the JavaScript code where the native method was invoked. The behavior of most N-API calls is unspecified while an exception is pending, and many will simply return <code>napi_pending_exception</code>, so it is important to do as little as possible and then return to JavaScript where the exception can be handled.</p> <p>The second approach is to try to handle the exception. There will be cases where the native code can catch the exception, take the appropriate action, and then continue. This is only recommended in specific cases where it is known that the exception can be safely handled. In these cases <a href="#n_api_napi_get_and_clear_last_exception"><code>napi_get_and_clear_last_exception</code></a> can be used to get and clear the exception. On success, result will contain the handle to the last JavaScript <code>Object</code> thrown. If it is determined, after retrieving the exception, the exception cannot be handled after all it can be re-thrown it with <a href="#n_api_napi_throw"><code>napi_throw</code></a> where error is the JavaScript <code>Error</code> object to be thrown.</p> <p>The following utility functions are also available in case native code needs to throw an exception or determine if a <code>napi_value</code> is an instance of a JavaScript <code>Error</code> object: <a href="#n_api_napi_throw_error"><code>napi_throw_error</code></a>, <a href="#n_api_napi_throw_type_error"><code>napi_throw_type_error</code></a>, <a href="#n_api_napi_throw_range_error"><code>napi_throw_range_error</code></a> and <a href="#n_api_napi_is_error"><code>napi_is_error</code></a>.</p> <p>The following utility functions are also available in case native code needs to create an <code>Error</code> object: <a href="#n_api_napi_create_error"><code>napi_create_error</code></a>, <a href="#n_api_napi_create_type_error"><code>napi_create_type_error</code></a>, and <a href="#n_api_napi_create_range_error"><code>napi_create_range_error</code></a>, where result is the <code>napi_value</code> that refers to the newly created JavaScript <code>Error</code> object.</p> <p>The Node.js project is adding error codes to all of the errors generated internally. The goal is for applications to use these error codes for all error checking. The associated error messages will remain, but will only be meant to be used for logging and display with the expectation that the message can change without SemVer applying. In order to support this model with N-API, both in internal functionality and for module specific functionality (as its good practice), the <code>throw_</code> and <code>create_</code> functions take an optional code parameter which is the string for the code to be added to the error object. If the optional parameter is NULL then no code will be associated with the error. If a code is provided, the name associated with the error is also updated to be:</p> <pre><code class="language-text">originalName [code] </code></pre> <p>where <code>originalName</code> is the original name associated with the error and <code>code</code> is the code that was provided. For example, if the code is <code>'ERR_ERROR_1'</code> and a <code>TypeError</code> is being created the name will be:</p> <pre><code class="language-text">TypeError [ERR_ERROR_1] </code></pre> <h4>napi_throw<span><a class="mark" href="#n_api_napi_throw" id="n_api_napi_throw">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] error</code>: The JavaScript value to be thrown.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API throws the JavaScript value provided.</p> <h4>napi_throw_error<span><a class="mark" href="#n_api_napi_throw_error" id="n_api_napi_throw_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_throw_error(napi_env env, const char* code, const char* msg); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] code</code>: Optional error code to be set on the error.</li> <li><code>[in] msg</code>: C string representing the text to be associated with the error.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API throws a JavaScript <code>Error</code> with the text provided.</p> <h4>napi_throw_type_error<span><a class="mark" href="#n_api_napi_throw_type_error" id="n_api_napi_throw_type_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_throw_type_error(napi_env env, const char* code, const char* msg); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] code</code>: Optional error code to be set on the error.</li> <li><code>[in] msg</code>: C string representing the text to be associated with the error.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API throws a JavaScript <code>TypeError</code> with the text provided.</p> <h4>napi_throw_range_error<span><a class="mark" href="#n_api_napi_throw_range_error" id="n_api_napi_throw_range_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_throw_range_error(napi_env env, const char* code, const char* msg); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] code</code>: Optional error code to be set on the error.</li> <li><code>[in] msg</code>: C string representing the text to be associated with the error.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API throws a JavaScript <code>RangeError</code> with the text provided.</p> <h4>napi_is_error<span><a class="mark" href="#n_api_napi_is_error" id="n_api_napi_is_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_is_error(napi_env env, napi_value value, bool* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The <code>napi_value</code> to be checked.</li> <li><code>[out] result</code>: Boolean value that is set to true if <code>napi_value</code> represents an error, false otherwise.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API queries a <code>napi_value</code> to check if it represents an error object.</p> <h4>napi_create_error<span><a class="mark" href="#n_api_napi_create_error" id="n_api_napi_create_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_create_error(napi_env env, napi_value code, napi_value msg, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be associated with the error.</li> <li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>String</code> to be used as the message for the <code>Error</code>.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns a JavaScript <code>Error</code> with the text provided.</p> <h4>napi_create_type_error<span><a class="mark" href="#n_api_napi_create_type_error" id="n_api_napi_create_type_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_create_type_error(napi_env env, napi_value code, napi_value msg, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be associated with the error.</li> <li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>String</code> to be used as the message for the <code>Error</code>.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns a JavaScript <code>TypeError</code> with the text provided.</p> <h4>napi_create_range_error<span><a class="mark" href="#n_api_napi_create_range_error" id="n_api_napi_create_range_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_create_range_error(napi_env env, napi_value code, napi_value msg, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be associated with the error.</li> <li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>String</code> to be used as the message for the <code>Error</code>.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns a JavaScript <code>RangeError</code> with the text provided.</p> <h4>napi_get_and_clear_last_exception<span><a class="mark" href="#n_api_napi_get_and_clear_last_exception" id="n_api_napi_get_and_clear_last_exception">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_and_clear_last_exception(napi_env env, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] result</code>: The exception if one is pending, NULL otherwise.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns true if an exception is pending.</p> <p>This API can be called even if there is a pending JavaScript exception.</p> <h4>napi_is_exception_pending<span><a class="mark" href="#n_api_napi_is_exception_pending" id="n_api_napi_is_exception_pending">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_is_exception_pending(napi_env env, bool* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] result</code>: Boolean value that is set to true if an exception is pending.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns true if an exception is pending.</p> <p>This API can be called even if there is a pending JavaScript exception.</p> <h4>napi_fatal_exception<span><a class="mark" href="#n_api_napi_fatal_exception" id="n_api_napi_fatal_exception">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.10.0</span> <span>N-API version: 3</span> </div> <pre><code class="language-C">napi_status napi_fatal_exception(napi_env env, napi_value err); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] err</code>: The error that is passed to <code>'uncaughtException'</code>.</li> </ul> <p>Trigger an <code>'uncaughtException'</code> in JavaScript. Useful if an async callback throws an exception with no way to recover.</p> <h3>Fatal Errors<span><a class="mark" href="#n_api_fatal_errors" id="n_api_fatal_errors">#</a></span></h3> <p>In the event of an unrecoverable error in a native module, a fatal error can be thrown to immediately terminate the process.</p> <h4>napi_fatal_error<span><a class="mark" href="#n_api_napi_fatal_error" id="n_api_napi_fatal_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.2.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_NO_RETURN void napi_fatal_error(const char* location, size_t location_len, const char* message, size_t message_len); </code></pre> <ul> <li><code>[in] location</code>: Optional location at which the error occurred.</li> <li><code>[in] location_len</code>: The length of the location in bytes, or <code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li> <li><code>[in] message</code>: The message associated with the error.</li> <li><code>[in] message_len</code>: The length of the message in bytes, or <code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li> </ul> <p>The function call does not return, the process will be terminated.</p> <p>This API can be called even if there is a pending JavaScript exception.</p> <h2>Object Lifetime management<span><a class="mark" href="#n_api_object_lifetime_management" id="n_api_object_lifetime_management">#</a></span></h2> <p>As N-API calls are made, handles to objects in the heap for the underlying VM may be returned as <code>napi_values</code>. These handles must hold the objects 'live' until they are no longer required by the native code, otherwise the objects could be collected before the native code was finished using them.</p> <p>As object handles are returned they are associated with a 'scope'. The lifespan for the default scope is tied to the lifespan of the native method call. The result is that, by default, handles remain valid and the objects associated with these handles will be held live for the lifespan of the native method call.</p> <p>In many cases, however, it is necessary that the handles remain valid for either a shorter or longer lifespan than that of the native method. The sections which follow describe the N-API functions that can be used to change the handle lifespan from the default.</p> <h3>Making handle lifespan shorter than that of the native method<span><a class="mark" href="#n_api_making_handle_lifespan_shorter_than_that_of_the_native_method" id="n_api_making_handle_lifespan_shorter_than_that_of_the_native_method">#</a></span></h3> <p>It is often necessary to make the lifespan of handles shorter than the lifespan of a native method. For example, consider a native method that has a loop which iterates through the elements in a large array:</p> <pre><code class="language-C">for (int i = 0; i < 1000000; i++) { napi_value result; napi_status status = napi_get_element(env, object, i, &result); if (status != napi_ok) { break; } // do something with element } </code></pre> <p>This would result in a large number of handles being created, consuming substantial resources. In addition, even though the native code could only use the most recent handle, all of the associated objects would also be kept alive since they all share the same scope.</p> <p>To handle this case, N-API provides the ability to establish a new 'scope' to which newly created handles will be associated. Once those handles are no longer required, the scope can be 'closed' and any handles associated with the scope are invalidated. The methods available to open/close scopes are <a href="#n_api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and <a href="#n_api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a>.</p> <p>N-API only supports a single nested hierarchy of scopes. There is only one active scope at any time, and all new handles will be associated with that scope while it is active. Scopes must be closed in the reverse order from which they are opened. In addition, all scopes created within a native method must be closed before returning from that method.</p> <p>Taking the earlier example, adding calls to <a href="#n_api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and <a href="#n_api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a> would ensure that at most a single handle is valid throughout the execution of the loop:</p> <pre><code class="language-C">for (int i = 0; i < 1000000; i++) { napi_handle_scope scope; napi_status status = napi_open_handle_scope(env, &scope); if (status != napi_ok) { break; } napi_value result; status = napi_get_element(env, object, i, &result); if (status != napi_ok) { break; } // do something with element status = napi_close_handle_scope(env, scope); if (status != napi_ok) { break; } } </code></pre> <p>When nesting scopes, there are cases where a handle from an inner scope needs to live beyond the lifespan of that scope. N-API supports an 'escapable scope' in order to support this case. An escapable scope allows one handle to be 'promoted' so that it 'escapes' the current scope and the lifespan of the handle changes from the current scope to that of the outer scope.</p> <p>The methods available to open/close escapable scopes are <a href="#n_api_napi_open_escapable_handle_scope"><code>napi_open_escapable_handle_scope</code></a> and <a href="#n_api_napi_close_escapable_handle_scope"><code>napi_close_escapable_handle_scope</code></a>.</p> <p>The request to promote a handle is made through <a href="#n_api_napi_escape_handle"><code>napi_escape_handle</code></a> which can only be called once.</p> <h4>napi_open_handle_scope<span><a class="mark" href="#n_api_napi_open_handle_scope" id="n_api_napi_open_handle_scope">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env, napi_handle_scope* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the new scope.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API open a new scope.</p> <h4>napi_close_handle_scope<span><a class="mark" href="#n_api_napi_close_handle_scope" id="n_api_napi_close_handle_scope">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env, napi_handle_scope scope); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] scope</code>: <code>napi_value</code> representing the scope to be closed.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API closes the scope passed in. Scopes must be closed in the reverse order from which they were created.</p> <p>This API can be called even if there is a pending JavaScript exception.</p> <h4>napi_open_escapable_handle_scope<span><a class="mark" href="#n_api_napi_open_escapable_handle_scope" id="n_api_napi_open_escapable_handle_scope">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_open_escapable_handle_scope(napi_env env, napi_handle_scope* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the new scope.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API open a new scope from which one object can be promoted to the outer scope.</p> <h4>napi_close_escapable_handle_scope<span><a class="mark" href="#n_api_napi_close_escapable_handle_scope" id="n_api_napi_close_escapable_handle_scope">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_close_escapable_handle_scope(napi_env env, napi_handle_scope scope); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] scope</code>: <code>napi_value</code> representing the scope to be closed.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API closes the scope passed in. Scopes must be closed in the reverse order from which they were created.</p> <p>This API can be called even if there is a pending JavaScript exception.</p> <h4>napi_escape_handle<span><a class="mark" href="#n_api_napi_escape_handle" id="n_api_napi_escape_handle">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_escape_handle(napi_env env, napi_escapable_handle_scope scope, napi_value escapee, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] scope</code>: <code>napi_value</code> representing the current scope.</li> <li><code>[in] escapee</code>: <code>napi_value</code> representing the JavaScript <code>Object</code> to be escaped.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the handle to the escaped <code>Object</code> in the outer scope.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API promotes the handle to the JavaScript object so that it is valid for the lifetime of the outer scope. It can only be called once per scope. If it is called more than once an error will be returned.</p> <p>This API can be called even if there is a pending JavaScript exception.</p> <h3>References to objects with a lifespan longer than that of the native method<span><a class="mark" href="#n_api_references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method" id="n_api_references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method">#</a></span></h3> <p>In some cases an addon will need to be able to create and reference objects with a lifespan longer than that of a single native method invocation. For example, to create a constructor and later use that constructor in a request to creates instances, it must be possible to reference the constructor object across many different instance creation requests. This would not be possible with a normal handle returned as a <code>napi_value</code> as described in the earlier section. The lifespan of a normal handle is managed by scopes and all scopes must be closed before the end of a native method.</p> <p>N-API provides methods to create persistent references to an object. Each persistent reference has an associated count with a value of 0 or higher. The count determines if the reference will keep the corresponding object live. References with a count of 0 do not prevent the object from being collected and are often called 'weak' references. Any count greater than 0 will prevent the object from being collected.</p> <p>References can be created with an initial reference count. The count can then be modified through <a href="#n_api_napi_reference_ref"><code>napi_reference_ref</code></a> and <a href="#n_api_napi_reference_unref"><code>napi_reference_unref</code></a>. If an object is collected while the count for a reference is 0, all subsequent calls to get the object associated with the reference <a href="#n_api_napi_get_reference_value"><code>napi_get_reference_value</code></a> will return NULL for the returned <code>napi_value</code>. An attempt to call <a href="#n_api_napi_reference_ref"><code>napi_reference_ref</code></a> for a reference whose object has been collected will result in an error.</p> <p>References must be deleted once they are no longer required by the addon. When a reference is deleted it will no longer prevent the corresponding object from being collected. Failure to delete a persistent reference will result in a 'memory leak' with both the native memory for the persistent reference and the corresponding object on the heap being retained forever.</p> <p>There can be multiple persistent references created which refer to the same object, each of which will either keep the object live or not based on its individual count.</p> <h4>napi_create_reference<span><a class="mark" href="#n_api_napi_create_reference" id="n_api_napi_create_reference">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_create_reference(napi_env env, napi_value value, int initial_refcount, napi_ref* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing the <code>Object</code> to which we want a reference.</li> <li><code>[in] initial_refcount</code>: Initial reference count for the new reference.</li> <li><code>[out] result</code>: <code>napi_ref</code> pointing to the new reference.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API create a new reference with the specified reference count to the <code>Object</code> passed in.</p> <h4>napi_delete_reference<span><a class="mark" href="#n_api_napi_delete_reference" id="n_api_napi_delete_reference">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] ref</code>: <code>napi_ref</code> to be deleted.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API deletes the reference passed in.</p> <p>This API can be called even if there is a pending JavaScript exception.</p> <h4>napi_reference_ref<span><a class="mark" href="#n_api_napi_reference_ref" id="n_api_napi_reference_ref">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_reference_ref(napi_env env, napi_ref ref, int* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] ref</code>: <code>napi_ref</code> for which the reference count will be incremented.</li> <li><code>[out] result</code>: The new reference count.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API increments the reference count for the reference passed in and returns the resulting reference count.</p> <h4>napi_reference_unref<span><a class="mark" href="#n_api_napi_reference_unref" id="n_api_napi_reference_unref">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_reference_unref(napi_env env, napi_ref ref, int* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] ref</code>: <code>napi_ref</code> for which the reference count will be decremented.</li> <li><code>[out] result</code>: The new reference count.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API decrements the reference count for the reference passed in and returns the resulting reference count.</p> <h4>napi_get_reference_value<span><a class="mark" href="#n_api_napi_get_reference_value" id="n_api_napi_get_reference_value">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_get_reference_value(napi_env env, napi_ref ref, napi_value* result); </code></pre> <p>the <code>napi_value passed</code> in or out of these methods is a handle to the object to which the reference is related.</p> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] ref</code>: <code>napi_ref</code> for which we requesting the corresponding <code>Object</code>.</li> <li><code>[out] result</code>: The <code>napi_value</code> for the <code>Object</code> referenced by the <code>napi_ref</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>If still valid, this API returns the <code>napi_value</code> representing the JavaScript <code>Object</code> associated with the <code>napi_ref</code>. Otherwise, result will be NULL.</p> <h3>Cleanup on exit of the current Node.js instance<span><a class="mark" href="#n_api_cleanup_on_exit_of_the_current_node_js_instance" id="n_api_cleanup_on_exit_of_the_current_node_js_instance">#</a></span></h3> <p>While a Node.js process typically releases all its resources when exiting, embedders of Node.js, or future Worker support, may require addons to register clean-up hooks that will be run once the current Node.js instance exits.</p> <p>N-API provides functions for registering and un-registering such callbacks. When those callbacks are run, all resources that are being held by the addon should be freed up.</p> <h4>napi_add_env_cleanup_hook<span><a class="mark" href="#n_api_napi_add_env_cleanup_hook" id="n_api_napi_add_env_cleanup_hook">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.2.0</span> <span>N-API version: 3</span> </div> <pre><code class="language-C">NODE_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env, void (*fun)(void* arg), void* arg); </code></pre> <p>Registers <code>fun</code> as a function to be run with the <code>arg</code> parameter once the current Node.js environment exits.</p> <p>A function can safely be specified multiple times with different <code>arg</code> values. In that case, it will be called multiple times as well. Providing the same <code>fun</code> and <code>arg</code> values multiple times is not allowed and will lead the process to abort.</p> <p>The hooks will be called in reverse order, i.e. the most recently added one will be called first.</p> <p>Removing this hook can be done by using <code>napi_remove_env_cleanup_hook</code>. Typically, that happens when the resource for which this hook was added is being torn down anyway.</p> <h4>napi_remove_env_cleanup_hook<span><a class="mark" href="#n_api_napi_remove_env_cleanup_hook" id="n_api_napi_remove_env_cleanup_hook">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.2.0</span> <span>N-API version: 3</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env, void (*fun)(void* arg), void* arg); </code></pre> <p>Unregisters <code>fun</code> as a function to be run with the <code>arg</code> parameter once the current Node.js environment exits. Both the argument and the function value need to be exact matches.</p> <p>The function must have originally been registered with <code>napi_add_env_cleanup_hook</code>, otherwise the process will abort.</p> <h2>Module registration<span><a class="mark" href="#n_api_module_registration" id="n_api_module_registration">#</a></span></h2> <p>N-API modules are registered in a manner similar to other modules except that instead of using the <code>NODE_MODULE</code> macro the following is used:</p> <pre><code class="language-C">NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) </code></pre> <p>The next difference is the signature for the <code>Init</code> method. For a N-API module it is as follows:</p> <pre><code class="language-C">napi_value Init(napi_env env, napi_value exports); </code></pre> <p>The return value from <code>Init</code> is treated as the <code>exports</code> object for the module. The <code>Init</code> method is passed an empty object via the <code>exports</code> parameter as a convenience. If <code>Init</code> returns NULL, the parameter passed as <code>exports</code> is exported by the module. N-API modules cannot modify the <code>module</code> object but can specify anything as the <code>exports</code> property of the module.</p> <p>To add the method <code>hello</code> as a function so that it can be called as a method provided by the addon:</p> <pre><code class="language-C">napi_value Init(napi_env env, napi_value exports) { napi_status status; napi_property_descriptor desc = {"hello", NULL, Method, NULL, NULL, NULL, napi_default, NULL}; status = napi_define_properties(env, exports, 1, &desc); if (status != napi_ok) return NULL; return exports; } </code></pre> <p>To set a function to be returned by the <code>require()</code> for the addon:</p> <pre><code class="language-C">napi_value Init(napi_env env, napi_value exports) { napi_value method; napi_status status; status = napi_create_function(env, "exports", NAPI_AUTO_LENGTH, Method, NULL, &method); if (status != napi_ok) return NULL; return method; } </code></pre> <p>To define a class so that new instances can be created (often used with <a href="#n_api_object_wrap">Object Wrap</a>):</p> <pre><code class="language-C">// NOTE: partial example, not all referenced code is included napi_value Init(napi_env env, napi_value exports) { napi_status status; napi_property_descriptor properties[] = { { "value", NULL, NULL, GetValue, SetValue, NULL, napi_default, NULL }, DECLARE_NAPI_METHOD("plusOne", PlusOne), DECLARE_NAPI_METHOD("multiply", Multiply), }; napi_value cons; status = napi_define_class(env, "MyObject", New, NULL, 3, properties, &cons); if (status != napi_ok) return NULL; status = napi_create_reference(env, cons, 1, &constructor); if (status != napi_ok) return NULL; status = napi_set_named_property(env, exports, "MyObject", cons); if (status != napi_ok) return NULL; return exports; } </code></pre> <p>If the module will be loaded multiple times during the lifetime of the Node.js process, use the <code>NAPI_MODULE_INIT</code> macro to initialize the module:</p> <pre><code class="language-C">NAPI_MODULE_INIT() { napi_value answer; napi_status result; status = napi_create_int64(env, 42, &answer); if (status != napi_ok) return NULL; status = napi_set_named_property(env, exports, "answer", answer); if (status != napi_ok) return NULL; return exports; } </code></pre> <p>This macro includes <code>NAPI_MODULE</code>, and declares an <code>Init</code> function with a special name and with visibility beyond the addon. This will allow Node.js to initialize the module even if it is loaded multiple times.</p> <p>There are a few design considerations when declaring a module that may be loaded multiple times. The documentation of <a href="#addons_context_aware_addons">context-aware addons</a> provides more details.</p> <p>The variables <code>env</code> and <code>exports</code> will be available inside the function body following the macro invocation.</p> <p>For more details on setting properties on objects, see the section on <a href="#n_api_working_with_javascript_properties">Working with JavaScript Properties</a>.</p> <p>For more details on building addon modules in general, refer to the existing API.</p> <h2>Working with JavaScript Values<span><a class="mark" href="#n_api_working_with_javascript_values" id="n_api_working_with_javascript_values">#</a></span></h2> <p>N-API exposes a set of APIs to create all types of JavaScript values. Some of these types are documented under <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Section 6</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p> <p>Fundamentally, these APIs are used to do one of the following: 1. Create a new JavaScript object 2. Convert from a primitive C type to an N-API value 3. Convert from N-API value to a primitive C type 4. Get global instances including <code>undefined</code> and <code>null</code></p> <p>N-API values are represented by the type <code>napi_value</code>. Any N-API call that requires a JavaScript value takes in a <code>napi_value</code>. In some cases, the API does check the type of the <code>napi_value</code> up-front. However, for better performance, it's better for the caller to make sure that the <code>napi_value</code> in question is of the JavaScript type expected by the API.</p> <h3>Enum types<span><a class="mark" href="#n_api_enum_types" id="n_api_enum_types">#</a></span></h3> <h4>napi_key_collection_mode<span><a class="mark" href="#n_api_napi_key_collection_mode" id="n_api_napi_key_collection_mode">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.20.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">typedef enum { napi_key_include_prototypes, napi_key_own_only } napi_key_collection_mode; </code></pre> <p>Describes the <code>Keys/Properties</code> filter enums:</p> <p><code>napi_key_collection_mode</code> limits the range of collected properties.</p> <p><code>napi_key_own_only</code> limits the collected properties to the given object only. <code>napi_key_include_prototypes</code> will include all keys of the objects's prototype chain as well.</p> <h4>napi_key_filter<span><a class="mark" href="#n_api_napi_key_filter" id="n_api_napi_key_filter">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.20.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">typedef enum { napi_key_all_properties = 0, napi_key_writable = 1, napi_key_enumerable = 1 << 1, napi_key_configurable = 1 << 2, napi_key_skip_strings = 1 << 3, napi_key_skip_symbols = 1 << 4 } napi_key_filter; </code></pre> <p>Property filter bits. They can be or'ed to build a composite filter.</p> <h4>napi_key_conversion<span><a class="mark" href="#n_api_napi_key_conversion" id="n_api_napi_key_conversion">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.20.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">typedef enum { napi_key_keep_numbers, napi_key_numbers_to_strings } napi_key_conversion; </code></pre> <p><code>napi_key_numbers_to_strings</code> will convert integer indices to strings. <code>napi_key_keep_numbers</code> will return numbers for integer indices.</p> <h4>napi_valuetype<span><a class="mark" href="#n_api_napi_valuetype" id="n_api_napi_valuetype">#</a></span></h4> <pre><code class="language-C">typedef enum { // ES6 types (corresponds to typeof) napi_undefined, napi_null, napi_boolean, napi_number, napi_string, napi_symbol, napi_object, napi_function, napi_external, napi_bigint, } napi_valuetype; </code></pre> <p>Describes the type of a <code>napi_value</code>. This generally corresponds to the types described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types">Section 6.1</a> of the ECMAScript Language Specification. In addition to types in that section, <code>napi_valuetype</code> can also represent <code>Function</code>s and <code>Object</code>s with external data.</p> <p>A JavaScript value of type <code>napi_external</code> appears in JavaScript as a plain object such that no properties can be set on it, and no prototype.</p> <h4>napi_typedarray_type<span><a class="mark" href="#n_api_napi_typedarray_type" id="n_api_napi_typedarray_type">#</a></span></h4> <pre><code class="language-C">typedef enum { napi_int8_array, napi_uint8_array, napi_uint8_clamped_array, napi_int16_array, napi_uint16_array, napi_int32_array, napi_uint32_array, napi_float32_array, napi_float64_array, napi_bigint64_array, napi_biguint64_array, } napi_typedarray_type; </code></pre> <p>This represents the underlying binary scalar datatype of the <code>TypedArray</code>. Elements of this enum correspond to <a href="https://tc39.github.io/ecma262/#sec-typedarray-objects">Section 22.2</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p> <h3>Object Creation Functions<span><a class="mark" href="#n_api_object_creation_functions" id="n_api_object_creation_functions">#</a></span></h3> <h4>napi_create_array<span><a class="mark" href="#n_api_napi_create_array" id="n_api_napi_create_array">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_array(napi_env env, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Array</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns an N-API value corresponding to a JavaScript <code>Array</code> type. JavaScript arrays are described in <a href="https://tc39.github.io/ecma262/#sec-array-objects">Section 22.1</a> of the ECMAScript Language Specification.</p> <h4>napi_create_array_with_length<span><a class="mark" href="#n_api_napi_create_array_with_length" id="n_api_napi_create_array_with_length">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_array_with_length(napi_env env, size_t length, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] length</code>: The initial length of the <code>Array</code>.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Array</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns an N-API value corresponding to a JavaScript <code>Array</code> type. The <code>Array</code>'s length property is set to the passed-in length parameter. However, the underlying buffer is not guaranteed to be pre-allocated by the VM when the array is created - that behavior is left to the underlying VM implementation. If the buffer must be a contiguous block of memory that can be directly read and/or written via C, consider using <a href="#n_api_napi_create_external_arraybuffer"><code>napi_create_external_arraybuffer</code></a>.</p> <p>JavaScript arrays are described in <a href="https://tc39.github.io/ecma262/#sec-array-objects">Section 22.1</a> of the ECMAScript Language Specification.</p> <h4>napi_create_arraybuffer<span><a class="mark" href="#n_api_napi_create_arraybuffer" id="n_api_napi_create_arraybuffer">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_arraybuffer(napi_env env, size_t byte_length, void** data, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] length</code>: The length in bytes of the array buffer to create.</li> <li><code>[out] data</code>: Pointer to the underlying byte buffer of the <code>ArrayBuffer</code>.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>ArrayBuffer</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns an N-API value corresponding to a JavaScript <code>ArrayBuffer</code>. <code>ArrayBuffer</code>s are used to represent fixed-length binary data buffers. They are normally used as a backing-buffer for <code>TypedArray</code> objects. The <code>ArrayBuffer</code> allocated will have an underlying byte buffer whose size is determined by the <code>length</code> parameter that's passed in. The underlying buffer is optionally returned back to the caller in case the caller wants to directly manipulate the buffer. This buffer can only be written to directly from native code. To write to this buffer from JavaScript, a typed array or <code>DataView</code> object would need to be created.</p> <p>JavaScript <code>ArrayBuffer</code> objects are described in <a href="https://tc39.github.io/ecma262/#sec-arraybuffer-objects">Section 24.1</a> of the ECMAScript Language Specification.</p> <h4>napi_create_buffer<span><a class="mark" href="#n_api_napi_create_buffer" id="n_api_napi_create_buffer">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_buffer(napi_env env, size_t size, void** data, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] size</code>: Size in bytes of the underlying buffer.</li> <li><code>[out] data</code>: Raw pointer to the underlying buffer.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API allocates a <code>node::Buffer</code> object. While this is still a fully-supported data structure, in most cases using a <code>TypedArray</code> will suffice.</p> <h4>napi_create_buffer_copy<span><a class="mark" href="#n_api_napi_create_buffer_copy" id="n_api_napi_create_buffer_copy">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_buffer_copy(napi_env env, size_t length, const void* data, void** result_data, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] size</code>: Size in bytes of the input buffer (should be the same as the size of the new buffer).</li> <li><code>[in] data</code>: Raw pointer to the underlying buffer to copy from.</li> <li><code>[out] result_data</code>: Pointer to the new <code>Buffer</code>'s underlying data buffer.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API allocates a <code>node::Buffer</code> object and initializes it with data copied from the passed-in buffer. While this is still a fully-supported data structure, in most cases using a <code>TypedArray</code> will suffice.</p> <h4>napi_create_date<span><a class="mark" href="#n_api_napi_create_date" id="n_api_napi_create_date">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.17.0</span> <span>N-API version: 4</span> </div> <pre><code class="language-C">napi_status napi_create_date(napi_env env, double time, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] time</code>: ECMAScript time value in milliseconds since 01 January, 1970 UTC.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Date</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API allocates a JavaScript <code>Date</code> object.</p> <p>JavaScript <code>Date</code> objects are described in <a href="https://tc39.github.io/ecma262/#sec-date-objects">Section 20.3</a> of the ECMAScript Language Specification.</p> <h4>napi_create_external<span><a class="mark" href="#n_api_napi_create_external" id="n_api_napi_create_external">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_external(napi_env env, void* data, napi_finalize finalize_cb, void* finalize_hint, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] data</code>: Raw pointer to the external data.</li> <li><code>[in] finalize_cb</code>: Optional callback to call when the external value is being collected.</li> <li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during collection.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing an external value.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API allocates a JavaScript value with external data attached to it. This is used to pass external data through JavaScript code, so it can be retrieved later by native code. The API allows the caller to pass in a finalize callback, in case the underlying native resource needs to be cleaned up when the external JavaScript value gets collected.</p> <p>The created value is not an object, and therefore does not support additional properties. It is considered a distinct value type: calling <code>napi_typeof()</code> with an external value yields <code>napi_external</code>.</p> <h4>napi_create_external_arraybuffer<span><a class="mark" href="#n_api_napi_create_external_arraybuffer" id="n_api_napi_create_external_arraybuffer">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_external_arraybuffer(napi_env env, void* external_data, size_t byte_length, napi_finalize finalize_cb, void* finalize_hint, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] external_data</code>: Pointer to the underlying byte buffer of the <code>ArrayBuffer</code>.</li> <li><code>[in] byte_length</code>: The length in bytes of the underlying buffer.</li> <li><code>[in] finalize_cb</code>: Optional callback to call when the <code>ArrayBuffer</code> is being collected.</li> <li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during collection.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>ArrayBuffer</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns an N-API value corresponding to a JavaScript <code>ArrayBuffer</code>. The underlying byte buffer of the <code>ArrayBuffer</code> is externally allocated and managed. The caller must ensure that the byte buffer remains valid until the finalize callback is called.</p> <p>JavaScript <code>ArrayBuffer</code>s are described in <a href="https://tc39.github.io/ecma262/#sec-arraybuffer-objects">Section 24.1</a> of the ECMAScript Language Specification.</p> <h4>napi_create_external_buffer<span><a class="mark" href="#n_api_napi_create_external_buffer" id="n_api_napi_create_external_buffer">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_external_buffer(napi_env env, size_t length, void* data, napi_finalize finalize_cb, void* finalize_hint, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] length</code>: Size in bytes of the input buffer (should be the same as the size of the new buffer).</li> <li><code>[in] data</code>: Raw pointer to the underlying buffer to copy from.</li> <li><code>[in] finalize_cb</code>: Optional callback to call when the <code>ArrayBuffer</code> is being collected.</li> <li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during collection.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API allocates a <code>node::Buffer</code> object and initializes it with data backed by the passed in buffer. While this is still a fully-supported data structure, in most cases using a <code>TypedArray</code> will suffice.</p> <p>For Node.js >=4 <code>Buffers</code> are <code>Uint8Array</code>s.</p> <h4>napi_create_object<span><a class="mark" href="#n_api_napi_create_object" id="n_api_napi_create_object">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_object(napi_env env, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Object</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API allocates a default JavaScript <code>Object</code>. It is the equivalent of doing <code>new Object()</code> in JavaScript.</p> <p>The JavaScript <code>Object</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-object-type">Section 6.1.7</a> of the ECMAScript Language Specification.</p> <h4>napi_create_symbol<span><a class="mark" href="#n_api_napi_create_symbol" id="n_api_napi_create_symbol">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_symbol(napi_env env, napi_value description, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] description</code>: Optional <code>napi_value</code> which refers to a JavaScript <code>String</code> to be set as the description for the symbol.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Symbol</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API creates a JavaScript <code>Symbol</code> object from a UTF8-encoded C string.</p> <p>The JavaScript <code>Symbol</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-symbol-objects">Section 19.4</a> of the ECMAScript Language Specification.</p> <h4>napi_create_typedarray<span><a class="mark" href="#n_api_napi_create_typedarray" id="n_api_napi_create_typedarray">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_typedarray(napi_env env, napi_typedarray_type type, size_t length, napi_value arraybuffer, size_t byte_offset, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] type</code>: Scalar datatype of the elements within the <code>TypedArray</code>.</li> <li><code>[in] length</code>: Number of elements in the <code>TypedArray</code>.</li> <li><code>[in] arraybuffer</code>: <code>ArrayBuffer</code> underlying the typed array.</li> <li><code>[in] byte_offset</code>: The byte offset within the <code>ArrayBuffer</code> from which to start projecting the <code>TypedArray</code>.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>TypedArray</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API creates a JavaScript <code>TypedArray</code> object over an existing <code>ArrayBuffer</code>. <code>TypedArray</code> objects provide an array-like view over an underlying data buffer where each element has the same underlying binary scalar datatype.</p> <p>It's required that <code>(length * size_of_element) + byte_offset</code> should be <= the size in bytes of the array passed in. If not, a <code>RangeError</code> exception is raised.</p> <p>JavaScript <code>TypedArray</code> objects are described in <a href="https://tc39.github.io/ecma262/#sec-typedarray-objects">Section 22.2</a> of the ECMAScript Language Specification.</p> <h4>napi_create_dataview<span><a class="mark" href="#n_api_napi_create_dataview" id="n_api_napi_create_dataview">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.3.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_dataview(napi_env env, size_t byte_length, napi_value arraybuffer, size_t byte_offset, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] length</code>: Number of elements in the <code>DataView</code>.</li> <li><code>[in] arraybuffer</code>: <code>ArrayBuffer</code> underlying the <code>DataView</code>.</li> <li><code>[in] byte_offset</code>: The byte offset within the <code>ArrayBuffer</code> from which to start projecting the <code>DataView</code>.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>DataView</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API creates a JavaScript <code>DataView</code> object over an existing <code>ArrayBuffer</code>. <code>DataView</code> objects provide an array-like view over an underlying data buffer, but one which allows items of different size and type in the <code>ArrayBuffer</code>.</p> <p>It is required that <code>byte_length + byte_offset</code> is less than or equal to the size in bytes of the array passed in. If not, a <code>RangeError</code> exception is raised.</p> <p>JavaScript <code>DataView</code> objects are described in <a href="https://tc39.github.io/ecma262/#sec-dataview-objects">Section 24.3</a> of the ECMAScript Language Specification.</p> <h3>Functions to convert from C types to N-API<span><a class="mark" href="#n_api_functions_to_convert_from_c_types_to_n_api" id="n_api_functions_to_convert_from_c_types_to_n_api">#</a></span></h3> <h4>napi_create_int32<span><a class="mark" href="#n_api_napi_create_int32" id="n_api_napi_create_int32">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: Integer value to be represented in JavaScript.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Number</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API is used to convert from the C <code>int32_t</code> type to the JavaScript <code>Number</code> type.</p> <p>The JavaScript <code>Number</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p> <h4>napi_create_uint32<span><a class="mark" href="#n_api_napi_create_uint32" id="n_api_napi_create_uint32">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: Unsigned integer value to be represented in JavaScript.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Number</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API is used to convert from the C <code>uint32_t</code> type to the JavaScript <code>Number</code> type.</p> <p>The JavaScript <code>Number</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p> <h4>napi_create_int64<span><a class="mark" href="#n_api_napi_create_int64" id="n_api_napi_create_int64">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: Integer value to be represented in JavaScript.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Number</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API is used to convert from the C <code>int64_t</code> type to the JavaScript <code>Number</code> type.</p> <p>The JavaScript <code>Number</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification. Note the complete range of <code>int64_t</code> cannot be represented with full precision in JavaScript. Integer values outside the range of <a href="https://tc39.github.io/ecma262/#sec-number.min_safe_integer"><code>Number.MIN_SAFE_INTEGER</code></a> -(2^53 - 1) - <a href="https://tc39.github.io/ecma262/#sec-number.max_safe_integer"><code>Number.MAX_SAFE_INTEGER</code></a> (2^53 - 1) will lose precision.</p> <h4>napi_create_double<span><a class="mark" href="#n_api_napi_create_double" id="n_api_napi_create_double">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_double(napi_env env, double value, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: Double-precision value to be represented in JavaScript.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Number</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API is used to convert from the C <code>double</code> type to the JavaScript <code>Number</code> type.</p> <p>The JavaScript <code>Number</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p> <h4>napi_create_bigint_int64<span><a class="mark" href="#n_api_napi_create_bigint_int64" id="n_api_napi_create_bigint_int64">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.7.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">napi_status napi_create_bigint_int64(napi_env env, int64_t value, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: Integer value to be represented in JavaScript.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API converts the C <code>int64_t</code> type to the JavaScript <code>BigInt</code> type.</p> <h4>napi_create_bigint_uint64<span><a class="mark" href="#n_api_napi_create_bigint_uint64" id="n_api_napi_create_bigint_uint64">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.7.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">napi_status napi_create_bigint_uint64(napi_env env, uint64_t value, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: Unsigned integer value to be represented in JavaScript.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API converts the C <code>uint64_t</code> type to the JavaScript <code>BigInt</code> type.</p> <h4>napi_create_bigint_words<span><a class="mark" href="#n_api_napi_create_bigint_words" id="n_api_napi_create_bigint_words">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.7.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">napi_status napi_create_bigint_words(napi_env env, int sign_bit, size_t word_count, const uint64_t* words, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] sign_bit</code>: Determines if the resulting <code>BigInt</code> will be positive or negative.</li> <li><code>[in] word_count</code>: The length of the <code>words</code> array.</li> <li><code>[in] words</code>: An array of <code>uint64_t</code> little-endian 64-bit words.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API converts an array of unsigned 64-bit words into a single <code>BigInt</code> value.</p> <p>The resulting <code>BigInt</code> is calculated as: (–1)<sup><code>sign_bit</code></sup> (<code>words[0]</code> × (2<sup>64</sup>)<sup>0</sup> + <code>words[1]</code> × (2<sup>64</sup>)<sup>1</sup> + …)</p> <h4>napi_create_string_latin1<span><a class="mark" href="#n_api_napi_create_string_latin1" id="n_api_napi_create_string_latin1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_string_latin1(napi_env env, const char* str, size_t length, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] str</code>: Character buffer representing an ISO-8859-1-encoded string.</li> <li><code>[in] length</code>: The length of the string in bytes, or <code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>String</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API creates a JavaScript <code>String</code> object from an ISO-8859-1-encoded C string. The native string is copied.</p> <p>The JavaScript <code>String</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p> <h4>napi_create_string_utf16<span><a class="mark" href="#n_api_napi_create_string_utf16" id="n_api_napi_create_string_utf16">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_string_utf16(napi_env env, const char16_t* str, size_t length, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] str</code>: Character buffer representing a UTF16-LE-encoded string.</li> <li><code>[in] length</code>: The length of the string in two-byte code units, or <code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>String</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API creates a JavaScript <code>String</code> object from a UTF16-LE-encoded C string. The native string is copied.</p> <p>The JavaScript <code>String</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p> <h4>napi_create_string_utf8<span><a class="mark" href="#n_api_napi_create_string_utf8" id="n_api_napi_create_string_utf8">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_string_utf8(napi_env env, const char* str, size_t length, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] str</code>: Character buffer representing a UTF8-encoded string.</li> <li><code>[in] length</code>: The length of the string in bytes, or <code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>String</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API creates a JavaScript <code>String</code> object from a UTF8-encoded C string. The native string is copied.</p> <p>The JavaScript <code>String</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p> <h3>Functions to convert from N-API to C types<span><a class="mark" href="#n_api_functions_to_convert_from_n_api_to_c_types" id="n_api_functions_to_convert_from_n_api_to_c_types">#</a></span></h3> <h4>napi_get_array_length<span><a class="mark" href="#n_api_napi_get_array_length" id="n_api_napi_get_array_length">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_array_length(napi_env env, napi_value value, uint32_t* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing the JavaScript <code>Array</code> whose length is being queried.</li> <li><code>[out] result</code>: <code>uint32</code> representing length of the array.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns the length of an array.</p> <p><code>Array</code> length is described in <a href="https://tc39.github.io/ecma262/#sec-properties-of-array-instances-length">Section 22.1.4.1</a> of the ECMAScript Language Specification.</p> <h4>napi_get_arraybuffer_info<span><a class="mark" href="#n_api_napi_get_arraybuffer_info" id="n_api_napi_get_arraybuffer_info">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_arraybuffer_info(napi_env env, napi_value arraybuffer, void** data, size_t* byte_length) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] arraybuffer</code>: <code>napi_value</code> representing the <code>ArrayBuffer</code> being queried.</li> <li><code>[out] data</code>: The underlying data buffer of the <code>ArrayBuffer</code>.</li> <li><code>[out] byte_length</code>: Length in bytes of the underlying data buffer.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API is used to retrieve the underlying data buffer of an <code>ArrayBuffer</code> and its length.</p> <p><em>WARNING</em>: Use caution while using this API. The lifetime of the underlying data buffer is managed by the <code>ArrayBuffer</code> even after it's returned. A possible safe way to use this API is in conjunction with <a href="#n_api_napi_create_reference"><code>napi_create_reference</code></a>, which can be used to guarantee control over the lifetime of the <code>ArrayBuffer</code>. It's also safe to use the returned data buffer within the same callback as long as there are no calls to other APIs that might trigger a GC.</p> <h4>napi_get_buffer_info<span><a class="mark" href="#n_api_napi_get_buffer_info" id="n_api_napi_get_buffer_info">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_buffer_info(napi_env env, napi_value value, void** data, size_t* length) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing the <code>node::Buffer</code> being queried.</li> <li><code>[out] data</code>: The underlying data buffer of the <code>node::Buffer</code>.</li> <li><code>[out] length</code>: Length in bytes of the underlying data buffer.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API is used to retrieve the underlying data buffer of a <code>node::Buffer</code> and it's length.</p> <p><em>Warning</em>: Use caution while using this API since the underlying data buffer's lifetime is not guaranteed if it's managed by the VM.</p> <h4>napi_get_prototype<span><a class="mark" href="#n_api_napi_get_prototype" id="n_api_napi_get_prototype">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_prototype(napi_env env, napi_value object, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] object</code>: <code>napi_value</code> representing JavaScript <code>Object</code> whose prototype to return. This returns the equivalent of <code>Object.getPrototypeOf</code> (which is not the same as the function's <code>prototype</code> property).</li> <li><code>[out] result</code>: <code>napi_value</code> representing prototype of the given object.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <h4>napi_get_typedarray_info<span><a class="mark" href="#n_api_napi_get_typedarray_info" id="n_api_napi_get_typedarray_info">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_typedarray_info(napi_env env, napi_value typedarray, napi_typedarray_type* type, size_t* length, void** data, napi_value* arraybuffer, size_t* byte_offset) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] typedarray</code>: <code>napi_value</code> representing the <code>TypedArray</code> whose properties to query.</li> <li><code>[out] type</code>: Scalar datatype of the elements within the <code>TypedArray</code>.</li> <li><code>[out] length</code>: The number of elements in the <code>TypedArray</code>.</li> <li><code>[out] data</code>: The data buffer underlying the <code>TypedArray</code> adjusted by the <code>byte_offset</code> value so that it points to the first element in the <code>TypedArray</code>.</li> <li><code>[out] arraybuffer</code>: The <code>ArrayBuffer</code> underlying the <code>TypedArray</code>.</li> <li><code>[out] byte_offset</code>: The byte offset within the underlying native array at which the first element of the arrays is located. The value for the data parameter has already been adjusted so that data points to the first element in the array. Therefore, the first byte of the native array would be at data - <code>byte_offset</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns various properties of a typed array.</p> <p><em>Warning</em>: Use caution while using this API since the underlying data buffer is managed by the VM.</p> <h4>napi_get_dataview_info<span><a class="mark" href="#n_api_napi_get_dataview_info" id="n_api_napi_get_dataview_info">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.3.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_dataview_info(napi_env env, napi_value dataview, size_t* byte_length, void** data, napi_value* arraybuffer, size_t* byte_offset) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] dataview</code>: <code>napi_value</code> representing the <code>DataView</code> whose properties to query.</li> <li><code>[out] byte_length</code>: <code>Number</code> of bytes in the <code>DataView</code>.</li> <li><code>[out] data</code>: The data buffer underlying the <code>DataView</code>.</li> <li><code>[out] arraybuffer</code>: <code>ArrayBuffer</code> underlying the <code>DataView</code>.</li> <li><code>[out] byte_offset</code>: The byte offset within the data buffer from which to start projecting the <code>DataView</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns various properties of a <code>DataView</code>.</p> <h4>napi_get_date_value<span><a class="mark" href="#n_api_napi_get_date_value" id="n_api_napi_get_date_value">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.17.0</span> <span>N-API version: 4</span> </div> <pre><code class="language-C">napi_status napi_get_date_value(napi_env env, napi_value value, double* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing a JavaScript <code>Date</code>.</li> <li><code>[out] result</code>: Time value as a <code>double</code> represented as milliseconds since midnight at the beginning of 01 January, 1970 UTC.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-date <code>napi_value</code> is passed in it returns <code>napi_date_expected</code>.</p> <p>This API returns the C double primitive of time value for the given JavaScript <code>Date</code>.</p> <h4>napi_get_value_bool<span><a class="mark" href="#n_api_napi_get_value_bool" id="n_api_napi_get_value_bool">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Boolean</code>.</li> <li><code>[out] result</code>: C boolean primitive equivalent of the given JavaScript <code>Boolean</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-boolean <code>napi_value</code> is passed in it returns <code>napi_boolean_expected</code>.</p> <p>This API returns the C boolean primitive equivalent of the given JavaScript <code>Boolean</code>.</p> <h4>napi_get_value_double<span><a class="mark" href="#n_api_napi_get_value_double" id="n_api_napi_get_value_double">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_value_double(napi_env env, napi_value value, double* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Number</code>.</li> <li><code>[out] result</code>: C double primitive equivalent of the given JavaScript <code>Number</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code> is passed in it returns <code>napi_number_expected</code>.</p> <p>This API returns the C double primitive equivalent of the given JavaScript <code>Number</code>.</p> <h4>napi_get_value_bigint_int64<span><a class="mark" href="#n_api_napi_get_value_bigint_int64" id="n_api_napi_get_value_bigint_int64">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.7.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">napi_status napi_get_value_bigint_int64(napi_env env, napi_value value, int64_t* result, bool* lossless); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li> <li><code>[out] result</code>: C <code>int64_t</code> primitive equivalent of the given JavaScript <code>BigInt</code>.</li> <li><code>[out] lossless</code>: Indicates whether the <code>BigInt</code> value was converted losslessly.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>BigInt</code> is passed in it returns <code>napi_bigint_expected</code>.</p> <p>This API returns the C <code>int64_t</code> primitive equivalent of the given JavaScript <code>BigInt</code>. If needed it will truncate the value, setting <code>lossless</code> to <code>false</code>.</p> <h4>napi_get_value_bigint_uint64<span><a class="mark" href="#n_api_napi_get_value_bigint_uint64" id="n_api_napi_get_value_bigint_uint64">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.7.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">napi_status napi_get_value_bigint_uint64(napi_env env, napi_value value, uint64_t* result, bool* lossless); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li> <li><code>[out] result</code>: C <code>uint64_t</code> primitive equivalent of the given JavaScript <code>BigInt</code>.</li> <li><code>[out] lossless</code>: Indicates whether the <code>BigInt</code> value was converted losslessly.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>BigInt</code> is passed in it returns <code>napi_bigint_expected</code>.</p> <p>This API returns the C <code>uint64_t</code> primitive equivalent of the given JavaScript <code>BigInt</code>. If needed it will truncate the value, setting <code>lossless</code> to <code>false</code>.</p> <h4>napi_get_value_bigint_words<span><a class="mark" href="#n_api_napi_get_value_bigint_words" id="n_api_napi_get_value_bigint_words">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.7.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">napi_status napi_get_value_bigint_words(napi_env env, napi_value value, size_t* word_count, int* sign_bit, uint64_t* words); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li> <li><code>[out] sign_bit</code>: Integer representing if the JavaScript <code>BigInt</code> is positive or negative.</li> <li><code>[in/out] word_count</code>: Must be initialized to the length of the <code>words</code> array. Upon return, it will be set to the actual number of words that would be needed to store this <code>BigInt</code>.</li> <li><code>[out] words</code>: Pointer to a pre-allocated 64-bit word array.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API converts a single <code>BigInt</code> value into a sign bit, 64-bit little-endian array, and the number of elements in the array. <code>sign_bit</code> and <code>words</code> may be both set to <code>NULL</code>, in order to get only <code>word_count</code>.</p> <h4>napi_get_value_external<span><a class="mark" href="#n_api_napi_get_value_external" id="n_api_napi_get_value_external">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_value_external(napi_env env, napi_value value, void** result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript external value.</li> <li><code>[out] result</code>: Pointer to the data wrapped by the JavaScript external value.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-external <code>napi_value</code> is passed in it returns <code>napi_invalid_arg</code>.</p> <p>This API retrieves the external data pointer that was previously passed to <code>napi_create_external()</code>.</p> <h4>napi_get_value_int32<span><a class="mark" href="#n_api_napi_get_value_int32" id="n_api_napi_get_value_int32">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_value_int32(napi_env env, napi_value value, int32_t* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Number</code>.</li> <li><code>[out] result</code>: C <code>int32</code> primitive equivalent of the given JavaScript <code>Number</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code> is passed in <code>napi_number_expected</code>.</p> <p>This API returns the C <code>int32</code> primitive equivalent of the given JavaScript <code>Number</code>.</p> <p>If the number exceeds the range of the 32 bit integer, then the result is truncated to the equivalent of the bottom 32 bits. This can result in a large positive number becoming a negative number if the value is > 2^31 -1.</p> <p>Non-finite number values (<code>NaN</code>, <code>+Infinity</code>, or <code>-Infinity</code>) set the result to zero.</p> <h4>napi_get_value_int64<span><a class="mark" href="#n_api_napi_get_value_int64" id="n_api_napi_get_value_int64">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_value_int64(napi_env env, napi_value value, int64_t* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Number</code>.</li> <li><code>[out] result</code>: C <code>int64</code> primitive equivalent of the given JavaScript <code>Number</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code> is passed in it returns <code>napi_number_expected</code>.</p> <p>This API returns the C <code>int64</code> primitive equivalent of the given JavaScript <code>Number</code>.</p> <p><code>Number</code> values outside the range of <a href="https://tc39.github.io/ecma262/#sec-number.min_safe_integer"><code>Number.MIN_SAFE_INTEGER</code></a> -(2^53 - 1) - <a href="https://tc39.github.io/ecma262/#sec-number.max_safe_integer"><code>Number.MAX_SAFE_INTEGER</code></a> (2^53 - 1) will lose precision.</p> <p>Non-finite number values (<code>NaN</code>, <code>+Infinity</code>, or <code>-Infinity</code>) set the result to zero.</p> <h4>napi_get_value_string_latin1<span><a class="mark" href="#n_api_napi_get_value_string_latin1" id="n_api_napi_get_value_string_latin1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_value_string_latin1(napi_env env, napi_value value, char* buf, size_t bufsize, size_t* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li> <li><code>[in] buf</code>: Buffer to write the ISO-8859-1-encoded string into. If NULL is passed in, the length of the string (in bytes) is returned.</li> <li><code>[in] bufsize</code>: Size of the destination buffer. When this value is insufficient, the returned string will be truncated.</li> <li><code>[out] result</code>: Number of bytes copied into the buffer, excluding the null terminator.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>String</code> <code>napi_value</code> is passed in it returns <code>napi_string_expected</code>.</p> <p>This API returns the ISO-8859-1-encoded string corresponding the value passed in.</p> <h4>napi_get_value_string_utf8<span><a class="mark" href="#n_api_napi_get_value_string_utf8" id="n_api_napi_get_value_string_utf8">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_value_string_utf8(napi_env env, napi_value value, char* buf, size_t bufsize, size_t* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li> <li><code>[in] buf</code>: Buffer to write the UTF8-encoded string into. If NULL is passed in, the length of the string (in bytes) is returned.</li> <li><code>[in] bufsize</code>: Size of the destination buffer. When this value is insufficient, the returned string will be truncated.</li> <li><code>[out] result</code>: Number of bytes copied into the buffer, excluding the null terminator.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>String</code> <code>napi_value</code> is passed in it returns <code>napi_string_expected</code>.</p> <p>This API returns the UTF8-encoded string corresponding the value passed in.</p> <h4>napi_get_value_string_utf16<span><a class="mark" href="#n_api_napi_get_value_string_utf16" id="n_api_napi_get_value_string_utf16">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_value_string_utf16(napi_env env, napi_value value, char16_t* buf, size_t bufsize, size_t* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li> <li><code>[in] buf</code>: Buffer to write the UTF16-LE-encoded string into. If NULL is passed in, the length of the string (in 2-byte code units) is returned.</li> <li><code>[in] bufsize</code>: Size of the destination buffer. When this value is insufficient, the returned string will be truncated.</li> <li><code>[out] result</code>: Number of 2-byte code units copied into the buffer, excluding the null terminator.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>String</code> <code>napi_value</code> is passed in it returns <code>napi_string_expected</code>.</p> <p>This API returns the UTF16-encoded string corresponding the value passed in.</p> <h4>napi_get_value_uint32<span><a class="mark" href="#n_api_napi_get_value_uint32" id="n_api_napi_get_value_uint32">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_value_uint32(napi_env env, napi_value value, uint32_t* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Number</code>.</li> <li><code>[out] result</code>: C primitive equivalent of the given <code>napi_value</code> as a <code>uint32_t</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code> is passed in it returns <code>napi_number_expected</code>.</p> <p>This API returns the C primitive equivalent of the given <code>napi_value</code> as a <code>uint32_t</code>.</p> <h3>Functions to get global instances<span><a class="mark" href="#n_api_functions_to_get_global_instances" id="n_api_functions_to_get_global_instances">#</a></span></h3> <h4>napi_get_boolean<span><a class="mark" href="#n_api_napi_get_boolean" id="n_api_napi_get_boolean">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_boolean(napi_env env, bool value, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The value of the boolean to retrieve.</li> <li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>Boolean</code> singleton to retrieve.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API is used to return the JavaScript singleton object that is used to represent the given boolean value.</p> <h4>napi_get_global<span><a class="mark" href="#n_api_napi_get_global" id="n_api_napi_get_global">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_global(napi_env env, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>global</code> object.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns the <code>global</code> object.</p> <h4>napi_get_null<span><a class="mark" href="#n_api_napi_get_null" id="n_api_napi_get_null">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_null(napi_env env, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>null</code> object.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns the <code>null</code> object.</p> <h4>napi_get_undefined<span><a class="mark" href="#n_api_napi_get_undefined" id="n_api_napi_get_undefined">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_undefined(napi_env env, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] result</code>: <code>napi_value</code> representing JavaScript Undefined value.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns the Undefined object.</p> <h2>Working with JavaScript Values - Abstract Operations<span><a class="mark" href="#n_api_working_with_javascript_values_abstract_operations" id="n_api_working_with_javascript_values_abstract_operations">#</a></span></h2> <p>N-API exposes a set of APIs to perform some abstract operations on JavaScript values. Some of these operations are documented under <a href="https://tc39.github.io/ecma262/#sec-abstract-operations">Section 7</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p> <p>These APIs support doing one of the following: 1. Coerce JavaScript values to specific JavaScript types (such as <code>Number</code> or <code>String</code>). 2. Check the type of a JavaScript value. 3. Check for equality between two JavaScript values.</p> <h3>napi_coerce_to_bool<span><a class="mark" href="#n_api_napi_coerce_to_bool" id="n_api_napi_coerce_to_bool">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_coerce_to_bool(napi_env env, napi_value value, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value to coerce.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>Boolean</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API implements the abstract operation <code>ToBoolean()</code> as defined in <a href="https://tc39.github.io/ecma262/#sec-toboolean">Section 7.1.2</a> of the ECMAScript Language Specification. This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p> <h3>napi_coerce_to_number<span><a class="mark" href="#n_api_napi_coerce_to_number" id="n_api_napi_coerce_to_number">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_coerce_to_number(napi_env env, napi_value value, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value to coerce.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>Number</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API implements the abstract operation <code>ToNumber()</code> as defined in <a href="https://tc39.github.io/ecma262/#sec-tonumber">Section 7.1.3</a> of the ECMAScript Language Specification. This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p> <h3>napi_coerce_to_object<span><a class="mark" href="#n_api_napi_coerce_to_object" id="n_api_napi_coerce_to_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_coerce_to_object(napi_env env, napi_value value, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value to coerce.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>Object</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API implements the abstract operation <code>ToObject()</code> as defined in <a href="https://tc39.github.io/ecma262/#sec-toobject">Section 7.1.13</a> of the ECMAScript Language Specification. This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p> <h3>napi_coerce_to_string<span><a class="mark" href="#n_api_napi_coerce_to_string" id="n_api_napi_coerce_to_string">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_coerce_to_string(napi_env env, napi_value value, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value to coerce.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>String</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API implements the abstract operation <code>ToString()</code> as defined in <a href="https://tc39.github.io/ecma262/#sec-tostring">Section 7.1.13</a> of the ECMAScript Language Specification. This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p> <h3>napi_typeof<span><a class="mark" href="#n_api_napi_typeof" id="n_api_napi_typeof">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value whose type to query.</li> <li><code>[out] result</code>: The type of the JavaScript value.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <ul> <li><code>napi_invalid_arg</code> if the type of <code>value</code> is not a known ECMAScript type and <code>value</code> is not an External value.</li> </ul> <p>This API represents behavior similar to invoking the <code>typeof</code> Operator on the object as defined in <a href="https://tc39.github.io/ecma262/#sec-typeof-operator">Section 12.5.5</a> of the ECMAScript Language Specification. However, it has support for detecting an External value. If <code>value</code> has a type that is invalid, an error is returned.</p> <h3>napi_instanceof<span><a class="mark" href="#n_api_napi_instanceof" id="n_api_napi_instanceof">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_instanceof(napi_env env, napi_value object, napi_value constructor, bool* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] object</code>: The JavaScript value to check.</li> <li><code>[in] constructor</code>: The JavaScript function object of the constructor function to check against.</li> <li><code>[out] result</code>: Boolean that is set to true if <code>object instanceof constructor</code> is true.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API represents invoking the <code>instanceof</code> Operator on the object as defined in <a href="https://tc39.github.io/ecma262/#sec-instanceofoperator">Section 12.10.4</a> of the ECMAScript Language Specification.</p> <h3>napi_is_array<span><a class="mark" href="#n_api_napi_is_array" id="n_api_napi_is_array">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_is_array(napi_env env, napi_value value, bool* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value to check.</li> <li><code>[out] result</code>: Whether the given object is an array.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API represents invoking the <code>IsArray</code> operation on the object as defined in <a href="https://tc39.github.io/ecma262/#sec-isarray">Section 7.2.2</a> of the ECMAScript Language Specification.</p> <h3>napi_is_arraybuffer<span><a class="mark" href="#n_api_napi_is_arraybuffer" id="n_api_napi_is_arraybuffer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value to check.</li> <li><code>[out] result</code>: Whether the given object is an <code>ArrayBuffer</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API checks if the <code>Object</code> passed in is an array buffer.</p> <h3>napi_is_buffer<span><a class="mark" href="#n_api_napi_is_buffer" id="n_api_napi_is_buffer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_is_buffer(napi_env env, napi_value value, bool* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value to check.</li> <li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>node::Buffer</code> object.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API checks if the <code>Object</code> passed in is a buffer.</p> <h3>napi_is_date<span><a class="mark" href="#n_api_napi_is_date" id="n_api_napi_is_date">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.17.0</span> <span>N-API version: 4</span> </div> <pre><code class="language-C">napi_status napi_is_date(napi_env env, napi_value value, bool* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value to check.</li> <li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a JavaScript <code>Date</code> object.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API checks if the <code>Object</code> passed in is a date.</p> <h3>napi_is_error<span><a class="mark" href="#n_api_napi_is_error_1" id="n_api_napi_is_error_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_is_error(napi_env env, napi_value value, bool* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value to check.</li> <li><code>[out] result</code>: Whether the given <code>napi_value</code> represents an <code>Error</code> object.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API checks if the <code>Object</code> passed in is an <code>Error</code>.</p> <h3>napi_is_typedarray<span><a class="mark" href="#n_api_napi_is_typedarray" id="n_api_napi_is_typedarray">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value to check.</li> <li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>TypedArray</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API checks if the <code>Object</code> passed in is a typed array.</p> <h3>napi_is_dataview<span><a class="mark" href="#n_api_napi_is_dataview" id="n_api_napi_is_dataview">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.3.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_is_dataview(napi_env env, napi_value value, bool* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] value</code>: The JavaScript value to check.</li> <li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>DataView</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API checks if the <code>Object</code> passed in is a <code>DataView</code>.</p> <h3>napi_strict_equals<span><a class="mark" href="#n_api_napi_strict_equals" id="n_api_napi_strict_equals">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_strict_equals(napi_env env, napi_value lhs, napi_value rhs, bool* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] lhs</code>: The JavaScript value to check.</li> <li><code>[in] rhs</code>: The JavaScript value to check against.</li> <li><code>[out] result</code>: Whether the two <code>napi_value</code> objects are equal.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API represents the invocation of the Strict Equality algorithm as defined in <a href="https://tc39.github.io/ecma262/#sec-strict-equality-comparison">Section 7.2.14</a> of the ECMAScript Language Specification.</p> <h3>napi_detach_arraybuffer<span><a class="mark" href="#n_api_napi_detach_arraybuffer" id="n_api_napi_detach_arraybuffer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.22.0</span> <span>N-API version: 7</span> </div> <pre><code class="language-C">napi_status napi_detach_arraybuffer(napi_env env, napi_value arraybuffer) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] arraybuffer</code>: The JavaScript <code>ArrayBuffer</code> to be detached.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded. If a non-detachable <code>ArrayBuffer</code> is passed in it returns <code>napi_detachable_arraybuffer_expected</code>.</p> <p>Generally, an <code>ArrayBuffer</code> is non-detachable if it has been detached before. The engine may impose additional conditions on whether an <code>ArrayBuffer</code> is detachable. For example, V8 requires that the <code>ArrayBuffer</code> be external, that is, created with <a href="#n_api_napi_create_external_arraybuffer"><code>napi_create_external_arraybuffer</code></a>.</p> <p>This API represents the invocation of the <code>ArrayBuffer</code> detach operation as defined in <a href="https://tc39.es/ecma262/#sec-detacharraybuffer">Section 24.1.1.3</a> of the ECMAScript Language Specification.</p> <h3>napi_is_detached_arraybuffer<span><a class="mark" href="#n_api_napi_is_detached_arraybuffer" id="n_api_napi_is_detached_arraybuffer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.22.0</span> <span>N-API version: 7</span> </div> <pre><code class="language-C">napi_status napi_is_detached_arraybuffer(napi_env env, napi_value arraybuffer, bool* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] arraybuffer</code>: The JavaScript <code>ArrayBuffer</code> to be checked.</li> <li><code>[out] result</code>: Whether the <code>arraybuffer</code> is detached.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>The <code>ArrayBuffer</code> is considered detached if its internal data is <code>null</code>.</p> <p>This API represents the invocation of the <code>ArrayBuffer</code> <code>IsDetachedBuffer</code> operation as defined in <a href="https://tc39.es/ecma262/#sec-isdetachedbuffer">Section 24.1.1.2</a> of the ECMAScript Language Specification.</p> <h2>Working with JavaScript Properties<span><a class="mark" href="#n_api_working_with_javascript_properties" id="n_api_working_with_javascript_properties">#</a></span></h2> <p>N-API exposes a set of APIs to get and set properties on JavaScript objects. Some of these types are documented under <a href="https://tc39.github.io/ecma262/#sec-operations-on-objects">Section 7</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p> <p>Properties in JavaScript are represented as a tuple of a key and a value. Fundamentally, all property keys in N-API can be represented in one of the following forms:</p> <ul> <li>Named: a simple UTF8-encoded string</li> <li>Integer-Indexed: an index value represented by <code>uint32_t</code></li> <li>JavaScript value: these are represented in N-API by <code>napi_value</code>. This can be a <code>napi_value</code> representing a <code>String</code>, <code>Number</code>, or <code>Symbol</code>.</li> </ul> <p>N-API values are represented by the type <code>napi_value</code>. Any N-API call that requires a JavaScript value takes in a <code>napi_value</code>. However, it's the caller's responsibility to make sure that the <code>napi_value</code> in question is of the JavaScript type expected by the API.</p> <p>The APIs documented in this section provide a simple interface to get and set properties on arbitrary JavaScript objects represented by <code>napi_value</code>.</p> <p>For instance, consider the following JavaScript code snippet:</p> <pre><code class="language-js">const obj = {}; obj.myProp = 123; </code></pre> <p>The equivalent can be done using N-API values with the following snippet:</p> <pre><code class="language-C">napi_status status = napi_generic_failure; // const obj = {} napi_value obj, value; status = napi_create_object(env, &obj); if (status != napi_ok) return status; // Create a napi_value for 123 status = napi_create_int32(env, 123, &value); if (status != napi_ok) return status; // obj.myProp = 123 status = napi_set_named_property(env, obj, "myProp", value); if (status != napi_ok) return status; </code></pre> <p>Indexed properties can be set in a similar manner. Consider the following JavaScript snippet:</p> <pre><code class="language-js">const arr = []; arr[123] = 'hello'; </code></pre> <p>The equivalent can be done using N-API values with the following snippet:</p> <pre><code class="language-C">napi_status status = napi_generic_failure; // const arr = []; napi_value arr, value; status = napi_create_array(env, &arr); if (status != napi_ok) return status; // Create a napi_value for 'hello' status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &value); if (status != napi_ok) return status; // arr[123] = 'hello'; status = napi_set_element(env, arr, 123, value); if (status != napi_ok) return status; </code></pre> <p>Properties can be retrieved using the APIs described in this section. Consider the following JavaScript snippet:</p> <pre><code class="language-js">const arr = []; const value = arr[123]; </code></pre> <p>The following is the approximate equivalent of the N-API counterpart:</p> <pre><code class="language-C">napi_status status = napi_generic_failure; // const arr = [] napi_value arr, value; status = napi_create_array(env, &arr); if (status != napi_ok) return status; // const value = arr[123] status = napi_get_element(env, arr, 123, &value); if (status != napi_ok) return status; </code></pre> <p>Finally, multiple properties can also be defined on an object for performance reasons. Consider the following JavaScript:</p> <pre><code class="language-js">const obj = {}; Object.defineProperties(obj, { 'foo': { value: 123, writable: true, configurable: true, enumerable: true }, 'bar': { value: 456, writable: true, configurable: true, enumerable: true } }); </code></pre> <p>The following is the approximate equivalent of the N-API counterpart:</p> <pre><code class="language-C">napi_status status = napi_status_generic_failure; // const obj = {}; napi_value obj; status = napi_create_object(env, &obj); if (status != napi_ok) return status; // Create napi_values for 123 and 456 napi_value fooValue, barValue; status = napi_create_int32(env, 123, &fooValue); if (status != napi_ok) return status; status = napi_create_int32(env, 456, &barValue); if (status != napi_ok) return status; // Set the properties napi_property_descriptor descriptors[] = { { "foo", NULL, NULL, NULL, NULL, fooValue, napi_default, NULL }, { "bar", NULL, NULL, NULL, NULL, barValue, napi_default, NULL } } status = napi_define_properties(env, obj, sizeof(descriptors) / sizeof(descriptors[0]), descriptors); if (status != napi_ok) return status; </code></pre> <h3>Structures<span><a class="mark" href="#n_api_structures" id="n_api_structures">#</a></span></h3> <h4>napi_property_attributes<span><a class="mark" href="#n_api_napi_property_attributes" id="n_api_napi_property_attributes">#</a></span></h4> <pre><code class="language-C">typedef enum { napi_default = 0, napi_writable = 1 << 0, napi_enumerable = 1 << 1, napi_configurable = 1 << 2, // Used with napi_define_class to distinguish static properties // from instance properties. Ignored by napi_define_properties. napi_static = 1 << 10, } napi_property_attributes; </code></pre> <p><code>napi_property_attributes</code> are flags used to control the behavior of properties set on a JavaScript object. Other than <code>napi_static</code> they correspond to the attributes listed in <a href="https://tc39.github.io/ecma262/#table-2">Section 6.1.7.1</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>. They can be one or more of the following bitflags:</p> <ul> <li><code>napi_default</code> - Used to indicate that no explicit attributes are set on the given property. By default, a property is read only, not enumerable and not configurable.</li> <li><code>napi_writable</code> - Used to indicate that a given property is writable.</li> <li><code>napi_enumerable</code> - Used to indicate that a given property is enumerable.</li> <li><code>napi_configurable</code> - Used to indicate that a given property is configurable, as defined in <a href="https://tc39.github.io/ecma262/#table-2">Section 6.1.7.1</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</li> <li><code>napi_static</code> - Used to indicate that the property will be defined as a static property on a class as opposed to an instance property, which is the default. This is used only by <a href="#n_api_napi_define_class"><code>napi_define_class</code></a>. It is ignored by <code>napi_define_properties</code>.</li> </ul> <h4>napi_property_descriptor<span><a class="mark" href="#n_api_napi_property_descriptor" id="n_api_napi_property_descriptor">#</a></span></h4> <pre><code class="language-C">typedef struct { // One of utf8name or name should be NULL. const char* utf8name; napi_value name; napi_callback method; napi_callback getter; napi_callback setter; napi_value value; napi_property_attributes attributes; void* data; } napi_property_descriptor; </code></pre> <ul> <li><code>utf8name</code>: Optional <code>String</code> describing the key for the property, encoded as UTF8. One of <code>utf8name</code> or <code>name</code> must be provided for the property.</li> <li><code>name</code>: Optional <code>napi_value</code> that points to a JavaScript string or symbol to be used as the key for the property. One of <code>utf8name</code> or <code>name</code> must be provided for the property.</li> <li><code>value</code>: The value that's retrieved by a get access of the property if the property is a data property. If this is passed in, set <code>getter</code>, <code>setter</code>, <code>method</code> and <code>data</code> to <code>NULL</code> (since these members won't be used).</li> <li><code>getter</code>: A function to call when a get access of the property is performed. If this is passed in, set <code>value</code> and <code>method</code> to <code>NULL</code> (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).</li> <li><code>setter</code>: A function to call when a set access of the property is performed. If this is passed in, set <code>value</code> and <code>method</code> to <code>NULL</code> (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).</li> <li><code>method</code>: Set this to make the property descriptor object's <code>value</code> property to be a JavaScript function represented by <code>method</code>. If this is passed in, set <code>value</code>, <code>getter</code> and <code>setter</code> to <code>NULL</code> (since these members won't be used).</li> <li><code>attributes</code>: The attributes associated with the particular property. See <a href="#n_api_napi_property_attributes"><code>napi_property_attributes</code></a>.</li> <li><code>data</code>: The callback data passed into <code>method</code>, <code>getter</code> and <code>setter</code> if this function is invoked.</li> </ul> <h3>Functions<span><a class="mark" href="#n_api_functions" id="n_api_functions">#</a></span></h3> <h4>napi_get_property_names<span><a class="mark" href="#n_api_napi_get_property_names" id="n_api_napi_get_property_names">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_property_names(napi_env env, napi_value object, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object from which to retrieve the properties.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing an array of JavaScript values that represent the property names of the object. The API can be used to iterate over <code>result</code> using <a href="#n_api_napi_get_array_length"><code>napi_get_array_length</code></a> and <a href="#n_api_napi_get_element"><code>napi_get_element</code></a>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns the names of the enumerable properties of <code>object</code> as an array of strings. The properties of <code>object</code> whose key is a symbol will not be included.</p> <h4>napi_get_all_property_names<span><a class="mark" href="#n_api_napi_get_all_property_names" id="n_api_napi_get_all_property_names">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.20.0</span> <span>N-API version: 6</span> </div> <pre><code class="language-C">napi_get_all_property_names(napi_env env, napi_value object, napi_key_collection_mode key_mode, napi_key_filter key_filter, napi_key_conversion key_conversion, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object from which to retrieve the properties.</li> <li><code>[in] key_mode</code>: Whether to retrieve prototype properties as well.</li> <li><code>[in] key_filter</code>: Which properties to retrieve (enumerable/readable/writable).</li> <li><code>[in] key_conversion</code>: Whether to convert numbered property keys to strings.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing an array of JavaScript values that represent the property names of the object. <a href="#n_api_napi_get_array_length"><code>napi_get_array_length</code></a> and <a href="#n_api_napi_get_element"><code>napi_get_element</code></a> can be used to iterate over <code>result</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns an array containing the names of the available properties of this object.</p> <h4>napi_set_property<span><a class="mark" href="#n_api_napi_set_property" id="n_api_napi_set_property">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_set_property(napi_env env, napi_value object, napi_value key, napi_value value); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object on which to set the property.</li> <li><code>[in] key</code>: The name of the property to set.</li> <li><code>[in] value</code>: The property value.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API set a property on the <code>Object</code> passed in.</p> <h4>napi_get_property<span><a class="mark" href="#n_api_napi_get_property" id="n_api_napi_get_property">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_property(napi_env env, napi_value object, napi_value key, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object from which to retrieve the property.</li> <li><code>[in] key</code>: The name of the property to retrieve.</li> <li><code>[out] result</code>: The value of the property.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API gets the requested property from the <code>Object</code> passed in.</p> <h4>napi_has_property<span><a class="mark" href="#n_api_napi_has_property" id="n_api_napi_has_property">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_has_property(napi_env env, napi_value object, napi_value key, bool* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object to query.</li> <li><code>[in] key</code>: The name of the property whose existence to check.</li> <li><code>[out] result</code>: Whether the property exists on the object or not.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API checks if the <code>Object</code> passed in has the named property.</p> <h4>napi_delete_property<span><a class="mark" href="#n_api_napi_delete_property" id="n_api_napi_delete_property">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.2.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_delete_property(napi_env env, napi_value object, napi_value key, bool* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object to query.</li> <li><code>[in] key</code>: The name of the property to delete.</li> <li><code>[out] result</code>: Whether the property deletion succeeded or not. <code>result</code> can optionally be ignored by passing <code>NULL</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API attempts to delete the <code>key</code> own property from <code>object</code>.</p> <h4>napi_has_own_property<span><a class="mark" href="#n_api_napi_has_own_property" id="n_api_napi_has_own_property">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.2.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_has_own_property(napi_env env, napi_value object, napi_value key, bool* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object to query.</li> <li><code>[in] key</code>: The name of the own property whose existence to check.</li> <li><code>[out] result</code>: Whether the own property exists on the object or not.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API checks if the <code>Object</code> passed in has the named own property. <code>key</code> must be a string or a <code>Symbol</code>, or an error will be thrown. N-API will not perform any conversion between data types.</p> <h4>napi_set_named_property<span><a class="mark" href="#n_api_napi_set_named_property" id="n_api_napi_set_named_property">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_set_named_property(napi_env env, napi_value object, const char* utf8Name, napi_value value); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object on which to set the property.</li> <li><code>[in] utf8Name</code>: The name of the property to set.</li> <li><code>[in] value</code>: The property value.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This method is equivalent to calling <a href="#n_api_napi_set_property"><code>napi_set_property</code></a> with a <code>napi_value</code> created from the string passed in as <code>utf8Name</code>.</p> <h4>napi_get_named_property<span><a class="mark" href="#n_api_napi_get_named_property" id="n_api_napi_get_named_property">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_named_property(napi_env env, napi_value object, const char* utf8Name, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object from which to retrieve the property.</li> <li><code>[in] utf8Name</code>: The name of the property to get.</li> <li><code>[out] result</code>: The value of the property.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This method is equivalent to calling <a href="#n_api_napi_get_property"><code>napi_get_property</code></a> with a <code>napi_value</code> created from the string passed in as <code>utf8Name</code>.</p> <h4>napi_has_named_property<span><a class="mark" href="#n_api_napi_has_named_property" id="n_api_napi_has_named_property">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_has_named_property(napi_env env, napi_value object, const char* utf8Name, bool* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object to query.</li> <li><code>[in] utf8Name</code>: The name of the property whose existence to check.</li> <li><code>[out] result</code>: Whether the property exists on the object or not.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This method is equivalent to calling <a href="#n_api_napi_has_property"><code>napi_has_property</code></a> with a <code>napi_value</code> created from the string passed in as <code>utf8Name</code>.</p> <h4>napi_set_element<span><a class="mark" href="#n_api_napi_set_element" id="n_api_napi_set_element">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_set_element(napi_env env, napi_value object, uint32_t index, napi_value value); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object from which to set the properties.</li> <li><code>[in] index</code>: The index of the property to set.</li> <li><code>[in] value</code>: The property value.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API sets and element on the <code>Object</code> passed in.</p> <h4>napi_get_element<span><a class="mark" href="#n_api_napi_get_element" id="n_api_napi_get_element">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_element(napi_env env, napi_value object, uint32_t index, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object from which to retrieve the property.</li> <li><code>[in] index</code>: The index of the property to get.</li> <li><code>[out] result</code>: The value of the property.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API gets the element at the requested index.</p> <h4>napi_has_element<span><a class="mark" href="#n_api_napi_has_element" id="n_api_napi_has_element">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_has_element(napi_env env, napi_value object, uint32_t index, bool* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object to query.</li> <li><code>[in] index</code>: The index of the property whose existence to check.</li> <li><code>[out] result</code>: Whether the property exists on the object or not.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns if the <code>Object</code> passed in has an element at the requested index.</p> <h4>napi_delete_element<span><a class="mark" href="#n_api_napi_delete_element" id="n_api_napi_delete_element">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.2.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_delete_element(napi_env env, napi_value object, uint32_t index, bool* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object to query.</li> <li><code>[in] index</code>: The index of the property to delete.</li> <li><code>[out] result</code>: Whether the element deletion succeeded or not. <code>result</code> can optionally be ignored by passing <code>NULL</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API attempts to delete the specified <code>index</code> from <code>object</code>.</p> <h4>napi_define_properties<span><a class="mark" href="#n_api_napi_define_properties" id="n_api_napi_define_properties">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_define_properties(napi_env env, napi_value object, size_t property_count, const napi_property_descriptor* properties); </code></pre> <ul> <li><code>[in] env</code>: The environment that the N-API call is invoked under.</li> <li><code>[in] object</code>: The object from which to retrieve the properties.</li> <li><code>[in] property_count</code>: The number of elements in the <code>properties</code> array.</li> <li><code>[in] properties</code>: The array of property descriptors.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This method allows the efficient definition of multiple properties on a given object. The properties are defined using property descriptors (see <a href="#n_api_napi_property_descriptor"><code>napi_property_descriptor</code></a>). Given an array of such property descriptors, this API will set the properties on the object one at a time, as defined by <code>DefineOwnProperty()</code> (described in <a href="https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-defineownproperty-p-desc">Section 9.1.6</a> of the ECMA262 specification).</p> <h2>Working with JavaScript Functions<span><a class="mark" href="#n_api_working_with_javascript_functions" id="n_api_working_with_javascript_functions">#</a></span></h2> <p>N-API provides a set of APIs that allow JavaScript code to call back into native code. N-API APIs that support calling back into native code take in a callback functions represented by the <code>napi_callback</code> type. When the JavaScript VM calls back to native code, the <code>napi_callback</code> function provided is invoked. The APIs documented in this section allow the callback function to do the following:</p> <ul> <li>Get information about the context in which the callback was invoked.</li> <li>Get the arguments passed into the callback.</li> <li>Return a <code>napi_value</code> back from the callback.</li> </ul> <p>Additionally, N-API provides a set of functions which allow calling JavaScript functions from native code. One can either call a function like a regular JavaScript function call, or as a constructor function.</p> <p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> field of the <code>napi_property_descriptor</code> items can be associated with <code>object</code> and freed whenever <code>object</code> is garbage-collected by passing both <code>object</code> and the data to <a href="#n_api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p> <h3>napi_call_function<span><a class="mark" href="#n_api_napi_call_function" id="n_api_napi_call_function">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_call_function(napi_env env, napi_value recv, napi_value func, int argc, const napi_value* argv, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] recv</code>: The <code>this</code> object passed to the called function.</li> <li><code>[in] func</code>: <code>napi_value</code> representing the JavaScript function to be invoked.</li> <li><code>[in] argc</code>: The count of elements in the <code>argv</code> array.</li> <li><code>[in] argv</code>: Array of <code>napi_values</code> representing JavaScript values passed in as arguments to the function.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript object returned.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This method allows a JavaScript function object to be called from a native add-on. This is the primary mechanism of calling back <em>from</em> the add-on's native code <em>into</em> JavaScript. For the special case of calling into JavaScript after an async operation, see <a href="#n_api_napi_make_callback"><code>napi_make_callback</code></a>.</p> <p>A sample use case might look as follows. Consider the following JavaScript snippet:</p> <pre><code class="language-js">function AddTwo(num) { return num + 2; } </code></pre> <p>Then, the above function can be invoked from a native add-on using the following code:</p> <pre><code class="language-C">// Get the function named "AddTwo" on the global object napi_value global, add_two, arg; napi_status status = napi_get_global(env, &global); if (status != napi_ok) return; status = napi_get_named_property(env, global, "AddTwo", &add_two); if (status != napi_ok) return; // const arg = 1337 status = napi_create_int32(env, 1337, &arg); if (status != napi_ok) return; napi_value* argv = &arg; size_t argc = 1; // AddTwo(arg); napi_value return_val; status = napi_call_function(env, global, add_two, argc, argv, &return_val); if (status != napi_ok) return; // Convert the result back to a native type int32_t result; status = napi_get_value_int32(env, return_val, &result); if (status != napi_ok) return; </code></pre> <h3>napi_create_function<span><a class="mark" href="#n_api_napi_create_function" id="n_api_napi_create_function">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_function(napi_env env, const char* utf8name, size_t length, napi_callback cb, void* data, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] utf8Name</code>: The name of the function encoded as UTF8. This is visible within JavaScript as the new function object's <code>name</code> property.</li> <li><code>[in] length</code>: The length of the <code>utf8name</code> in bytes, or <code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li> <li><code>[in] cb</code>: The native function which should be called when this function object is invoked.</li> <li><code>[in] data</code>: User-provided data context. This will be passed back into the function when invoked later.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript function object for the newly created function.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API allows an add-on author to create a function object in native code. This is the primary mechanism to allow calling <em>into</em> the add-on's native code <em>from</em> JavaScript.</p> <p>The newly created function is not automatically visible from script after this call. Instead, a property must be explicitly set on any object that is visible to JavaScript, in order for the function to be accessible from script.</p> <p>In order to expose a function as part of the add-on's module exports, set the newly created function on the exports object. A sample module might look as follows:</p> <pre><code class="language-C">napi_value SayHello(napi_env env, napi_callback_info info) { printf("Hello\n"); return NULL; } napi_value Init(napi_env env, napi_value exports) { napi_status status; napi_value fn; status = napi_create_function(env, NULL, 0, SayHello, NULL, &fn); if (status != napi_ok) return NULL; status = napi_set_named_property(env, exports, "sayHello", fn); if (status != napi_ok) return NULL; return exports; } NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) </code></pre> <p>Given the above code, the add-on can be used from JavaScript as follows:</p> <pre><code class="language-js">const myaddon = require('./addon'); myaddon.sayHello(); </code></pre> <p>The string passed to <code>require()</code> is the name of the target in <code>binding.gyp</code> responsible for creating the <code>.node</code> file.</p> <p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> parameter can be associated with the resulting JavaScript function (which is returned in the <code>result</code> parameter) and freed whenever the function is garbage-collected by passing both the JavaScript function and the data to <a href="#n_api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p> <p>JavaScript <code>Function</code>s are described in <a href="https://tc39.github.io/ecma262/#sec-function-objects">Section 19.2</a> of the ECMAScript Language Specification.</p> <h3>napi_get_cb_info<span><a class="mark" href="#n_api_napi_get_cb_info" id="n_api_napi_get_cb_info">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_cb_info(napi_env env, napi_callback_info cbinfo, size_t* argc, napi_value* argv, napi_value* thisArg, void** data) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] cbinfo</code>: The callback info passed into the callback function.</li> <li><code>[in-out] argc</code>: Specifies the size of the provided <code>argv</code> array and receives the actual count of arguments.</li> <li><code>[out] argv</code>: Buffer to which the <code>napi_value</code> representing the arguments are copied. If there are more arguments than the provided count, only the requested number of arguments are copied. If there are fewer arguments provided than claimed, the rest of <code>argv</code> is filled with <code>napi_value</code> values that represent <code>undefined</code>.</li> <li><code>[out] this</code>: Receives the JavaScript <code>this</code> argument for the call.</li> <li><code>[out] data</code>: Receives the data pointer for the callback.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This method is used within a callback function to retrieve details about the call like the arguments and the <code>this</code> pointer from a given callback info.</p> <h3>napi_get_new_target<span><a class="mark" href="#n_api_napi_get_new_target" id="n_api_napi_get_new_target">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.6.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_new_target(napi_env env, napi_callback_info cbinfo, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] cbinfo</code>: The callback info passed into the callback function.</li> <li><code>[out] result</code>: The <code>new.target</code> of the constructor call.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns the <code>new.target</code> of the constructor call. If the current callback is not a constructor call, the result is <code>NULL</code>.</p> <h3>napi_new_instance<span><a class="mark" href="#n_api_napi_new_instance" id="n_api_napi_new_instance">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_new_instance(napi_env env, napi_value cons, size_t argc, napi_value* argv, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] cons</code>: <code>napi_value</code> representing the JavaScript function to be invoked as a constructor.</li> <li><code>[in] argc</code>: The count of elements in the <code>argv</code> array.</li> <li><code>[in] argv</code>: Array of JavaScript values as <code>napi_value</code> representing the arguments to the constructor.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript object returned, which in this case is the constructed object.</li> </ul> <p>This method is used to instantiate a new JavaScript value using a given <code>napi_value</code> that represents the constructor for the object. For example, consider the following snippet:</p> <pre><code class="language-js">function MyObject(param) { this.param = param; } const arg = 'hello'; const value = new MyObject(arg); </code></pre> <p>The following can be approximated in N-API using the following snippet:</p> <pre><code class="language-C">// Get the constructor function MyObject napi_value global, constructor, arg, value; napi_status status = napi_get_global(env, &global); if (status != napi_ok) return; status = napi_get_named_property(env, global, "MyObject", &constructor); if (status != napi_ok) return; // const arg = "hello" status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &arg); if (status != napi_ok) return; napi_value* argv = &arg; size_t argc = 1; // const value = new MyObject(arg) status = napi_new_instance(env, constructor, argc, argv, &value); </code></pre> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <h2>Object Wrap<span><a class="mark" href="#n_api_object_wrap" id="n_api_object_wrap">#</a></span></h2> <p>N-API offers a way to "wrap" C++ classes and instances so that the class constructor and methods can be called from JavaScript.</p> <ol> <li>The <a href="#n_api_napi_define_class"><code>napi_define_class</code></a> API defines a JavaScript class with constructor, static properties and methods, and instance properties and methods that correspond to the C++ class.</li> <li>When JavaScript code invokes the constructor, the constructor callback uses <a href="#n_api_napi_wrap"><code>napi_wrap</code></a> to wrap a new C++ instance in a JavaScript object, then returns the wrapper object.</li> <li>When JavaScript code invokes a method or property accessor on the class, the corresponding <code>napi_callback</code> C++ function is invoked. For an instance callback, <a href="#n_api_napi_unwrap"><code>napi_unwrap</code></a> obtains the C++ instance that is the target of the call.</li> </ol> <p>For wrapped objects it may be difficult to distinguish between a function called on a class prototype and a function called on an instance of a class. A common pattern used to address this problem is to save a persistent reference to the class constructor for later <code>instanceof</code> checks.</p> <pre><code class="language-C">napi_value MyClass_constructor = NULL; status = napi_get_reference_value(env, MyClass::es_constructor, &MyClass_constructor); assert(napi_ok == status); bool is_instance = false; status = napi_instanceof(env, es_this, MyClass_constructor, &is_instance); assert(napi_ok == status); if (is_instance) { // napi_unwrap() ... } else { // otherwise... } </code></pre> <p>The reference must be freed once it is no longer needed.</p> <h3>napi_define_class<span><a class="mark" href="#n_api_napi_define_class" id="n_api_napi_define_class">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_define_class(napi_env env, const char* utf8name, size_t length, napi_callback constructor, void* data, size_t property_count, const napi_property_descriptor* properties, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] utf8name</code>: Name of the JavaScript constructor function; this is not required to be the same as the C++ class name, though it is recommended for clarity.</li> <li><code>[in] length</code>: The length of the <code>utf8name</code> in bytes, or <code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li> <li><code>[in] constructor</code>: Callback function that handles constructing instances of the class. (This should be a static method on the class, not an actual C++ constructor function.)</li> <li><code>[in] data</code>: Optional data to be passed to the constructor callback as the <code>data</code> property of the callback info.</li> <li><code>[in] property_count</code>: Number of items in the <code>properties</code> array argument.</li> <li><code>[in] properties</code>: Array of property descriptors describing static and instance data properties, accessors, and methods on the class See <code>napi_property_descriptor</code>.</li> <li><code>[out] result</code>: A <code>napi_value</code> representing the constructor function for the class.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>Defines a JavaScript class that corresponds to a C++ class, including:</p> <ul> <li>A JavaScript constructor function that has the class name and invokes the provided C++ constructor callback.</li> <li>Properties on the constructor function corresponding to <em>static</em> data properties, accessors, and methods of the C++ class (defined by property descriptors with the <code>napi_static</code> attribute).</li> <li>Properties on the constructor function's <code>prototype</code> object corresponding to <em>non-static</em> data properties, accessors, and methods of the C++ class (defined by property descriptors without the <code>napi_static</code> attribute).</li> </ul> <p>The C++ constructor callback should be a static method on the class that calls the actual class constructor, then wraps the new C++ instance in a JavaScript object, and returns the wrapper object. See <code>napi_wrap()</code> for details.</p> <p>The JavaScript constructor function returned from <a href="#n_api_napi_define_class"><code>napi_define_class</code></a> is often saved and used later, to construct new instances of the class from native code, and/or check whether provided values are instances of the class. In that case, to prevent the function value from being garbage-collected, create a persistent reference to it using <a href="#n_api_napi_create_reference"><code>napi_create_reference</code></a> and ensure the reference count is kept >= 1.</p> <p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> parameter or via the <code>data</code> field of the <code>napi_property_descriptor</code> array items can be associated with the resulting JavaScript constructor (which is returned in the <code>result</code> parameter) and freed whenever the class is garbage-collected by passing both the JavaScript function and the data to <a href="#n_api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p> <h3>napi_wrap<span><a class="mark" href="#n_api_napi_wrap" id="n_api_napi_wrap">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_wrap(napi_env env, napi_value js_object, void* native_object, napi_finalize finalize_cb, void* finalize_hint, napi_ref* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] js_object</code>: The JavaScript object that will be the wrapper for the native object.</li> <li><code>[in] native_object</code>: The native instance that will be wrapped in the JavaScript object.</li> <li><code>[in] finalize_cb</code>: Optional native callback that can be used to free the native instance when the JavaScript object is ready for garbage-collection.</li> <li><code>[in] finalize_hint</code>: Optional contextual hint that is passed to the finalize callback.</li> <li><code>[out] result</code>: Optional reference to the wrapped object.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>Wraps a native instance in a JavaScript object. The native instance can be retrieved later using <code>napi_unwrap()</code>.</p> <p>When JavaScript code invokes a constructor for a class that was defined using <code>napi_define_class()</code>, the <code>napi_callback</code> for the constructor is invoked. After constructing an instance of the native class, the callback must then call <code>napi_wrap()</code> to wrap the newly constructed instance in the already-created JavaScript object that is the <code>this</code> argument to the constructor callback. (That <code>this</code> object was created from the constructor function's <code>prototype</code>, so it already has definitions of all the instance properties and methods.)</p> <p>Typically when wrapping a class instance, a finalize callback should be provided that simply deletes the native instance that is received as the <code>data</code> argument to the finalize callback.</p> <p>The optional returned reference is initially a weak reference, meaning it has a reference count of 0. Typically this reference count would be incremented temporarily during async operations that require the instance to remain valid.</p> <p><em>Caution</em>: The optional returned reference (if obtained) should be deleted via <a href="#n_api_napi_delete_reference"><code>napi_delete_reference</code></a> ONLY in response to the finalize callback invocation. If it is deleted before then, then the finalize callback may never be invoked. Therefore, when obtaining a reference a finalize callback is also required in order to enable correct disposal of the reference.</p> <p>Calling <code>napi_wrap()</code> a second time on an object will return an error. To associate another native instance with the object, use <code>napi_remove_wrap()</code> first.</p> <h3>napi_unwrap<span><a class="mark" href="#n_api_napi_unwrap" id="n_api_napi_unwrap">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_unwrap(napi_env env, napi_value js_object, void** result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] js_object</code>: The object associated with the native instance.</li> <li><code>[out] result</code>: Pointer to the wrapped native instance.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>Retrieves a native instance that was previously wrapped in a JavaScript object using <code>napi_wrap()</code>.</p> <p>When JavaScript code invokes a method or property accessor on the class, the corresponding <code>napi_callback</code> is invoked. If the callback is for an instance method or accessor, then the <code>this</code> argument to the callback is the wrapper object; the wrapped C++ instance that is the target of the call can be obtained then by calling <code>napi_unwrap()</code> on the wrapper object.</p> <h3>napi_remove_wrap<span><a class="mark" href="#n_api_napi_remove_wrap" id="n_api_napi_remove_wrap">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_remove_wrap(napi_env env, napi_value js_object, void** result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] js_object</code>: The object associated with the native instance.</li> <li><code>[out] result</code>: Pointer to the wrapped native instance.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>Retrieves a native instance that was previously wrapped in the JavaScript object <code>js_object</code> using <code>napi_wrap()</code> and removes the wrapping. If a finalize callback was associated with the wrapping, it will no longer be called when the JavaScript object becomes garbage-collected.</p> <h3>napi_add_finalizer<span><a class="mark" href="#n_api_napi_add_finalizer" id="n_api_napi_add_finalizer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_add_finalizer(napi_env env, napi_value js_object, void* native_object, napi_finalize finalize_cb, void* finalize_hint, napi_ref* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] js_object</code>: The JavaScript object to which the native data will be attached.</li> <li><code>[in] native_object</code>: The native data that will be attached to the JavaScript object.</li> <li><code>[in] finalize_cb</code>: Native callback that will be used to free the native data when the JavaScript object is ready for garbage-collection.</li> <li><code>[in] finalize_hint</code>: Optional contextual hint that is passed to the finalize callback.</li> <li><code>[out] result</code>: Optional reference to the JavaScript object.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>Adds a <code>napi_finalize</code> callback which will be called when the JavaScript object in <code>js_object</code> is ready for garbage collection. This API is similar to <code>napi_wrap()</code> except that</p> <ul> <li>the native data cannot be retrieved later using <code>napi_unwrap()</code>,</li> <li>nor can it be removed later using <code>napi_remove_wrap()</code>, and</li> <li>the API can be called multiple times with different data items in order to attach each of them to the JavaScript object.</li> </ul> <p><em>Caution</em>: The optional returned reference (if obtained) should be deleted via <a href="#n_api_napi_delete_reference"><code>napi_delete_reference</code></a> ONLY in response to the finalize callback invocation. If it is deleted before then, then the finalize callback may never be invoked. Therefore, when obtaining a reference a finalize callback is also required in order to enable correct disposal of the reference.</p> <h2>Simple Asynchronous Operations<span><a class="mark" href="#n_api_simple_asynchronous_operations" id="n_api_simple_asynchronous_operations">#</a></span></h2> <p>Addon modules often need to leverage async helpers from libuv as part of their implementation. This allows them to schedule work to be executed asynchronously so that their methods can return in advance of the work being completed. This is important in order to allow them to avoid blocking overall execution of the Node.js application.</p> <p>N-API provides an ABI-stable interface for these supporting functions which covers the most common asynchronous use cases.</p> <p>N-API defines the <code>napi_work</code> structure which is used to manage asynchronous workers. Instances are created/deleted with <a href="#n_api_napi_create_async_work"><code>napi_create_async_work</code></a> and <a href="#n_api_napi_delete_async_work"><code>napi_delete_async_work</code></a>.</p> <p>The <code>execute</code> and <code>complete</code> callbacks are functions that will be invoked when the executor is ready to execute and when it completes its task respectively.</p> <p>The <code>execute</code> function should avoid making any N-API calls that could result in the execution of JavaScript or interaction with JavaScript objects. Most often, any code that needs to make N-API calls should be made in <code>complete</code> callback instead.</p> <p>These functions implement the following interfaces:</p> <pre><code class="language-C">typedef void (*napi_async_execute_callback)(napi_env env, void* data); typedef void (*napi_async_complete_callback)(napi_env env, napi_status status, void* data); </code></pre> <p>When these methods are invoked, the <code>data</code> parameter passed will be the addon-provided <code>void*</code> data that was passed into the <code>napi_create_async_work</code> call.</p> <p>Once created the async worker can be queued for execution using the <a href="#n_api_napi_queue_async_work"><code>napi_queue_async_work</code></a> function:</p> <pre><code class="language-C">napi_status napi_queue_async_work(napi_env env, napi_async_work work); </code></pre> <p><a href="#n_api_napi_cancel_async_work"><code>napi_cancel_async_work</code></a> can be used if the work needs to be cancelled before the work has started execution.</p> <p>After calling <a href="#n_api_napi_cancel_async_work"><code>napi_cancel_async_work</code></a>, the <code>complete</code> callback will be invoked with a status value of <code>napi_cancelled</code>. The work should not be deleted before the <code>complete</code> callback invocation, even when it was cancelled.</p> <h3>napi_create_async_work<span><a class="mark" href="#n_api_napi_create_async_work" id="n_api_napi_create_async_work">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.6.0</td> <td><p>Added <code>async_resource</code> and <code>async_resource_name</code> parameters.</p></td></tr> <tr><td>v8.0.0</td> <td><p><span>Added in: v8.0.0</span></p></td></tr> </tbody></table> </details> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_async_work(napi_env env, napi_value async_resource, napi_value async_resource_name, napi_async_execute_callback execute, napi_async_complete_callback complete, void* data, napi_async_work* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] async_resource</code>: An optional object associated with the async work that will be passed to possible <code>async_hooks</code> <a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a>.</li> <li><code>[in] async_resource_name</code>: Identifier for the kind of resource that is being provided for diagnostic information exposed by the <code>async_hooks</code> API.</li> <li><code>[in] execute</code>: The native function which should be called to execute the logic asynchronously. The given function is called from a worker pool thread and can execute in parallel with the main event loop thread.</li> <li><code>[in] complete</code>: 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.</li> <li><code>[in] data</code>: User-provided data context. This will be passed back into the execute and complete functions.</li> <li><code>[out] result</code>: <code>napi_async_work*</code> which is the handle to the newly created async work.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API allocates a work object that is used to execute logic asynchronously. It should be freed using <a href="#n_api_napi_delete_async_work"><code>napi_delete_async_work</code></a> once the work is no longer required.</p> <p><code>async_resource_name</code> should be a null-terminated, UTF-8-encoded string.</p> <p>The <code>async_resource_name</code> identifier is provided by the user and should be representative of the type of async work being performed. It is also recommended to apply namespacing to the identifier, e.g. by including the module name. See the <a href="#async_hooks_type"><code>async_hooks</code> documentation</a> for more information.</p> <h3>napi_delete_async_work<span><a class="mark" href="#n_api_napi_delete_async_work" id="n_api_napi_delete_async_work">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_delete_async_work(napi_env env, napi_async_work work); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API frees a previously allocated work object.</p> <p>This API can be called even if there is a pending JavaScript exception.</p> <h3>napi_queue_async_work<span><a class="mark" href="#n_api_napi_queue_async_work" id="n_api_napi_queue_async_work">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_queue_async_work(napi_env env, napi_async_work work); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API requests that the previously allocated work be scheduled for execution.</p> <h3>napi_cancel_async_work<span><a class="mark" href="#n_api_napi_cancel_async_work" id="n_api_napi_cancel_async_work">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_cancel_async_work(napi_env env, napi_async_work work); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API cancels queued work if it has not yet been started. If it has already started executing, it cannot be cancelled and <code>napi_generic_failure</code> will be returned. If successful, the <code>complete</code> callback will be invoked with a status value of <code>napi_cancelled</code>. The work should not be deleted before the <code>complete</code> callback invocation, even if it has been successfully cancelled.</p> <p>This API can be called even if there is a pending JavaScript exception.</p> <h2>Custom Asynchronous Operations<span><a class="mark" href="#n_api_custom_asynchronous_operations" id="n_api_custom_asynchronous_operations">#</a></span></h2> <p>The simple asynchronous work APIs above may not be appropriate for every scenario. When using any other asynchronous mechanism, the following APIs are necessary to ensure an asynchronous operation is properly tracked by the runtime.</p> <h3>napi_async_init<span><a class="mark" href="#n_api_napi_async_init" id="n_api_napi_async_init">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.6.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_async_init(napi_env env, napi_value async_resource, napi_value async_resource_name, napi_async_context* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] async_resource</code>: An optional object associated with the async work that will be passed to possible <code>async_hooks</code> <a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a>.</li> <li><code>[in] async_resource_name</code>: Identifier for the kind of resource that is being provided for diagnostic information exposed by the <code>async_hooks</code> API.</li> <li><code>[out] result</code>: The initialized async context.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <h3>napi_async_destroy<span><a class="mark" href="#n_api_napi_async_destroy" id="n_api_napi_async_destroy">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.6.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_async_destroy(napi_env env, napi_async_context async_context); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] async_context</code>: The async context to be destroyed.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API can be called even if there is a pending JavaScript exception.</p> <h3>napi_make_callback<span><a class="mark" href="#n_api_napi_make_callback" id="n_api_napi_make_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.6.0</td> <td><p>Added <code>async_context</code> parameter.</p></td></tr> <tr><td>v8.0.0</td> <td><p><span>Added in: v8.0.0</span></p></td></tr> </tbody></table> </details> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_make_callback(napi_env env, napi_async_context async_context, napi_value recv, napi_value func, int argc, const napi_value* argv, napi_value* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] async_context</code>: Context for the async operation that is invoking the callback. This should normally be a value previously obtained from <a href="#n_api_napi_async_init"><code>napi_async_init</code></a>. However <code>NULL</code> is also allowed, which indicates the current async context (if any) is to be used for the callback.</li> <li><code>[in] recv</code>: The <code>this</code> object passed to the called function.</li> <li><code>[in] func</code>: <code>napi_value</code> representing the JavaScript function to be invoked.</li> <li><code>[in] argc</code>: The count of elements in the <code>argv</code> array.</li> <li><code>[in] argv</code>: Array of JavaScript values as <code>napi_value</code> representing the arguments to the function.</li> <li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript object returned.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This method allows a JavaScript function object to be called from a native add-on. This API is similar to <code>napi_call_function</code>. However, it is used to call <em>from</em> native code back <em>into</em> JavaScript <em>after</em> returning from an async operation (when there is no other script on the stack). It is a fairly simple wrapper around <code>node::MakeCallback</code>.</p> <p>Note it is <em>not</em> necessary to use <code>napi_make_callback</code> from within a <code>napi_async_complete_callback</code>; in that situation the callback's async context has already been set up, so a direct call to <code>napi_call_function</code> is sufficient and appropriate. Use of the <code>napi_make_callback</code> function may be required when implementing custom async behavior that does not use <code>napi_create_async_work</code>.</p> <h3>napi_open_callback_scope<span><a class="mark" href="#n_api_napi_open_callback_scope" id="n_api_napi_open_callback_scope">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.6.0</span> <span>N-API version: 3</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env, napi_value resource_object, napi_async_context context, napi_callback_scope* result) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] resource_object</code>: An object associated with the async work that will be passed to possible <code>async_hooks</code> <a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a>.</li> <li><code>[in] context</code>: Context for the async operation that is invoking the callback. This should be a value previously obtained from <a href="#n_api_napi_async_init"><code>napi_async_init</code></a>.</li> <li><code>[out] result</code>: The newly created scope.</li> </ul> <p>There are cases (for example, resolving promises) where it is necessary to have the equivalent of the scope associated with a callback in place when making certain N-API calls. If there is no other script on the stack the <a href="#n_api_napi_open_callback_scope"><code>napi_open_callback_scope</code></a> and <a href="#n_api_napi_close_callback_scope"><code>napi_close_callback_scope</code></a> functions can be used to open/close the required scope.</p> <h3>napi_close_callback_scope<span><a class="mark" href="#n_api_napi_close_callback_scope" id="n_api_napi_close_callback_scope">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.6.0</span> <span>N-API version: 3</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env, napi_callback_scope scope) </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] scope</code>: The scope to be closed.</li> </ul> <p>This API can be called even if there is a pending JavaScript exception.</p> <h2>Version Management<span><a class="mark" href="#n_api_version_management" id="n_api_version_management">#</a></span></h2> <h3>napi_get_node_version<span><a class="mark" href="#n_api_napi_get_node_version" id="n_api_napi_get_node_version">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">typedef struct { uint32_t major; uint32_t minor; uint32_t patch; const char* release; } napi_node_version; napi_status napi_get_node_version(napi_env env, const napi_node_version** version); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] version</code>: A pointer to version information for Node.js itself.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This function fills the <code>version</code> struct with the major, minor, and patch version of Node.js that is currently running, and the <code>release</code> field with the value of <a href="#process_process_release"><code>process.release.name</code></a>.</p> <p>The returned buffer is statically allocated and does not need to be freed.</p> <h3>napi_get_version<span><a class="mark" href="#n_api_napi_get_version" id="n_api_napi_get_version">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_get_version(napi_env env, uint32_t* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] result</code>: The highest version of N-API supported.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API returns the highest N-API version supported by the Node.js runtime. N-API is planned to be additive such that newer releases of Node.js may support additional API functions. In order to allow an addon to use a newer function when running with versions of Node.js that support it, while providing fallback behavior when running with Node.js versions that don't support it:</p> <ul> <li>Call <code>napi_get_version()</code> to determine if the API is available.</li> <li>If available, dynamically load a pointer to the function using <code>uv_dlsym()</code>.</li> <li>Use the dynamically loaded pointer to invoke the function.</li> <li>If the function is not available, provide an alternate implementation that does not use the function.</li> </ul> <h2>Memory Management<span><a class="mark" href="#n_api_memory_management" id="n_api_memory_management">#</a></span></h2> <h3>napi_adjust_external_memory<span><a class="mark" href="#n_api_napi_adjust_external_memory" id="n_api_napi_adjust_external_memory">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env, int64_t change_in_bytes, int64_t* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] change_in_bytes</code>: The change in externally allocated memory that is kept alive by JavaScript objects.</li> <li><code>[out] result</code>: The adjusted value</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This function gives V8 an indication of the amount of externally allocated memory that is kept alive by JavaScript objects (i.e. a JavaScript object that points to its own memory allocated by a native module). Registering externally allocated memory will trigger global garbage collections more often than it would otherwise.</p> <!-- it's very convenient to have all the anchors indexed --> <!--lint disable no-unused-definitions remark-lint--> <h2>Promises<span><a class="mark" href="#n_api_promises" id="n_api_promises">#</a></span></h2> <p>N-API provides facilities for creating <code>Promise</code> objects as described in <a href="https://tc39.github.io/ecma262/#sec-promise-objects">Section 25.4</a> of the ECMA specification. It implements promises as a pair of objects. When a promise is created by <code>napi_create_promise()</code>, a "deferred" object is created and returned alongside the <code>Promise</code>. The deferred object is bound to the created <code>Promise</code> and is the only means to resolve or reject the <code>Promise</code> using <code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code>. The deferred object that is created by <code>napi_create_promise()</code> is freed by <code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code>. The <code>Promise</code> object may be returned to JavaScript where it can be used in the usual fashion.</p> <p>For example, to create a promise and pass it to an asynchronous worker:</p> <pre><code class="language-c">napi_deferred deferred; napi_value promise; napi_status status; // Create the promise. status = napi_create_promise(env, &deferred, &promise); if (status != napi_ok) return NULL; // Pass the deferred to a function that performs an asynchronous action. do_something_asynchronous(deferred); // Return the promise to JS return promise; </code></pre> <p>The above function <code>do_something_asynchronous()</code> would perform its asynchronous action and then it would resolve or reject the deferred, thereby concluding the promise and freeing the deferred:</p> <pre><code class="language-c">napi_deferred deferred; napi_value undefined; napi_status status; // Create a value with which to conclude the deferred. status = napi_get_undefined(env, &undefined); if (status != napi_ok) return NULL; // Resolve or reject the promise associated with the deferred depending on // whether the asynchronous action succeeded. if (asynchronous_action_succeeded) { status = napi_resolve_deferred(env, deferred, undefined); } else { status = napi_reject_deferred(env, deferred, undefined); } if (status != napi_ok) return NULL; // At this point the deferred has been freed, so we should assign NULL to it. deferred = NULL; </code></pre> <h3>napi_create_promise<span><a class="mark" href="#n_api_napi_create_promise" id="n_api_napi_create_promise">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_create_promise(napi_env env, napi_deferred* deferred, napi_value* promise); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] deferred</code>: A newly created deferred object which can later be passed to <code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code> to resolve resp. reject the associated promise.</li> <li><code>[out] promise</code>: The JavaScript promise associated with the deferred object.</li> </ul> <p>Returns <code>napi_ok</code> if the API succeeded.</p> <p>This API creates a deferred object and a JavaScript promise.</p> <h3>napi_resolve_deferred<span><a class="mark" href="#n_api_napi_resolve_deferred" id="n_api_napi_resolve_deferred">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_resolve_deferred(napi_env env, napi_deferred deferred, napi_value resolution); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] deferred</code>: The deferred object whose associated promise to resolve.</li> <li><code>[in] resolution</code>: The value with which to resolve the promise.</li> </ul> <p>This API resolves a JavaScript promise by way of the deferred object with which it is associated. Thus, it can only be used to resolve JavaScript promises for which the corresponding deferred object is available. This effectively means that the promise must have been created using <code>napi_create_promise()</code> and the deferred object returned from that call must have been retained in order to be passed to this API.</p> <p>The deferred object is freed upon successful completion.</p> <h3>napi_reject_deferred<span><a class="mark" href="#n_api_napi_reject_deferred" id="n_api_napi_reject_deferred">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_reject_deferred(napi_env env, napi_deferred deferred, napi_value rejection); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] deferred</code>: The deferred object whose associated promise to resolve.</li> <li><code>[in] rejection</code>: The value with which to reject the promise.</li> </ul> <p>This API rejects a JavaScript promise by way of the deferred object with which it is associated. Thus, it can only be used to reject JavaScript promises for which the corresponding deferred object is available. This effectively means that the promise must have been created using <code>napi_create_promise()</code> and the deferred object returned from that call must have been retained in order to be passed to this API.</p> <p>The deferred object is freed upon successful completion.</p> <h3>napi_is_promise<span><a class="mark" href="#n_api_napi_is_promise" id="n_api_napi_is_promise">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">napi_status napi_is_promise(napi_env env, napi_value promise, bool* is_promise); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] promise</code>: The promise to examine</li> <li><code>[out] is_promise</code>: Flag indicating whether <code>promise</code> is a native promise object - that is, a promise object created by the underlying engine.</li> </ul> <h2>Script execution<span><a class="mark" href="#n_api_script_execution" id="n_api_script_execution">#</a></span></h2> <p>N-API provides an API for executing a string containing JavaScript using the underlying JavaScript engine.</p> <h3>napi_run_script<span><a class="mark" href="#n_api_napi_run_script" id="n_api_napi_run_script">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> <span>N-API version: 1</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_run_script(napi_env env, napi_value script, napi_value* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] script</code>: A JavaScript string containing the script to execute.</li> <li><code>[out] result</code>: The value resulting from having executed the script.</li> </ul> <h2>libuv event loop<span><a class="mark" href="#n_api_libuv_event_loop" id="n_api_libuv_event_loop">#</a></span></h2> <p>N-API provides a function for getting the current event loop associated with a specific <code>napi_env</code>.</p> <h3>napi_get_uv_event_loop<span><a class="mark" href="#n_api_napi_get_uv_event_loop" id="n_api_napi_get_uv_event_loop">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.10.0, v9.3.0</span> <span>N-API version: 2</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env, uv_loop_t** loop); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[out] loop</code>: The current libuv loop instance.</li> </ul> <!-- it's very convenient to have all the anchors indexed --> <!--lint disable no-unused-definitions remark-lint--> <h2>Asynchronous Thread-safe Function Calls<span><a class="mark" href="#n_api_asynchronous_thread_safe_function_calls" id="n_api_asynchronous_thread_safe_function_calls">#</a></span></h2> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>JavaScript functions can normally only be called from a native addon's main thread. If an addon creates additional threads, then N-API functions that require a <code>napi_env</code>, <code>napi_value</code>, or <code>napi_ref</code> must not be called from those threads.</p> <p>When an addon has additional threads and JavaScript functions need to be invoked based on the processing completed by those threads, those threads must communicate with the addon's main thread so that the main thread can invoke the JavaScript function on their behalf. The thread-safe function APIs provide an easy way to do this.</p> <p>These APIs provide the type <code>napi_threadsafe_function</code> as well as APIs to create, destroy, and call objects of this type. <code>napi_create_threadsafe_function()</code> creates a persistent reference to a <code>napi_value</code> that holds a JavaScript function which can be called from multiple threads. The calls happen asynchronously. This means that values with which the JavaScript callback is to be called will be placed in a queue, and, for each value in the queue, a call will eventually be made to the JavaScript function.</p> <p>Upon creation of a <code>napi_threadsafe_function</code> a <code>napi_finalize</code> callback can be provided. This callback will be invoked on the main thread when the thread-safe function is about to be destroyed. It receives the context and the finalize data given during construction, and provides an opportunity for cleaning up after the threads e.g. by calling <code>uv_thread_join()</code>. <strong>It is important that, aside from the main loop thread, there be no threads left using the thread-safe function after the finalize callback completes.</strong></p> <p>The <code>context</code> given during the call to <code>napi_create_threadsafe_function()</code> can be retrieved from any thread with a call to <code>napi_get_threadsafe_function_context()</code>.</p> <p><code>napi_call_threadsafe_function()</code> can then be used for initiating a call into JavaScript. <code>napi_call_threadsafe_function()</code> accepts a parameter which controls whether the API behaves blockingly. If set to <code>napi_tsfn_nonblocking</code>, the API behaves non-blockingly, returning <code>napi_queue_full</code> if the queue was full, preventing data from being successfully added to the queue. If set to <code>napi_tsfn_blocking</code>, the API blocks until space becomes available in the queue. <code>napi_call_threadsafe_function()</code> never blocks if the thread-safe function was created with a maximum queue size of 0.</p> <p>The actual call into JavaScript is controlled by the callback given via the <code>call_js_cb</code> parameter. <code>call_js_cb</code> is invoked on the main thread once for each value that was placed into the queue by a successful call to <code>napi_call_threadsafe_function()</code>. If such a callback is not given, a default callback will be used, and the resulting JavaScript call will have no arguments. The <code>call_js_cb</code> callback receives the JavaScript function to call as a <code>napi_value</code> in its parameters, as well as the <code>void*</code> context pointer used when creating the <code>napi_threadsafe_function</code>, and the next data pointer that was created by one of the secondary threads. The callback can then use an API such as <code>napi_call_function()</code> to call into JavaScript.</p> <p>The callback may also be invoked with <code>env</code> and <code>call_js_cb</code> both set to <code>NULL</code> to indicate that calls into JavaScript are no longer possible, while items remain in the queue that may need to be freed. This normally occurs when the Node.js process exits while there is a thread-safe function still active.</p> <p>It is not necessary to call into JavaScript via <code>napi_make_callback()</code> because N-API runs <code>call_js_cb</code> in a context appropriate for callbacks.</p> <p>Threads can be added to and removed from a <code>napi_threadsafe_function</code> object during its existence. Thus, in addition to specifying an initial number of threads upon creation, <code>napi_acquire_threadsafe_function</code> can be called to indicate that a new thread will start making use of the thread-safe function. Similarly, <code>napi_release_threadsafe_function</code> can be called to indicate that an existing thread will stop making use of the thread-safe function.</p> <p><code>napi_threadsafe_function</code> objects are destroyed when every thread which uses the object has called <code>napi_release_threadsafe_function()</code> or has received a return status of <code>napi_closing</code> in response to a call to <code>napi_call_threadsafe_function</code>. The queue is emptied before the <code>napi_threadsafe_function</code> is destroyed. It is important that <code>napi_release_threadsafe_function()</code> be the last API call made in conjunction with a given <code>napi_threadsafe_function</code>, because after the call completes, there is no guarantee that the <code>napi_threadsafe_function</code> is still allocated. For the same reason it is also important that no more use be made of a thread-safe function after receiving a return value of <code>napi_closing</code> in response to a call to <code>napi_call_threadsafe_function</code>. Data associated with the <code>napi_threadsafe_function</code> can be freed in its <code>napi_finalize</code> callback which was passed to <code>napi_create_threadsafe_function()</code>.</p> <p>Once the number of threads making use of a <code>napi_threadsafe_function</code> reaches zero, no further threads can start making use of it by calling <code>napi_acquire_threadsafe_function()</code>. In fact, all subsequent API calls associated with it, except <code>napi_release_threadsafe_function()</code>, will return an error value of <code>napi_closing</code>.</p> <p>The thread-safe function can be "aborted" by giving a value of <code>napi_tsfn_abort</code> to <code>napi_release_threadsafe_function()</code>. This will cause all subsequent APIs associated with the thread-safe function except <code>napi_release_threadsafe_function()</code> to return <code>napi_closing</code> even before its reference count reaches zero. In particular, <code>napi_call_threadsafe_function()</code> will return <code>napi_closing</code>, thus informing the threads that it is no longer possible to make asynchronous calls to the thread-safe function. This can be used as a criterion for terminating the thread. <strong>Upon receiving a return value of <code>napi_closing</code> from <code>napi_call_threadsafe_function()</code> a thread must make no further use of the thread-safe function because it is no longer guaranteed to be allocated.</strong></p> <p>Similarly to libuv handles, thread-safe functions can be "referenced" and "unreferenced". A "referenced" thread-safe function will cause the event loop on the thread on which it is created to remain alive until the thread-safe function is destroyed. In contrast, an "unreferenced" thread-safe function will not prevent the event loop from exiting. The APIs <code>napi_ref_threadsafe_function</code> and <code>napi_unref_threadsafe_function</code> exist for this purpose.</p> <h3>napi_create_threadsafe_function<span><a class="mark" href="#n_api_napi_create_threadsafe_function" id="n_api_napi_create_threadsafe_function">#</a></span></h3> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.17.0</td> <td><p>Made <code>func</code> parameter optional with custom <code>call_js_cb</code>.</p></td></tr> <tr><td>v10.6.0</td> <td><p><span>Added in: v10.6.0</span></p></td></tr> </tbody></table> </details> <span>N-API version: 4</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_create_threadsafe_function(napi_env env, napi_value func, napi_value async_resource, napi_value async_resource_name, size_t max_queue_size, size_t initial_thread_count, void* thread_finalize_data, napi_finalize thread_finalize_cb, void* context, napi_threadsafe_function_call_js call_js_cb, napi_threadsafe_function* result); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] func</code>: An optional JavaScript function to call from another thread. It must be provided if <code>NULL</code> is passed to <code>call_js_cb</code>.</li> <li><code>[in] async_resource</code>: An optional object associated with the async work that will be passed to possible <code>async_hooks</code> <a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a>.</li> <li><code>[in] async_resource_name</code>: A JavaScript string to provide an identifier for the kind of resource that is being provided for diagnostic information exposed by the <code>async_hooks</code> API.</li> <li><code>[in] max_queue_size</code>: Maximum size of the queue. <code>0</code> for no limit.</li> <li><code>[in] initial_thread_count</code>: The initial number of threads, including the main thread, which will be making use of this function.</li> <li><code>[in] thread_finalize_data</code>: Optional data to be passed to <code>thread_finalize_cb</code>.</li> <li><code>[in] thread_finalize_cb</code>: Optional function to call when the <code>napi_threadsafe_function</code> is being destroyed.</li> <li><code>[in] context</code>: Optional data to attach to the resulting <code>napi_threadsafe_function</code>.</li> <li><code>[in] call_js_cb</code>: Optional callback which calls the JavaScript function in 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 <code>undefined</code> as its <code>this</code> value.</li> <li><code>[out] result</code>: The asynchronous thread-safe JavaScript function.</li> </ul> <h3>napi_get_threadsafe_function_context<span><a class="mark" href="#n_api_napi_get_threadsafe_function_context" id="n_api_napi_get_threadsafe_function_context">#</a></span></h3> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_get_threadsafe_function_context(napi_threadsafe_function func, void** result); </code></pre> <ul> <li><code>[in] func</code>: The thread-safe function for which to retrieve the context.</li> <li><code>[out] result</code>: The location where to store the context.</li> </ul> <p>This API may be called from any thread which makes use of <code>func</code>.</p> <h3>napi_call_threadsafe_function<span><a class="mark" href="#n_api_napi_call_threadsafe_function" id="n_api_napi_call_threadsafe_function">#</a></span></h3> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_call_threadsafe_function(napi_threadsafe_function func, void* data, napi_threadsafe_function_call_mode is_blocking); </code></pre> <ul> <li><code>[in] func</code>: The asynchronous thread-safe JavaScript function to invoke.</li> <li><code>[in] data</code>: Data to send into JavaScript via the callback <code>call_js_cb</code> provided during the creation of the thread-safe JavaScript function.</li> <li><code>[in] is_blocking</code>: Flag whose value can be either <code>napi_tsfn_blocking</code> to indicate that the call should block if the queue is full or <code>napi_tsfn_nonblocking</code> to indicate that the call should return immediately with a status of <code>napi_queue_full</code> whenever the queue is full.</li> </ul> <p>This API will return <code>napi_closing</code> if <code>napi_release_threadsafe_function()</code> was called with <code>abort</code> set to <code>napi_tsfn_abort</code> from any thread. The value is only added to the queue if the API returns <code>napi_ok</code>.</p> <p>This API may be called from any thread which makes use of <code>func</code>.</p> <h3>napi_acquire_threadsafe_function<span><a class="mark" href="#n_api_napi_acquire_threadsafe_function" id="n_api_napi_acquire_threadsafe_function">#</a></span></h3> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_acquire_threadsafe_function(napi_threadsafe_function func); </code></pre> <ul> <li><code>[in] func</code>: The asynchronous thread-safe JavaScript function to start making use of.</li> </ul> <p>A thread should call this API before passing <code>func</code> to any other thread-safe function APIs to indicate that it will be making use of <code>func</code>. This prevents <code>func</code> from being destroyed when all other threads have stopped making use of it.</p> <p>This API may be called from any thread which will start making use of <code>func</code>.</p> <h3>napi_release_threadsafe_function<span><a class="mark" href="#n_api_napi_release_threadsafe_function" id="n_api_napi_release_threadsafe_function">#</a></span></h3> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_release_threadsafe_function(napi_threadsafe_function func, napi_threadsafe_function_release_mode mode); </code></pre> <ul> <li><code>[in] func</code>: The asynchronous thread-safe JavaScript function whose reference count to decrement.</li> <li><code>[in] mode</code>: Flag whose value can be either <code>napi_tsfn_release</code> to indicate that the current thread will make no further calls to the thread-safe function, or <code>napi_tsfn_abort</code> to indicate that in addition to the current thread, no other thread should make any further calls to the thread-safe function. If set to <code>napi_tsfn_abort</code>, further calls to <code>napi_call_threadsafe_function()</code> will return <code>napi_closing</code>, and no further values will be placed in the queue.</li> </ul> <p>A thread should call this API when it stops making use of <code>func</code>. Passing <code>func</code> to any thread-safe APIs after having called this API has undefined results, as <code>func</code> may have been destroyed.</p> <p>This API may be called from any thread which will stop making use of <code>func</code>.</p> <h3>napi_ref_threadsafe_function<span><a class="mark" href="#n_api_napi_ref_threadsafe_function" id="n_api_napi_ref_threadsafe_function">#</a></span></h3> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] func</code>: The thread-safe function to reference.</li> </ul> <p>This API is used to indicate that the event loop running on the main thread should not exit until <code>func</code> has been destroyed. Similar to <a href="http://docs.libuv.org/en/v1.x/handle.html#c.uv_ref"><code>uv_ref</code></a> it is also idempotent.</p> <p>This API may only be called from the main thread.</p> <h3>napi_unref_threadsafe_function<span><a class="mark" href="#n_api_napi_unref_threadsafe_function" id="n_api_napi_unref_threadsafe_function">#</a></span></h3> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <pre><code class="language-C">NAPI_EXTERN napi_status napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func); </code></pre> <ul> <li><code>[in] env</code>: The environment that the API is invoked under.</li> <li><code>[in] func</code>: The thread-safe function to unreference.</li> </ul> <p>This API is used to indicate that the event loop running on the main thread may exit before <code>func</code> is destroyed. Similar to <a href="http://docs.libuv.org/en/v1.x/handle.html#c.uv_unref"><code>uv_unref</code></a> it is also idempotent.</p> <p>This API may only be called from the main thread.</p> <h1>Child Process<span><a class="mark" href="#child_process_child_process" id="child_process_child_process">#</a></span></h1> <!--lint disable maximum-line-length--> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>child_process</code> module provides the ability to spawn child processes in a manner that is similar, but not identical, to <a href="http://man7.org/linux/man-pages/man3/popen.3.html"><code>popen(3)</code></a>. This capability is primarily provided by the <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> function:</p> <pre><code class="language-js">const { spawn } = require('child_process'); const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.log(`stderr: ${data}`); }); ls.on('close', (code) => { console.log(`child process exited with code ${code}`); }); </code></pre> <p>By default, pipes for <code>stdin</code>, <code>stdout</code>, and <code>stderr</code> are established between the parent Node.js process and the spawned child. These pipes have limited (and platform-specific) capacity. If the child process writes to stdout in excess of that limit without the output being captured, the child process will block waiting for the pipe buffer to accept more data. This is identical to the behavior of pipes in the shell. Use the <code>{ stdio: 'ignore' }</code> option if the output will not be consumed.</p> <p>The <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> method spawns the child process asynchronously, without blocking the Node.js event loop. The <a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a> function provides equivalent functionality in a synchronous manner that blocks the event loop until the spawned process either exits or is terminated.</p> <p>For convenience, the <code>child_process</code> module provides a handful of synchronous and asynchronous alternatives to <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> and <a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a>. <em>Note that each of these alternatives are implemented on top of <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> or <a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a>.</em></p> <ul> <li><a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>: spawns a shell and runs a command within that shell, passing the <code>stdout</code> and <code>stderr</code> to a callback function when complete.</li> <li><a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a>: similar to <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> except that it spawns the command directly without first spawning a shell by default.</li> <li><a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>: spawns a new Node.js process and invokes a specified module with an IPC communication channel established that allows sending messages between parent and child.</li> <li><a href="#child_process_child_process_execsync_command_options"><code>child_process.execSync()</code></a>: a synchronous version of <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> that <em>will</em> block the Node.js event loop.</li> <li><a href="#child_process_child_process_execfilesync_file_args_options"><code>child_process.execFileSync()</code></a>: a synchronous version of <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a> that <em>will</em> block the Node.js event loop.</li> </ul> <p>For certain use cases, such as automating shell scripts, the <a href="#child_process_synchronous_process_creation">synchronous counterparts</a> may be more convenient. In many cases, however, the synchronous methods can have significant impact on performance due to stalling the event loop while spawned processes complete.</p> <h2>Asynchronous Process Creation<span><a class="mark" href="#child_process_asynchronous_process_creation" id="child_process_asynchronous_process_creation">#</a></span></h2> <p>The <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>, <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>, <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>, and <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a> methods all follow the idiomatic asynchronous programming pattern typical of other Node.js APIs.</p> <p>Each of the methods returns a <a href="#child_process_child_process"><code>ChildProcess</code></a> instance. These objects implement the Node.js <a href="#events_class_eventemitter"><code>EventEmitter</code></a> API, allowing the parent process to register listener functions that are called when certain events occur during the life cycle of the child process.</p> <p>The <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> and <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a> methods additionally allow for an optional <code>callback</code> function to be specified that is invoked when the child process terminates.</p> <h3>Spawning <code>.bat</code> and <code>.cmd</code> files on Windows<span><a class="mark" href="#child_process_spawning_bat_and_cmd_files_on_windows" id="child_process_spawning_bat_and_cmd_files_on_windows">#</a></span></h3> <p>The importance of the distinction between <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> and <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a> can vary based on platform. On Unix-type operating systems (Unix, Linux, macOS) <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a> can be more efficient because it does not spawn a shell by default. On Windows, however, <code>.bat</code> and <code>.cmd</code> files are not executable on their own without a terminal, and therefore cannot be launched using <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a>. When running on Windows, <code>.bat</code> and <code>.cmd</code> files can be invoked using <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> with the <code>shell</code> option set, with <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>, or by spawning <code>cmd.exe</code> and passing the <code>.bat</code> or <code>.cmd</code> file as an argument (which is what the <code>shell</code> option and <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> do). In any case, if the script filename contains spaces it needs to be quoted.</p> <pre><code class="language-js">// On Windows Only ... const { spawn } = require('child_process'); const bat = spawn('cmd.exe', ['/c', 'my.bat']); bat.stdout.on('data', (data) => { console.log(data.toString()); }); bat.stderr.on('data', (data) => { console.log(data.toString()); }); bat.on('exit', (code) => { console.log(`Child exited with code ${code}`); }); </code></pre> <pre><code class="language-js">// OR... const { exec } = require('child_process'); exec('my.bat', (err, stdout, stderr) => { if (err) { console.error(err); return; } console.log(stdout); }); // Script with spaces in the filename: const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true }); // or: exec('"my script.cmd" a b', (err, stdout, stderr) => { // ... }); </code></pre> <h3>child_process.exec(command[, options][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/child_process.js#L150">[src]</a><span><a class="mark" href="#child_process_child_process_exec_command_options_callback" id="child_process_child_process_exec_command_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.8.0</td> <td><p>The <code>windowsHide</code> option is supported now.</p></td></tr> <tr><td>v0.1.90</td> <td><p><span>Added in: v0.1.90</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The command to run, with space-separated arguments.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Current working directory of the child process. <strong>Default:</strong> <code>null</code>.</li> <li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs. <strong>Default:</strong> <code>null</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Shell to execute the command with. See <a href="#child_process_shell_requirements">Shell Requirements</a> and <a href="#child_process_default_windows_shell">Default Windows Shell</a>. <strong>Default:</strong> <code>'/bin/sh'</code> on UNIX, <code>process.env.ComSpec</code> on Windows.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>0</code></li> <li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at <a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a>. <strong>Default:</strong> <code>200 * 1024</code>.</li> <li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>'SIGTERM'</code></li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li> <li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> called with the output when process terminates.</p> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> <li>Returns: <a href="#child_process_class_childprocess" class="type"><ChildProcess></a></li> </ul> <p>Spawns a shell then executes the <code>command</code> within that shell, buffering any generated output. The <code>command</code> string passed to the exec function is processed directly by the shell and special characters (vary based on <a href="https://en.wikipedia.org/wiki/List_of_command-line_interpreters">shell</a>) need to be dealt with accordingly:</p> <pre><code class="language-js">exec('"/path/to/test file/test.sh" arg1 arg2'); // Double quotes are used so that the space in the path is not interpreted as // multiple arguments exec('echo "The \\$HOME variable is $HOME"'); // The $HOME variable is escaped in the first instance, but not in the second </code></pre> <p><strong>Never pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.</strong></p> <p>If a <code>callback</code> function is provided, it is called with the arguments <code>(error, stdout, stderr)</code>. On success, <code>error</code> will be <code>null</code>. On error, <code>error</code> will be an instance of <a href="#errors_class_error"><code>Error</code></a>. The <code>error.code</code> property will be the exit code of the child process while <code>error.signal</code> will be set to the signal that terminated the process. Any exit code other than <code>0</code> is considered to be an error.</p> <p>The <code>stdout</code> and <code>stderr</code> arguments passed to the callback will contain the stdout and stderr output of the child process. By default, Node.js will decode the output as UTF-8 and pass strings to the callback. The <code>encoding</code> option can be used to specify the character encoding used to decode the stdout and stderr output. If <code>encoding</code> is <code>'buffer'</code>, or an unrecognized character encoding, <code>Buffer</code> objects will be passed to the callback instead.</p> <pre><code class="language-js">const { exec } = require('child_process'); exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { if (error) { console.error(`exec error: ${error}`); return; } console.log(`stdout: ${stdout}`); console.log(`stderr: ${stderr}`); }); </code></pre> <p>If <code>timeout</code> is greater than <code>0</code>, the parent will send the signal identified by the <code>killSignal</code> property (the default is <code>'SIGTERM'</code>) if the child runs longer than <code>timeout</code> milliseconds.</p> <p>Unlike the <a href="http://man7.org/linux/man-pages/man3/exec.3.html"><code>exec(3)</code></a> POSIX system call, <code>child_process.exec()</code> does not replace the existing process and uses a shell to execute the command.</p> <p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns a <code>Promise</code> for an <code>Object</code> with <code>stdout</code> and <code>stderr</code> properties. In case of an error (including any error resulting in an exit code other than 0), a rejected promise is returned, with the same <code>error</code> object given in the callback, but with an additional two properties <code>stdout</code> and <code>stderr</code>.</p> <pre><code class="language-js">const util = require('util'); const exec = util.promisify(require('child_process').exec); async function lsExample() { const { stdout, stderr } = await exec('ls'); console.log('stdout:', stdout); console.log('stderr:', stderr); } lsExample(); </code></pre> <h3>child_process.execFile(file[, args][, options][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/child_process.js#L178">[src]</a><span><a class="mark" href="#child_process_child_process_execfile_file_args_options_callback" id="child_process_child_process_execfile_file_args_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.8.0</td> <td><p>The <code>windowsHide</code> option is supported now.</p></td></tr> <tr><td>v0.1.91</td> <td><p><span>Added in: v0.1.91</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name or path of the executable file to run.</li> <li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Current working directory of the child process.</li> <li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>0</code></li> <li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at <a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a>. <strong>Default:</strong> <code>200 * 1024</code>.</li> <li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>'SIGTERM'</code></li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li> <li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li> <li><code>windowsVerbatimArguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> No quoting or escaping of arguments is done on Windows. Ignored on Unix. <strong>Default:</strong> <code>false</code>.</li> <li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses <code>'/bin/sh'</code> on UNIX, and <code>process.env.ComSpec</code> on Windows. A different shell can be specified as a string. See <a href="#child_process_shell_requirements">Shell Requirements</a> and <a href="#child_process_default_windows_shell">Default Windows Shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called with the output when process terminates.</p> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> <li>Returns: <a href="#child_process_class_childprocess" class="type"><ChildProcess></a></li> </ul> <p>The <code>child_process.execFile()</code> function is similar to <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> except that it does not spawn a shell by default. Rather, the specified executable <code>file</code> is spawned directly as a new process making it slightly more efficient than <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>.</p> <p>The same options as <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> are supported. Since a shell is not spawned, behaviors such as I/O redirection and file globbing are not supported.</p> <pre><code class="language-js">const { execFile } = require('child_process'); const child = execFile('node', ['--version'], (error, stdout, stderr) => { if (error) { throw error; } console.log(stdout); }); </code></pre> <p>The <code>stdout</code> and <code>stderr</code> arguments passed to the callback will contain the stdout and stderr output of the child process. By default, Node.js will decode the output as UTF-8 and pass strings to the callback. The <code>encoding</code> option can be used to specify the character encoding used to decode the stdout and stderr output. If <code>encoding</code> is <code>'buffer'</code>, or an unrecognized character encoding, <code>Buffer</code> objects will be passed to the callback instead.</p> <p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns a <code>Promise</code> for an <code>Object</code> with <code>stdout</code> and <code>stderr</code> properties. In case of an error (including any error resulting in an exit code other than 0), a rejected promise is returned, with the same <code>error</code> object given in the callback, but with an additional two properties <code>stdout</code> and <code>stderr</code>.</p> <pre><code class="language-js">const util = require('util'); const execFile = util.promisify(require('child_process').execFile); async function getVersion() { const { stdout } = await execFile('node', ['--version']); console.log(stdout); } getVersion(); </code></pre> <p><strong>If the <code>shell</code> option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.</strong></p> <h3>child_process.fork(modulePath[, args][, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/child_process.js#L61">[src]</a><span><a class="mark" href="#child_process_child_process_fork_modulepath_args_options" id="child_process_child_process_fork_modulepath_args_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>stdio</code> option can now be a string.</p></td></tr> <tr><td>v6.4.0</td> <td><p>The <code>stdio</code> option is supported now.</p></td></tr> <tr><td>v0.5.0</td> <td><p><span>Added in: v0.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>modulePath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The module to run in the child.</li> <li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Current working directory of the child process.</li> <li><code>detached</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Prepare child to run independently of its parent process. Specific behavior depends on the platform, see <a href="#child_process_options_detached"><code>options.detached</code></a>).</li> <li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs.</li> <li><code>execPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Executable used to create the child process.</li> <li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments passed to the executable. <strong>Default:</strong> <code>process.execArgv</code>.</li> <li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the <code>'pipe'</code> and <code>'inherit'</code> options for <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>'s <a href="#child_process_options_stdio"><code>stdio</code></a> for more details. <strong>Default:</strong> <code>false</code>.</li> <li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>'s <a href="#child_process_options_stdio"><code>stdio</code></a>. When this option is provided, it overrides <code>silent</code>. If the array variant is used, it must contain exactly one item with value <code>'ipc'</code> or an error will be thrown. For instance <code>[0, 1, 2, 'ipc']</code>.</li> <li><code>windowsVerbatimArguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> No quoting or escaping of arguments is done on Windows. Ignored on Unix. <strong>Default:</strong> <code>false</code>.</li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li> </ul> </li> <li>Returns: <a href="#child_process_class_childprocess" class="type"><ChildProcess></a></li> </ul> <p>The <code>child_process.fork()</code> method is a special case of <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> used specifically to spawn new Node.js processes. Like <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>, a <a href="#child_process_child_process"><code>ChildProcess</code></a> object is returned. The returned <a href="#child_process_child_process"><code>ChildProcess</code></a> will have an additional communication channel built-in that allows messages to be passed back and forth between the parent and child. See <a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>subprocess.send()</code></a> for details.</p> <p>It is important to keep in mind that spawned Node.js child processes are independent of the parent with exception of the IPC communication channel that is established between the two. Each process has its own memory, with their own V8 instances. Because of the additional resource allocations required, spawning a large number of child Node.js processes is not recommended.</p> <p>By default, <code>child_process.fork()</code> will spawn new Node.js instances using the <a href="#process_process_execpath"><code>process.execPath</code></a> of the parent process. The <code>execPath</code> property in the <code>options</code> object allows for an alternative execution path to be used.</p> <p>Node.js processes launched with a custom <code>execPath</code> will communicate with the parent process using the file descriptor (fd) identified using the environment variable <code>NODE_CHANNEL_FD</code> on the child process.</p> <p>Unlike the <a href="http://man7.org/linux/man-pages/man2/fork.2.html"><code>fork(2)</code></a> POSIX system call, <code>child_process.fork()</code> does not clone the current process.</p> <p>The <code>shell</code> option available in <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> is not supported by <code>child_process.fork()</code> and will be ignored if set.</p> <h3>child_process.spawn(command[, args][, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/child_process.js#L544">[src]</a><span><a class="mark" href="#child_process_child_process_spawn_command_args_options" id="child_process_child_process_spawn_command_args_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.8.0</td> <td><p>The <code>windowsHide</code> option is supported now.</p></td></tr> <tr><td>v6.4.0</td> <td><p>The <code>argv0</code> option is supported now.</p></td></tr> <tr><td>v5.7.0</td> <td><p>The <code>shell</code> option is supported now.</p></td></tr> <tr><td>v0.1.90</td> <td><p><span>Added in: v0.1.90</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The command to run.</li> <li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Current working directory of the child process.</li> <li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs.</li> <li><code>argv0</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Explicitly set the value of <code>argv[0]</code> sent to the child process. This will be set to <code>command</code> if not specified.</li> <li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Child's stdio configuration (see <a href="#child_process_options_stdio"><code>options.stdio</code></a>).</li> <li><code>detached</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Prepare child to run independently of its parent process. Specific behavior depends on the platform, see <a href="#child_process_options_detached"><code>options.detached</code></a>).</li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li> <li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses <code>'/bin/sh'</code> on UNIX, and <code>process.env.ComSpec</code> on Windows. A different shell can be specified as a string. See <a href="#child_process_shell_requirements">Shell Requirements</a> and <a href="#child_process_default_windows_shell">Default Windows Shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li> <li><code>windowsVerbatimArguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to <code>true</code> automatically when <code>shell</code> is specified. <strong>Default:</strong> <code>false</code>.</li> <li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="#child_process_class_childprocess" class="type"><ChildProcess></a></li> </ul> <p>The <code>child_process.spawn()</code> method spawns a new process using the given <code>command</code>, with command line arguments in <code>args</code>. If omitted, <code>args</code> defaults to an empty array.</p> <p><strong>If the <code>shell</code> option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.</strong></p> <p>A third argument may be used to specify additional options, with these defaults:</p> <pre><code class="language-js">const defaults = { cwd: undefined, env: process.env }; </code></pre> <p>Use <code>cwd</code> to specify the working directory from which the process is spawned. If not given, the default is to inherit the current working directory.</p> <p>Use <code>env</code> to specify environment variables that will be visible to the new process, the default is <a href="#process_process_env"><code>process.env</code></a>.</p> <p><code>undefined</code> values in <code>env</code> will be ignored.</p> <p>Example of running <code>ls -lh /usr</code>, capturing <code>stdout</code>, <code>stderr</code>, and the exit code:</p> <pre><code class="language-js">const { spawn } = require('child_process'); const ls = spawn('ls', ['-lh', '/usr']); ls.stdout.on('data', (data) => { console.log(`stdout: ${data}`); }); ls.stderr.on('data', (data) => { console.log(`stderr: ${data}`); }); ls.on('close', (code) => { console.log(`child process exited with code ${code}`); }); </code></pre> <p>Example: A very elaborate way to run <code>ps ax | grep ssh</code></p> <pre><code class="language-js">const { spawn } = require('child_process'); const ps = spawn('ps', ['ax']); const grep = spawn('grep', ['ssh']); ps.stdout.on('data', (data) => { grep.stdin.write(data); }); ps.stderr.on('data', (data) => { console.log(`ps stderr: ${data}`); }); ps.on('close', (code) => { if (code !== 0) { console.log(`ps process exited with code ${code}`); } grep.stdin.end(); }); grep.stdout.on('data', (data) => { console.log(data.toString()); }); grep.stderr.on('data', (data) => { console.log(`grep stderr: ${data}`); }); grep.on('close', (code) => { if (code !== 0) { console.log(`grep process exited with code ${code}`); } }); </code></pre> <p>Example of checking for failed <code>spawn</code>:</p> <pre><code class="language-js">const { spawn } = require('child_process'); const subprocess = spawn('bad_command'); subprocess.on('error', (err) => { console.log('Failed to start subprocess.'); }); </code></pre> <p>Certain platforms (macOS, Linux) will use the value of <code>argv[0]</code> for the process title while others (Windows, SunOS) will use <code>command</code>.</p> <p>Node.js currently overwrites <code>argv[0]</code> with <code>process.execPath</code> on startup, so <code>process.argv[0]</code> in a Node.js child process will not match the <code>argv0</code> parameter passed to <code>spawn</code> from the parent, retrieve it with the <code>process.argv0</code> property instead.</p> <h4>options.detached<span><a class="mark" href="#child_process_options_detached" id="child_process_options_detached">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.7.10</span> </div> <p>On Windows, setting <code>options.detached</code> to <code>true</code> makes it possible for the child process to continue running after the parent exits. The child will have its own console window. <em>Once enabled for a child process, it cannot be disabled</em>.</p> <p>On non-Windows platforms, if <code>options.detached</code> is set to <code>true</code>, the child process will be made the leader of a new process group and session. Note that child processes may continue running after the parent exits regardless of whether they are detached or not. See <a href="http://man7.org/linux/man-pages/man2/setsid.2.html"><code>setsid(2)</code></a> for more information.</p> <p>By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given <code>subprocess</code> to exit, use the <code>subprocess.unref()</code> method. Doing so will cause the parent's event loop to not include the child in its reference count, allowing the parent to exit independently of the child, unless there is an established IPC channel between the child and the parent.</p> <p>When using the <code>detached</code> option to start a long-running process, the process will not stay running in the background after the parent exits unless it is provided with a <code>stdio</code> configuration that is not connected to the parent. If the parent's <code>stdio</code> is inherited, the child will remain attached to the controlling terminal.</p> <p>Example of a long-running process, by detaching and also ignoring its parent <code>stdio</code> file descriptors, in order to ignore the parent's termination:</p> <pre><code class="language-js">const { spawn } = require('child_process'); const subprocess = spawn(process.argv[0], ['child_program.js'], { detached: true, stdio: 'ignore' }); subprocess.unref(); </code></pre> <p>Alternatively one can redirect the child process' output into files:</p> <pre><code class="language-js">const fs = require('fs'); const { spawn } = require('child_process'); const out = fs.openSync('./out.log', 'a'); const err = fs.openSync('./out.log', 'a'); const subprocess = spawn('prg', [], { detached: true, stdio: [ 'ignore', out, err ] }); subprocess.unref(); </code></pre> <h4>options.stdio<span><a class="mark" href="#child_process_options_stdio" id="child_process_options_stdio">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v3.3.1</td> <td><p>The value <code>0</code> is now accepted as a file descriptor.</p></td></tr> <tr><td>v0.7.10</td> <td><p><span>Added in: v0.7.10</span></p></td></tr> </tbody></table> </details> </div> <p>The <code>options.stdio</code> option is used to configure the pipes that are established between the parent and child process. By default, the child's stdin, stdout, and stderr are redirected to corresponding <a href="#child_process_subprocess_stdin"><code>subprocess.stdin</code></a>, <a href="#child_process_subprocess_stdout"><code>subprocess.stdout</code></a>, and <a href="#child_process_subprocess_stderr"><code>subprocess.stderr</code></a> streams on the <a href="#child_process_child_process"><code>ChildProcess</code></a> object. This is equivalent to setting the <code>options.stdio</code> equal to <code>['pipe', 'pipe', 'pipe']</code>.</p> <p>For convenience, <code>options.stdio</code> may be one of the following strings:</p> <ul> <li><code>'pipe'</code> - equivalent to <code>['pipe', 'pipe', 'pipe']</code> (the default)</li> <li><code>'ignore'</code> - equivalent to <code>['ignore', 'ignore', 'ignore']</code></li> <li><code>'inherit'</code> - equivalent to <code>['inherit', 'inherit', 'inherit']</code> or <code>[0, 1, 2]</code></li> </ul> <p>Otherwise, the value of <code>options.stdio</code> is an array where each index corresponds to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout, and stderr, respectively. Additional fds can be specified to create additional pipes between the parent and child. The value is one of the following:</p> <ol> <li> <p><code>'pipe'</code> - Create a pipe between the child process and the parent process. The parent end of the pipe is exposed to the parent as a property on the <code>child_process</code> object as <a href="#child_process_options_stdio"><code>subprocess.stdio[fd]</code></a>. Pipes created for fds 0 - 2 are also available as <a href="#child_process_subprocess_stdin"><code>subprocess.stdin</code></a>, <a href="#child_process_subprocess_stdout"><code>subprocess.stdout</code></a> and <a href="#child_process_subprocess_stderr"><code>subprocess.stderr</code></a>, respectively.</p> </li> <li> <p><code>'ipc'</code> - Create an IPC channel for passing messages/file descriptors between parent and child. A <a href="#child_process_child_process"><code>ChildProcess</code></a> may have at most <em>one</em> IPC stdio file descriptor. Setting this option enables the <a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>subprocess.send()</code></a> method. If the child is a Node.js process, the presence of an IPC channel will enable <a href="#process_process_send_message_sendhandle_options_callback"><code>process.send()</code></a> and <a href="#process_process_disconnect"><code>process.disconnect()</code></a> methods, as well as <a href="#process_event_disconnect"><code>'disconnect'</code></a> and <a href="#process_event_message"><code>'message'</code></a> events within the child.</p> <p>Accessing the IPC channel fd in any way other than <a href="#process_process_send_message_sendhandle_options_callback"><code>process.send()</code></a> or using the IPC channel with a child process that is not a Node.js instance is not supported.</p> </li> <li> <p><code>'ignore'</code> - Instructs Node.js to ignore the fd in the child. While Node.js will always open fds 0 - 2 for the processes it spawns, setting the fd to <code>'ignore'</code> will cause Node.js to open <code>/dev/null</code> and attach it to the child's fd.</p> </li> <li> <p><code>'inherit'</code> - Pass through the corresponding stdio stream to/from the parent process. In the first three positions, this is equivalent to <code>process.stdin</code>, <code>process.stdout</code>, and <code>process.stderr</code>, respectively. In any other position, equivalent to <code>'ignore'</code>.</p> </li> <li> <p><a href="#stream_stream" class="type"><Stream></a> object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process. The stream's underlying file descriptor is duplicated in the child process to the fd that corresponds to the index in the <code>stdio</code> array. Note that the stream must have an underlying descriptor (file streams do not until the <code>'open'</code> event has occurred).</p> </li> <li> <p>Positive integer - The integer value is interpreted as a file descriptor that is currently open in the parent process. It is shared with the child process, similar to how <a href="#stream_stream" class="type"><Stream></a> objects can be shared. Passing sockets is not supported on Windows.</p> </li> <li> <p><code>null</code>, <code>undefined</code> - Use default value. For stdio fds 0, 1, and 2 (in other words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the default is <code>'ignore'</code>.</p> </li> </ol> <pre><code class="language-js">const { spawn } = require('child_process'); // Child will use parent's stdios spawn('prg', [], { stdio: 'inherit' }); // Spawn child sharing only stderr spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] }); // Open an extra fd=4, to interact with programs presenting a // startd-style interface. spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] }); </code></pre> <p><em>It is worth noting that when an IPC channel is established between the parent and child processes, and the child is a Node.js process, the child is launched with the IPC channel unreferenced (using <code>unref()</code>) until the child registers an event handler for the <a href="#process_event_disconnect"><code>'disconnect'</code></a> event or the <a href="#process_event_message"><code>'message'</code></a> event. This allows the child to exit normally without the process being held open by the open IPC channel.</em></p> <p>On UNIX-like operating systems, the <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> method performs memory operations synchronously before decoupling the event loop from the child. Applications with a large memory footprint may find frequent <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> calls to be a bottleneck. For more information, see <a href="https://bugs.chromium.org/p/v8/issues/detail?id=7381">V8 issue 7381</a>.</p> <p>See also: <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> and <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>.</p> <h2>Synchronous Process Creation<span><a class="mark" href="#child_process_synchronous_process_creation" id="child_process_synchronous_process_creation">#</a></span></h2> <p>The <a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a>, <a href="#child_process_child_process_execsync_command_options"><code>child_process.execSync()</code></a>, and <a href="#child_process_child_process_execfilesync_file_args_options"><code>child_process.execFileSync()</code></a> methods are <strong>synchronous</strong> and <strong>WILL</strong> block the Node.js event loop, pausing execution of any additional code until the spawned process exits.</p> <p>Blocking calls like these are mostly useful for simplifying general-purpose scripting tasks and for simplifying the loading/processing of application configuration at startup.</p> <h3>child_process.execFileSync(file[, args][, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/child_process.js#L638">[src]</a><span><a class="mark" href="#child_process_child_process_execfilesync_file_args_options" id="child_process_child_process_execfilesync_file_args_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>The <code>input</code> option can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr> <tr><td>v8.8.0</td> <td><p>The <code>windowsHide</code> option is supported now.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>input</code> option can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v6.2.1, v4.5.0</td> <td><p>The <code>encoding</code> option can now explicitly be set to <code>buffer</code>.</p></td></tr> <tr><td>v0.11.12</td> <td><p><span>Added in: v0.11.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name or path of the executable file to run.</li> <li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Current working directory of the child process.</li> <li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> The value which will be passed as stdin to the spawned process. Supplying this value will override <code>stdio[0]</code>.</li> <li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Child's stdio configuration. <code>stderr</code> by default will be output to the parent process' stderr unless <code>stdio</code> is specified. <strong>Default:</strong> <code>'pipe'</code>.</li> <li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs.</li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> In milliseconds the maximum amount of time the process is allowed to run. <strong>Default:</strong> <code>undefined</code>.</li> <li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The signal value to be used when the spawned process will be killed. <strong>Default:</strong> <code>'SIGTERM'</code>.</li> <li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated. See caveat at <a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a>. <strong>Default:</strong> <code>200 * 1024</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding used for all stdio inputs and outputs. <strong>Default:</strong> <code>'buffer'</code>.</li> <li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li> <li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses <code>'/bin/sh'</code> on UNIX, and <code>process.env.ComSpec</code> on Windows. A different shell can be specified as a string. See <a href="#child_process_shell_requirements">Shell Requirements</a> and <a href="#child_process_default_windows_shell">Default Windows Shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li> </ul> </li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The stdout from the command.</li> </ul> <p>The <code>child_process.execFileSync()</code> method is generally identical to <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a> with the exception that the method will not return until the child process has fully closed. When a timeout has been encountered and <code>killSignal</code> is sent, the method won't return until the process has completely exited.</p> <p>If the child process intercepts and handles the <code>SIGTERM</code> signal and does not exit, the parent process will still wait until the child process has exited.</p> <p>If the process times out or has a non-zero exit code, this method <strong><em>will</em></strong> throw an <a href="#errors_class_error"><code>Error</code></a> that will include the full result of the underlying <a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a>.</p> <p><strong>If the <code>shell</code> option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.</strong></p> <h3>child_process.execSync(command[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/child_process.js#L657">[src]</a><span><a class="mark" href="#child_process_child_process_execsync_command_options" id="child_process_child_process_execsync_command_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>The <code>input</code> option can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr> <tr><td>v8.8.0</td> <td><p>The <code>windowsHide</code> option is supported now.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>input</code> option can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v0.11.12</td> <td><p><span>Added in: v0.11.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The command to run.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Current working directory of the child process.</li> <li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> The value which will be passed as stdin to the spawned process. Supplying this value will override <code>stdio[0]</code>.</li> <li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Child's stdio configuration. <code>stderr</code> by default will be output to the parent process' stderr unless <code>stdio</code> is specified. <strong>Default:</strong> <code>'pipe'</code>.</li> <li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs.</li> <li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Shell to execute the command with. See <a href="#child_process_shell_requirements">Shell Requirements</a> and <a href="#child_process_default_windows_shell">Default Windows Shell</a>. <strong>Default:</strong> <code>'/bin/sh'</code> on UNIX, <code>process.env.ComSpec</code> on Windows.</li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> In milliseconds the maximum amount of time the process is allowed to run. <strong>Default:</strong> <code>undefined</code>.</li> <li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The signal value to be used when the spawned process will be killed. <strong>Default:</strong> <code>'SIGTERM'</code>.</li> <li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at <a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a>. <strong>Default:</strong> <code>200 * 1024</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding used for all stdio inputs and outputs. <strong>Default:</strong> <code>'buffer'</code>.</li> <li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The stdout from the command.</li> </ul> <p>The <code>child_process.execSync()</code> method is generally identical to <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> with the exception that the method will not return until the child process has fully closed. When a timeout has been encountered and <code>killSignal</code> is sent, the method won't return until the process has completely exited. <em>Note that if the child process intercepts and handles the <code>SIGTERM</code> signal and doesn't exit, the parent process will wait until the child process has exited.</em></p> <p>If the process times out or has a non-zero exit code, this method <strong><em>will</em></strong> throw. The <a href="#errors_class_error"><code>Error</code></a> object will contain the entire result from <a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a>.</p> <p><strong>Never pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.</strong></p> <h3>child_process.spawnSync(command[, args][, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/child_process.js#L567">[src]</a><span><a class="mark" href="#child_process_child_process_spawnsync_command_args_options" id="child_process_child_process_spawnsync_command_args_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>The <code>input</code> option can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr> <tr><td>v8.8.0</td> <td><p>The <code>windowsHide</code> option is supported now.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>input</code> option can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v6.2.1, v4.5.0</td> <td><p>The <code>encoding</code> option can now explicitly be set to <code>buffer</code>.</p></td></tr> <tr><td>v5.7.0</td> <td><p>The <code>shell</code> option is supported now.</p></td></tr> <tr><td>v0.11.12</td> <td><p><span>Added in: v0.11.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The command to run.</li> <li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Current working directory of the child process.</li> <li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> The value which will be passed as stdin to the spawned process. Supplying this value will override <code>stdio[0]</code>.</li> <li><code>argv0</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Explicitly set the value of <code>argv[0]</code> sent to the child process. This will be set to <code>command</code> if not specified.</li> <li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Child's stdio configuration.</li> <li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Environment key-value pairs.</li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> In milliseconds the maximum amount of time the process is allowed to run. <strong>Default:</strong> <code>undefined</code>.</li> <li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The signal value to be used when the spawned process will be killed. <strong>Default:</strong> <code>'SIGTERM'</code>.</li> <li><code>maxBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Largest amount of data in bytes allowed on stdout or stderr. If exceeded, the child process is terminated and any output is truncated. See caveat at <a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a>. <strong>Default:</strong> <code>200 * 1024</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding used for all stdio inputs and outputs. <strong>Default:</strong> <code>'buffer'</code>.</li> <li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses <code>'/bin/sh'</code> on UNIX, and <code>process.env.ComSpec</code> on Windows. A different shell can be specified as a string. See <a href="#child_process_shell_requirements">Shell Requirements</a> and <a href="#child_process_default_windows_shell">Default Windows Shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li> <li><code>windowsVerbatimArguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to <code>true</code> automatically when <code>shell</code> is specified. <strong>Default:</strong> <code>false</code>.</li> <li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the subprocess console window that would normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li> <p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Pid of the child process.</li> <li><code>output</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Array of results from stdio output.</li> <li><code>stdout</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The contents of <code>output[1]</code>.</li> <li><code>stderr</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The contents of <code>output[2]</code>.</li> <li><code>status</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The exit code of the subprocess, or <code>null</code> if the subprocess terminated due to a signal.</li> <li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The signal used to kill the subprocess, or <code>null</code> if the subprocess did not terminate due to a signal.</li> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The error object if the child process failed or timed out.</li> </ul> </li> </ul> <p>The <code>child_process.spawnSync()</code> method is generally identical to <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> with the exception that the function will not return until the child process has fully closed. When a timeout has been encountered and <code>killSignal</code> is sent, the method won't return until the process has completely exited. Note that if the process intercepts and handles the <code>SIGTERM</code> signal and doesn't exit, the parent process will wait until the child process has exited.</p> <p><strong>If the <code>shell</code> option is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.</strong></p> <h2>Class: ChildProcess<span><a class="mark" href="#child_process_class_childprocess" id="child_process_class_childprocess">#</a></span></h2> <div class="api_metadata"> <span>Added in: v2.2.0</span> </div> <p>Instances of the <code>ChildProcess</code> class are <a href="#events_class_eventemitter"><code>EventEmitters</code></a> that represent spawned child processes.</p> <p>Instances of <code>ChildProcess</code> are not intended to be created directly. Rather, use the <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>, <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>, <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a>, or <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a> methods to create instances of <code>ChildProcess</code>.</p> <h3>Event: 'close'<span><a class="mark" href="#child_process_event_close" id="child_process_event_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The exit code if the child exited on its own.</li> <li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The signal by which the child process was terminated.</li> </ul> <p>The <code>'close'</code> event is emitted when the stdio streams of a child process have been closed. This is distinct from the <a href="#child_process_event_exit"><code>'exit'</code></a> event, since multiple processes might share the same stdio streams.</p> <h3>Event: 'disconnect'<span><a class="mark" href="#child_process_event_disconnect" id="child_process_event_disconnect">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.2</span> </div> <p>The <code>'disconnect'</code> event is emitted after calling the <a href="#child_process_subprocess_disconnect"><code>subprocess.disconnect()</code></a> method in parent process or <a href="#process_process_disconnect"><code>process.disconnect()</code></a> in child process. After disconnecting it is no longer possible to send or receive messages, and the <a href="#child_process_subprocess_connected"><code>subprocess.connected</code></a> property is <code>false</code>.</p> <h3>Event: 'error'<span><a class="mark" href="#child_process_event_error" id="child_process_event_error">#</a></span></h3> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The error.</li> </ul> <p>The <code>'error'</code> event is emitted whenever:</p> <ol> <li>The process could not be spawned, or</li> <li>The process could not be killed, or</li> <li>Sending a message to the child process failed.</li> </ol> <p>The <code>'exit'</code> event may or may not fire after an error has occurred. When listening to both the <code>'exit'</code> and <code>'error'</code> events, it is important to guard against accidentally invoking handler functions multiple times.</p> <p>See also <a href="#child_process_subprocess_kill_signal"><code>subprocess.kill()</code></a> and <a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>subprocess.send()</code></a>.</p> <h3>Event: 'exit'<span><a class="mark" href="#child_process_event_exit" id="child_process_event_exit">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The exit code if the child exited on its own.</li> <li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The signal by which the child process was terminated.</li> </ul> <p>The <code>'exit'</code> event is emitted after the child process ends. If the process exited, <code>code</code> is the final exit code of the process, otherwise <code>null</code>. If the process terminated due to receipt of a signal, <code>signal</code> is the string name of the signal, otherwise <code>null</code>. One of the two will always be non-null.</p> <p>Note that when the <code>'exit'</code> event is triggered, child process stdio streams might still be open.</p> <p>Also, note that Node.js establishes signal handlers for <code>SIGINT</code> and <code>SIGTERM</code> and Node.js processes will not terminate immediately due to receipt of those signals. Rather, Node.js will perform a sequence of cleanup actions and then will re-raise the handled signal.</p> <p>See <a href="http://man7.org/linux/man-pages/man2/waitpid.2.html"><code>waitpid(2)</code></a>.</p> <h3>Event: 'message'<span><a class="mark" href="#child_process_event_message" id="child_process_event_message">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A parsed JSON object or primitive value.</li> <li><code>sendHandle</code> <a href="#net_server_listen_handle_backlog_callback" class="type"><Handle></a> A <a href="#net_class_net_socket"><code>net.Socket</code></a> or <a href="#net_class_net_server"><code>net.Server</code></a> object, or undefined.</li> </ul> <p>The <code>'message'</code> event is triggered when a child process uses <a href="#process_process_send_message_sendhandle_options_callback"><code>process.send()</code></a> to send messages.</p> <p>The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent.</p> <h3>subprocess.channel<span><a class="mark" href="#child_process_subprocess_channel" id="child_process_subprocess_channel">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.1.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A pipe representing the IPC channel to the child process.</li> </ul> <p>The <code>subprocess.channel</code> property is a reference to the child's IPC channel. If no IPC channel currently exists, this property is <code>undefined</code>.</p> <h3>subprocess.connected<span><a class="mark" href="#child_process_subprocess_connected" id="child_process_subprocess_connected">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.2</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>false</code> after <code>subprocess.disconnect()</code> is called.</li> </ul> <p>The <code>subprocess.connected</code> property indicates whether it is still possible to send and receive messages from a child process. When <code>subprocess.connected</code> is <code>false</code>, it is no longer possible to send or receive messages.</p> <h3>subprocess.disconnect()<span><a class="mark" href="#child_process_subprocess_disconnect" id="child_process_subprocess_disconnect">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.2</span> </div> <p>Closes the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive. After calling this method the <code>subprocess.connected</code> and <code>process.connected</code> properties in both the parent and child (respectively) will be set to <code>false</code>, and it will be no longer possible to pass messages between the processes.</p> <p>The <code>'disconnect'</code> event will be emitted when there are no messages in the process of being received. This will most often be triggered immediately after calling <code>subprocess.disconnect()</code>.</p> <p>Note that when the child process is a Node.js instance (e.g. spawned using <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>), the <code>process.disconnect()</code> method can be invoked within the child process to close the IPC channel as well.</p> <h3>subprocess.kill([signal])<span><a class="mark" href="#child_process_subprocess_kill_signal" id="child_process_subprocess_kill_signal">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>subprocess.kill()</code> method sends a signal to the child process. If no argument is given, the process will be sent the <code>'SIGTERM'</code> signal. See <a href="http://man7.org/linux/man-pages/man7/signal.7.html"><code>signal(7)</code></a> for a list of available signals.</p> <pre><code class="language-js">const { spawn } = require('child_process'); const grep = spawn('grep', ['ssh']); grep.on('close', (code, signal) => { console.log( `child process terminated due to receipt of signal ${signal}`); }); // Send SIGHUP to process grep.kill('SIGHUP'); </code></pre> <p>The <a href="#child_process_child_process"><code>ChildProcess</code></a> object may emit an <a href="#child_process_event_error"><code>'error'</code></a> event if the signal cannot be delivered. Sending a signal to a child process that has already exited is not an error but may have unforeseen consequences. Specifically, if the process identifier (PID) has been reassigned to another process, the signal will be delivered to that process instead which can have unexpected results.</p> <p>Note that while the function is called <code>kill</code>, the signal delivered to the child process may not actually terminate the process.</p> <p>See <a href="http://man7.org/linux/man-pages/man2/kill.2.html"><code>kill(2)</code></a> for reference.</p> <p>On Linux, child processes of child processes will not be terminated when attempting to kill their parent. This is likely to happen when running a new process in a shell or with the use of the <code>shell</code> option of <code>ChildProcess</code>:</p> <pre><code class="language-js">'use strict'; const { spawn } = require('child_process'); const subprocess = spawn( 'sh', [ '-c', `node -e "setInterval(() => { console.log(process.pid, 'is alive') }, 500);"` ], { stdio: ['inherit', 'inherit', 'inherit'] } ); setTimeout(() => { subprocess.kill(); // does not terminate the node process in the shell }, 2000); </code></pre> <h3>subprocess.killed<span><a class="mark" href="#child_process_subprocess_killed" id="child_process_subprocess_killed">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.10</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>true</code> after <code>subprocess.kill()</code> is used to successfully send a signal to the child process.</li> </ul> <p>The <code>subprocess.killed</code> property indicates whether the child process successfully received a signal from <code>subprocess.kill()</code>. The <code>killed</code> property does not indicate that the child process has been terminated.</p> <h3>subprocess.pid<span><a class="mark" href="#child_process_subprocess_pid" id="child_process_subprocess_pid">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Returns the process identifier (PID) of the child process.</p> <pre><code class="language-js">const { spawn } = require('child_process'); const grep = spawn('grep', ['ssh']); console.log(`Spawned child pid: ${grep.pid}`); grep.stdin.end(); </code></pre> <h3>subprocess.ref()<span><a class="mark" href="#child_process_subprocess_ref" id="child_process_subprocess_ref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.10</span> </div> <p>Calling <code>subprocess.ref()</code> after making a call to <code>subprocess.unref()</code> will restore the removed reference count for the child process, forcing the parent to wait for the child to exit before exiting itself.</p> <pre><code class="language-js">const { spawn } = require('child_process'); const subprocess = spawn(process.argv[0], ['child_program.js'], { detached: true, stdio: 'ignore' }); subprocess.unref(); subprocess.ref(); </code></pre> <h3>subprocess.send(message[, sendHandle[, options]][, callback])<span><a class="mark" href="#child_process_subprocess_send_message_sendhandle_options_callback" id="child_process_subprocess_send_message_sendhandle_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v5.8.0</td> <td><p>The <code>options</code> parameter, and the <code>keepOpen</code> option in particular, is supported now.</p></td></tr> <tr><td>v5.0.0</td> <td><p>This method returns a boolean for flow control now.</p></td></tr> <tr><td>v4.0.0</td> <td><p>The <code>callback</code> parameter is supported now.</p></td></tr> <tr><td>v0.5.9</td> <td><p><span>Added in: v0.5.9</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>sendHandle</code> <a href="#net_server_listen_handle_backlog_callback" class="type"><Handle></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <code>options</code> argument, if present, is an object used to parameterize the sending of certain types of handles. <code>options</code> supports the following properties:</p> <ul> <li><code>keepOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> A value that can be used when passing instances of <code>net.Socket</code>. When <code>true</code>, the socket is kept open in the sending process. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>When an IPC channel has been established between the parent and child ( i.e. when using <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>), the <code>subprocess.send()</code> method can be used to send messages to the child process. When the child process is a Node.js instance, these messages can be received via the <a href="#process_event_message"><code>'message'</code></a> event.</p> <p>The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent.</p> <p>For example, in the parent script:</p> <pre><code class="language-js">const cp = require('child_process'); const n = cp.fork(`${__dirname}/sub.js`); n.on('message', (m) => { console.log('PARENT got message:', m); }); // Causes the child to print: CHILD got message: { hello: 'world' } n.send({ hello: 'world' }); </code></pre> <p>And then the child script, <code>'sub.js'</code> might look like this:</p> <pre><code class="language-js">process.on('message', (m) => { console.log('CHILD got message:', m); }); // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } process.send({ foo: 'bar', baz: NaN }); </code></pre> <p>Child Node.js processes will have a <a href="#process_process_send_message_sendhandle_options_callback"><code>process.send()</code></a> method of their own that allows the child to send messages back to the parent.</p> <p>There is a special case when sending a <code>{cmd: 'NODE_foo'}</code> message. Messages containing a <code>NODE_</code> prefix in the <code>cmd</code> property are reserved for use within Node.js core and will not be emitted in the child's <a href="#process_event_message"><code>'message'</code></a> event. Rather, such messages are emitted using the <code>'internalMessage'</code> event and are consumed internally by Node.js. Applications should avoid using such messages or listening for <code>'internalMessage'</code> events as it is subject to change without notice.</p> <p>The optional <code>sendHandle</code> argument that may be passed to <code>subprocess.send()</code> is for passing a TCP server or socket object to the child process. The child will receive the object as the second argument passed to the callback function registered on the <a href="#process_event_message"><code>'message'</code></a> event. Any data that is received and buffered in the socket will not be sent to the child.</p> <p>The optional <code>callback</code> is a function that is invoked after the message is sent but before the child may have received it. The function is called with a single argument: <code>null</code> on success, or an <a href="#errors_class_error"><code>Error</code></a> object on failure.</p> <p>If no <code>callback</code> function is provided and the message cannot be sent, an <code>'error'</code> event will be emitted by the <a href="#child_process_child_process"><code>ChildProcess</code></a> object. This can happen, for instance, when the child process has already exited.</p> <p><code>subprocess.send()</code> will return <code>false</code> if the channel has closed or when the backlog of unsent messages exceeds a threshold that makes it unwise to send more. Otherwise, the method returns <code>true</code>. The <code>callback</code> function can be used to implement flow control.</p> <h4>Example: sending a server object<span><a class="mark" href="#child_process_example_sending_a_server_object" id="child_process_example_sending_a_server_object">#</a></span></h4> <p>The <code>sendHandle</code> argument can be used, for instance, to pass the handle of a TCP server object to the child process as illustrated in the example below:</p> <pre><code class="language-js">const subprocess = require('child_process').fork('subprocess.js'); // Open up the server object and send the handle. const server = require('net').createServer(); server.on('connection', (socket) => { socket.end('handled by parent'); }); server.listen(1337, () => { subprocess.send('server', server); }); </code></pre> <p>The child would then receive the server object as:</p> <pre><code class="language-js">process.on('message', (m, server) => { if (m === 'server') { server.on('connection', (socket) => { socket.end('handled by child'); }); } }); </code></pre> <p>Once the server is now shared between the parent and child, some connections can be handled by the parent and some by the child.</p> <p>While the example above uses a server created using the <code>net</code> module, <code>dgram</code> module servers use exactly the same workflow with the exceptions of listening on a <code>'message'</code> event instead of <code>'connection'</code> and using <code>server.bind()</code> instead of <code>server.listen()</code>. This is, however, currently only supported on UNIX platforms.</p> <h4>Example: sending a socket object<span><a class="mark" href="#child_process_example_sending_a_socket_object" id="child_process_example_sending_a_socket_object">#</a></span></h4> <p>Similarly, the <code>sendHandler</code> argument can be used to pass the handle of a socket to the child process. The example below spawns two children that each handle connections with "normal" or "special" priority:</p> <pre><code class="language-js">const { fork } = require('child_process'); const normal = fork('subprocess.js', ['normal']); const special = fork('subprocess.js', ['special']); // Open up the server and send sockets to child. Use pauseOnConnect to prevent // the sockets from being read before they are sent to the child process. const server = require('net').createServer({ pauseOnConnect: true }); server.on('connection', (socket) => { // If this is special priority if (socket.remoteAddress === '74.125.127.100') { special.send('socket', socket); return; } // This is normal priority normal.send('socket', socket); }); server.listen(1337); </code></pre> <p>The <code>subprocess.js</code> would receive the socket handle as the second argument passed to the event callback function:</p> <pre><code class="language-js">process.on('message', (m, socket) => { if (m === 'socket') { if (socket) { // Check that the client socket exists. // It is possible for the socket to be closed between the time it is // sent and the time it is received in the child process. socket.end(`Request handled with ${process.argv[2]} priority`); } } }); </code></pre> <p>Once a socket has been passed to a child, the parent is no longer capable of tracking when the socket is destroyed. To indicate this, the <code>.connections</code> property becomes <code>null</code>. It is recommended not to use <code>.maxConnections</code> when this occurs.</p> <p>It is also recommended that any <code>'message'</code> handlers in the child process verify that <code>socket</code> exists, as the connection may have been closed during the time it takes to send the connection to the child.</p> <h3>subprocess.stderr<span><a class="mark" href="#child_process_subprocess_stderr" id="child_process_subprocess_stderr">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><a href="#stream_class_stream_readable" class="type"><stream.Readable></a></li> </ul> <p>A <code>Readable Stream</code> that represents the child process's <code>stderr</code>.</p> <p>If the child was spawned with <code>stdio[2]</code> set to anything other than <code>'pipe'</code>, then this will be <code>null</code>.</p> <p><code>subprocess.stderr</code> is an alias for <code>subprocess.stdio[2]</code>. Both properties will refer to the same value.</p> <h3>subprocess.stdin<span><a class="mark" href="#child_process_subprocess_stdin" id="child_process_subprocess_stdin">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><a href="#stream_class_stream_writable" class="type"><stream.Writable></a></li> </ul> <p>A <code>Writable Stream</code> that represents the child process's <code>stdin</code>.</p> <p><em>Note that if a child process waits to read all of its input, the child will not continue until this stream has been closed via <code>end()</code>.</em></p> <p>If the child was spawned with <code>stdio[0]</code> set to anything other than <code>'pipe'</code>, then this will be <code>null</code>.</p> <p><code>subprocess.stdin</code> is an alias for <code>subprocess.stdio[0]</code>. Both properties will refer to the same value.</p> <h3>subprocess.stdio<span><a class="mark" href="#child_process_subprocess_stdio" id="child_process_subprocess_stdio">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.10</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li> </ul> <p>A sparse array of pipes to the child process, corresponding with positions in the <a href="#child_process_options_stdio"><code>stdio</code></a> option passed to <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> that have been set to the value <code>'pipe'</code>. Note that <code>subprocess.stdio[0]</code>, <code>subprocess.stdio[1]</code>, and <code>subprocess.stdio[2]</code> are also available as <code>subprocess.stdin</code>, <code>subprocess.stdout</code>, and <code>subprocess.stderr</code>, respectively.</p> <p>In the following example, only the child's fd <code>1</code> (stdout) is configured as a pipe, so only the parent's <code>subprocess.stdio[1]</code> is a stream, all other values in the array are <code>null</code>.</p> <pre><code class="language-js">const assert = require('assert'); const fs = require('fs'); const child_process = require('child_process'); const subprocess = child_process.spawn('ls', { stdio: [ 0, // Use parent's stdin for child 'pipe', // Pipe child's stdout to parent fs.openSync('err.out', 'w') // Direct child's stderr to a file ] }); assert.strictEqual(subprocess.stdio[0], null); assert.strictEqual(subprocess.stdio[0], subprocess.stdin); assert(subprocess.stdout); assert.strictEqual(subprocess.stdio[1], subprocess.stdout); assert.strictEqual(subprocess.stdio[2], null); assert.strictEqual(subprocess.stdio[2], subprocess.stderr); </code></pre> <h3>subprocess.stdout<span><a class="mark" href="#child_process_subprocess_stdout" id="child_process_subprocess_stdout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><a href="#stream_class_stream_readable" class="type"><stream.Readable></a></li> </ul> <p>A <code>Readable Stream</code> that represents the child process's <code>stdout</code>.</p> <p>If the child was spawned with <code>stdio[1]</code> set to anything other than <code>'pipe'</code>, then this will be <code>null</code>.</p> <p><code>subprocess.stdout</code> is an alias for <code>subprocess.stdio[1]</code>. Both properties will refer to the same value.</p> <h3>subprocess.unref()<span><a class="mark" href="#child_process_subprocess_unref" id="child_process_subprocess_unref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.10</span> </div> <p>By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given <code>subprocess</code> to exit, use the <code>subprocess.unref()</code> method. Doing so will cause the parent's event loop to not include the child in its reference count, allowing the parent to exit independently of the child, unless there is an established IPC channel between the child and the parent.</p> <pre><code class="language-js">const { spawn } = require('child_process'); const subprocess = spawn(process.argv[0], ['child_program.js'], { detached: true, stdio: 'ignore' }); subprocess.unref(); </code></pre> <h2><code>maxBuffer</code> and Unicode<span><a class="mark" href="#child_process_maxbuffer_and_unicode" id="child_process_maxbuffer_and_unicode">#</a></span></h2> <p>The <code>maxBuffer</code> option specifies the largest number of bytes allowed on <code>stdout</code> or <code>stderr</code>. If this value is exceeded, then the child process is terminated. This impacts output that includes multibyte character encodings such as UTF-8 or UTF-16. For instance, <code>console.log('中文测试')</code> will send 13 UTF-8 encoded bytes to <code>stdout</code> although there are only 4 characters.</p> <h2>Shell Requirements<span><a class="mark" href="#child_process_shell_requirements" id="child_process_shell_requirements">#</a></span></h2> <p>The shell should understand the <code>-c</code> switch on UNIX or <code>/d /s /c</code> on Windows. On Windows, command line parsing should be compatible with <code>'cmd.exe'</code>.</p> <h2>Default Windows Shell<span><a class="mark" href="#child_process_default_windows_shell" id="child_process_default_windows_shell">#</a></span></h2> <p>Although Microsoft specifies <code>%COMSPEC%</code> must contain the path to <code>'cmd.exe'</code> in the root environment, child processes are not always subject to the same requirement. Thus, in <code>child_process</code> functions where a shell can be spawned, <code>'cmd.exe'</code> is used as a fallback if <code>process.env.ComSpec</code> is unavailable.</p> <h1>Cluster<span><a class="mark" href="#cluster_cluster" id="cluster_cluster">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load.</p> <p>The cluster module allows easy creation of child processes that all share server ports.</p> <pre><code class="language-js">const cluster = require('cluster'); const http = require('http'); const numCPUs = require('os').cpus().length; if (cluster.isMaster) { console.log(`Master ${process.pid} is running`); // Fork workers. for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`worker ${worker.process.pid} died`); }); } else { // Workers can share any TCP connection // In this case it is an HTTP server http.createServer((req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000); console.log(`Worker ${process.pid} started`); } </code></pre> <p>Running Node.js will now share port 8000 between the workers:</p> <pre><code class="language-txt">$ node server.js Master 3596 is running Worker 4324 started Worker 4520 started Worker 6056 started Worker 5644 started </code></pre> <p>Please note that on Windows, it is not yet possible to set up a named pipe server in a worker.</p> <h2>How It Works<span><a class="mark" href="#cluster_how_it_works" id="cluster_how_it_works">#</a></span></h2> <p>The worker processes are spawned using the <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a> method, so that they can communicate with the parent via IPC and pass server handles back and forth.</p> <p>The cluster module supports two methods of distributing incoming connections.</p> <p>The first one (and the default one on all platforms except Windows), is the round-robin approach, where the master process listens on a port, accepts new connections and distributes them across the workers in a round-robin fashion, with some built-in smarts to avoid overloading a worker process.</p> <p>The second approach is where the master process creates the listen socket and sends it to interested workers. The workers then accept incoming connections directly.</p> <p>The second approach should, in theory, give the best performance. In practice however, distribution tends to be very unbalanced due to operating system scheduler vagaries. Loads have been observed where over 70% of all connections ended up in just two processes, out of a total of eight.</p> <p>Because <code>server.listen()</code> hands off most of the work to the master process, there are three cases where the behavior between a normal Node.js process and a cluster worker differs:</p> <ol> <li><code>server.listen({fd: 7})</code> Because the message is passed to the master, file descriptor 7 <strong>in the parent</strong> will be listened on, and the handle passed to the worker, rather than listening to the worker's idea of what the number 7 file descriptor references.</li> <li><code>server.listen(handle)</code> Listening on handles explicitly will cause the worker to use the supplied handle, rather than talk to the master process.</li> <li><code>server.listen(0)</code> Normally, this will cause servers to listen on a random port. However, in a cluster, each worker will receive the same "random" port each time they do <code>listen(0)</code>. In essence, the port is random the first time, but predictable thereafter. To listen on a unique port, generate a port number based on the cluster worker ID.</li> </ol> <p>Node.js does not provide routing logic. It is, therefore important to design an application such that it does not rely too heavily on in-memory data objects for things like sessions and login.</p> <p>Because workers are all separate processes, they can be killed or re-spawned depending on a program's needs, without affecting other workers. As long as there are some workers still alive, the server will continue to accept connections. If no workers are alive, existing connections will be dropped and new connections will be refused. Node.js does not automatically manage the number of workers, however. It is the application's responsibility to manage the worker pool based on its own needs.</p> <p>Although a primary use case for the <code>cluster</code> module is networking, it can also be used for other use cases requiring worker processes.</p> <h2>Class: Worker<span><a class="mark" href="#cluster_class_worker" id="cluster_class_worker">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <p>A <code>Worker</code> object contains all public information and method about a worker. In the master it can be obtained using <code>cluster.workers</code>. In a worker it can be obtained using <code>cluster.worker</code>.</p> <h3>Event: 'disconnect'<span><a class="mark" href="#cluster_event_disconnect" id="cluster_event_disconnect">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <p>Similar to the <code>cluster.on('disconnect')</code> event, but specific to this worker.</p> <pre><code class="language-js">cluster.fork().on('disconnect', () => { // Worker has disconnected }); </code></pre> <h3>Event: 'error'<span><a class="mark" href="#cluster_event_error" id="cluster_event_error">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.3</span> </div> <p>This event is the same as the one provided by <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>.</p> <p>Within a worker, <code>process.on('error')</code> may also be used.</p> <h3>Event: 'exit'<span><a class="mark" href="#cluster_event_exit" id="cluster_event_exit">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.2</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The exit code, if it exited normally.</li> <li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the signal (e.g. <code>'SIGHUP'</code>) that caused the process to be killed.</li> </ul> <p>Similar to the <code>cluster.on('exit')</code> event, but specific to this worker.</p> <pre><code class="language-js">const worker = cluster.fork(); worker.on('exit', (code, signal) => { if (signal) { console.log(`worker was killed by signal: ${signal}`); } else if (code !== 0) { console.log(`worker exited with error code: ${code}`); } else { console.log('worker success!'); } }); </code></pre> <h3>Event: 'listening'<span><a class="mark" href="#cluster_event_listening" id="cluster_event_listening">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Similar to the <code>cluster.on('listening')</code> event, but specific to this worker.</p> <pre><code class="language-js">cluster.fork().on('listening', (address) => { // Worker is listening }); </code></pre> <p>It is not emitted in the worker.</p> <h3>Event: 'message'<span><a class="mark" href="#cluster_event_message" id="cluster_event_message">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Similar to the <code>'message'</code> event of <code>cluster</code>, but specific to this worker.</p> <p>Within a worker, <code>process.on('message')</code> may also be used.</p> <p>See <a href="#process_event_message"><code>process</code> event: <code>'message'</code></a>.</p> <p>Here is an example using the message system. It keeps a count in the master process of the number of HTTP requests received by the workers:</p> <pre><code class="language-js">const cluster = require('cluster'); const http = require('http'); if (cluster.isMaster) { // Keep track of http requests let numReqs = 0; setInterval(() => { console.log(`numReqs = ${numReqs}`); }, 1000); // Count requests function messageHandler(msg) { if (msg.cmd && msg.cmd === 'notifyRequest') { numReqs += 1; } } // Start workers and listen for messages containing notifyRequest const numCPUs = require('os').cpus().length; for (let i = 0; i < numCPUs; i++) { cluster.fork(); } for (const id in cluster.workers) { cluster.workers[id].on('message', messageHandler); } } else { // Worker processes have a http server. http.Server((req, res) => { res.writeHead(200); res.end('hello world\n'); // notify master about the request process.send({ cmd: 'notifyRequest' }); }).listen(8000); } </code></pre> <h3>Event: 'online'<span><a class="mark" href="#cluster_event_online" id="cluster_event_online">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <p>Similar to the <code>cluster.on('online')</code> event, but specific to this worker.</p> <pre><code class="language-js">cluster.fork().on('online', () => { // Worker is online }); </code></pre> <p>It is not emitted in the worker.</p> <h3>worker.disconnect()<span><a class="mark" href="#cluster_worker_disconnect" id="cluster_worker_disconnect">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.3.0</td> <td><p>This method now returns a reference to <code>worker</code>.</p></td></tr> <tr><td>v0.7.7</td> <td><p><span>Added in: v0.7.7</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Returns: <a href="#cluster_class_worker" class="type"><cluster.Worker></a> A reference to <code>worker</code>.</li> </ul> <p>In a worker, this function will close all servers, wait for the <code>'close'</code> event on those servers, and then disconnect the IPC channel.</p> <p>In the master, an internal message is sent to the worker causing it to call <code>.disconnect()</code> on itself.</p> <p>Causes <code>.exitedAfterDisconnect</code> to be set.</p> <p>Note that after a server is closed, it will no longer accept new connections, but connections may be accepted by any other listening worker. Existing connections will be allowed to close as usual. When no more connections exist, see <a href="#net_event_close"><code>server.close()</code></a>, the IPC channel to the worker will close allowing it to die gracefully.</p> <p>The above applies <em>only</em> to server connections, client connections are not automatically closed by workers, and disconnect does not wait for them to close before exiting.</p> <p>Note that in a worker, <code>process.disconnect</code> exists, but it is not this function, it is <a href="#child_process_subprocess_disconnect"><code>disconnect</code></a>.</p> <p>Because long living server connections may block workers from disconnecting, it may be useful to send a message, so application specific actions may be taken to close them. It also may be useful to implement a timeout, killing a worker if the <code>'disconnect'</code> event has not been emitted after some time.</p> <pre><code class="language-js">if (cluster.isMaster) { const worker = cluster.fork(); let timeout; worker.on('listening', (address) => { worker.send('shutdown'); worker.disconnect(); timeout = setTimeout(() => { worker.kill(); }, 2000); }); worker.on('disconnect', () => { clearTimeout(timeout); }); } else if (cluster.isWorker) { const net = require('net'); const server = net.createServer((socket) => { // connections never end }); server.listen(8000); process.on('message', (msg) => { if (msg === 'shutdown') { // initiate graceful close of any connections to server } }); } </code></pre> <h3>worker.exitedAfterDisconnect<span><a class="mark" href="#cluster_worker_exitedafterdisconnect" id="cluster_worker_exitedafterdisconnect">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Set by calling <code>.kill()</code> or <code>.disconnect()</code>. Until then, it is <code>undefined</code>.</p> <p>The boolean <a href="#cluster_worker_exitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a> allows distinguishing between voluntary and accidental exit, the master may choose not to respawn a worker based on this value.</p> <pre><code class="language-js">cluster.on('exit', (worker, code, signal) => { if (worker.exitedAfterDisconnect === true) { console.log('Oh, it was just voluntary – no need to worry'); } }); // kill worker worker.kill(); </code></pre> <h3>worker.id<span><a class="mark" href="#cluster_worker_id" id="cluster_worker_id">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.8.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Each new worker is given its own unique id, this id is stored in the <code>id</code>.</p> <p>While a worker is alive, this is the key that indexes it in <code>cluster.workers</code>.</p> <h3>worker.isConnected()<span><a class="mark" href="#cluster_worker_isconnected" id="cluster_worker_isconnected">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <p>This function returns <code>true</code> if the worker is connected to its master via its IPC channel, <code>false</code> otherwise. A worker is connected to its master after it has been created. It is disconnected after the <code>'disconnect'</code> event is emitted.</p> <h3>worker.isDead()<span><a class="mark" href="#cluster_worker_isdead" id="cluster_worker_isdead">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <p>This function returns <code>true</code> if the worker's process has terminated (either because of exiting or being signaled). Otherwise, it returns <code>false</code>.</p> <h3>worker.kill([signal='SIGTERM'])<span><a class="mark" href="#cluster_worker_kill_signal_sigterm" id="cluster_worker_kill_signal_sigterm">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.12</span> </div> <ul> <li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the kill signal to send to the worker process.</li> </ul> <p>This function will kill the worker. In the master, it does this by disconnecting the <code>worker.process</code>, and once disconnected, killing with <code>signal</code>. In the worker, it does it by disconnecting the channel, and then exiting with code <code>0</code>.</p> <p>Because <code>kill()</code> attempts to gracefully disconnect the worker process, it is susceptible to waiting indefinitely for the disconnect to complete. For example, if the worker enters an infinite loop, a graceful disconnect will never occur. If the graceful disconnect behavior is not needed, use <code>worker.process.kill()</code>.</p> <p>Causes <code>.exitedAfterDisconnect</code> to be set.</p> <p>This method is aliased as <code>worker.destroy()</code> for backwards compatibility.</p> <p>Note that in a worker, <code>process.kill()</code> exists, but it is not this function, it is <a href="#process_process_kill_pid_signal"><code>kill</code></a>.</p> <h3>worker.process<span><a class="mark" href="#cluster_worker_process" id="cluster_worker_process">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><a href="#child_process_class_childprocess" class="type"><ChildProcess></a></li> </ul> <p>All workers are created using <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>, the returned object from this function is stored as <code>.process</code>. In a worker, the global <code>process</code> is stored.</p> <p>See: <a href="#child_process_child_process_fork_modulepath_args_options">Child Process module</a>.</p> <p>Note that workers will call <code>process.exit(0)</code> if the <code>'disconnect'</code> event occurs on <code>process</code> and <code>.exitedAfterDisconnect</code> is not <code>true</code>. This protects against accidental disconnection.</p> <h3>worker.send(message[, sendHandle][, callback])<span><a class="mark" href="#cluster_worker_send_message_sendhandle_callback" id="cluster_worker_send_message_sendhandle_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.0.0</td> <td><p>The <code>callback</code> parameter is supported now.</p></td></tr> <tr><td>v0.7.0</td> <td><p><span>Added in: v0.7.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>sendHandle</code> <a href="#net_server_listen_handle_backlog_callback" class="type"><Handle></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Send a message to a worker or master, optionally with a handle.</p> <p>In the master this sends a message to a specific worker. It is identical to <a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>ChildProcess.send()</code></a>.</p> <p>In a worker this sends a message to the master. It is identical to <code>process.send()</code>.</p> <p>This example will echo back all messages from the master:</p> <pre><code class="language-js">if (cluster.isMaster) { const worker = cluster.fork(); worker.send('hi there'); } else if (cluster.isWorker) { process.on('message', (msg) => { process.send(msg); }); } </code></pre> <h2>Event: 'disconnect'<span><a class="mark" href="#cluster_event_disconnect_1" id="cluster_event_disconnect_1">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.9</span> </div> <ul> <li><code>worker</code> <a href="#cluster_class_worker" class="type"><cluster.Worker></a></li> </ul> <p>Emitted after the worker IPC channel has disconnected. This can occur when a worker exits gracefully, is killed, or is disconnected manually (such as with <code>worker.disconnect()</code>).</p> <p>There may be a delay between the <code>'disconnect'</code> and <code>'exit'</code> events. These events can be used to detect if the process is stuck in a cleanup or if there are long-living connections.</p> <pre><code class="language-js">cluster.on('disconnect', (worker) => { console.log(`The worker #${worker.id} has disconnected`); }); </code></pre> <h2>Event: 'exit'<span><a class="mark" href="#cluster_event_exit_1" id="cluster_event_exit_1">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.9</span> </div> <ul> <li><code>worker</code> <a href="#cluster_class_worker" class="type"><cluster.Worker></a></li> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The exit code, if it exited normally.</li> <li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the signal (e.g. <code>'SIGHUP'</code>) that caused the process to be killed.</li> </ul> <p>When any of the workers die the cluster module will emit the <code>'exit'</code> event.</p> <p>This can be used to restart the worker by calling <code>.fork()</code> again.</p> <pre><code class="language-js">cluster.on('exit', (worker, code, signal) => { console.log('worker %d died (%s). restarting...', worker.process.pid, signal || code); cluster.fork(); }); </code></pre> <p>See <a href="#child_process_event_exit"><code>child_process</code> event: <code>'exit'</code></a>.</p> <h2>Event: 'fork'<span><a class="mark" href="#cluster_event_fork" id="cluster_event_fork">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>worker</code> <a href="#cluster_class_worker" class="type"><cluster.Worker></a></li> </ul> <p>When a new worker is forked the cluster module will emit a <code>'fork'</code> event. This can be used to log worker activity, and create a custom timeout.</p> <pre><code class="language-js">const timeouts = []; function errorMsg() { console.error('Something must be wrong with the connection ...'); } cluster.on('fork', (worker) => { timeouts[worker.id] = setTimeout(errorMsg, 2000); }); cluster.on('listening', (worker, address) => { clearTimeout(timeouts[worker.id]); }); cluster.on('exit', (worker, code, signal) => { clearTimeout(timeouts[worker.id]); errorMsg(); }); </code></pre> <h2>Event: 'listening'<span><a class="mark" href="#cluster_event_listening_1" id="cluster_event_listening_1">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>worker</code> <a href="#cluster_class_worker" class="type"><cluster.Worker></a></li> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>After calling <code>listen()</code> from a worker, when the <code>'listening'</code> event is emitted on the server a <code>'listening'</code> event will also be emitted on <code>cluster</code> in the master.</p> <p>The event handler is executed with two arguments, the <code>worker</code> contains the worker object and the <code>address</code> object contains the following connection properties: <code>address</code>, <code>port</code> and <code>addressType</code>. This is very useful if the worker is listening on more than one address.</p> <pre><code class="language-js">cluster.on('listening', (worker, address) => { console.log( `A worker is now connected to ${address.address}:${address.port}`); }); </code></pre> <p>The <code>addressType</code> is one of:</p> <ul> <li><code>4</code> (TCPv4)</li> <li><code>6</code> (TCPv6)</li> <li><code>-1</code> (unix domain socket)</li> <li><code>'udp4'</code> or <code>'udp6'</code> (UDP v4 or v6)</li> </ul> <h2>Event: 'message'<span><a class="mark" href="#cluster_event_message_1" id="cluster_event_message_1">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>The <code>worker</code> parameter is passed now; see below for details.</p></td></tr> <tr><td>v2.5.0</td> <td><p><span>Added in: v2.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>worker</code> <a href="#cluster_class_worker" class="type"><cluster.Worker></a></li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Emitted when the cluster master receives a message from any worker.</p> <p>See <a href="#child_process_event_message"><code>child_process</code> event: <code>'message'</code></a>.</p> <p>Before Node.js v6.0, this event emitted only the message and the handle, but not the worker object, contrary to what the documentation stated.</p> <p>If support for older versions is required but a worker object is not required, it is possible to work around the discrepancy by checking the number of arguments:</p> <pre><code class="language-js">cluster.on('message', (worker, message, handle) => { if (arguments.length === 2) { handle = message; message = worker; worker = undefined; } // ... }); </code></pre> <h2>Event: 'online'<span><a class="mark" href="#cluster_event_online_1" id="cluster_event_online_1">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>worker</code> <a href="#cluster_class_worker" class="type"><cluster.Worker></a></li> </ul> <p>After forking a new worker, the worker should respond with an online message. When the master receives an online message it will emit this event. The difference between <code>'fork'</code> and <code>'online'</code> is that fork is emitted when the master forks a worker, and <code>'online'</code> is emitted when the worker is running.</p> <pre><code class="language-js">cluster.on('online', (worker) => { console.log('Yay, the worker responded after it was forked'); }); </code></pre> <h2>Event: 'setup'<span><a class="mark" href="#cluster_event_setup" id="cluster_event_setup">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.1</span> </div> <ul> <li><code>settings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Emitted every time <code>.setupMaster()</code> is called.</p> <p>The <code>settings</code> object is the <code>cluster.settings</code> object at the time <code>.setupMaster()</code> was called and is advisory only, since multiple calls to <code>.setupMaster()</code> can be made in a single tick.</p> <p>If accuracy is important, use <code>cluster.settings</code>.</p> <h2>cluster.disconnect([callback])<span><a class="mark" href="#cluster_cluster_disconnect_callback" id="cluster_cluster_disconnect_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called when all workers are disconnected and handles are closed.</li> </ul> <p>Calls <code>.disconnect()</code> on each worker in <code>cluster.workers</code>.</p> <p>When they are disconnected all internal handles will be closed, allowing the master process to die gracefully if no other event is waiting.</p> <p>The method takes an optional callback argument which will be called when finished.</p> <p>This can only be called from the master process.</p> <h2>cluster.fork([env])<span><a class="mark" href="#cluster_cluster_fork_env" id="cluster_cluster_fork_env">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.6.0</span> </div> <ul> <li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Key/value pairs to add to worker process environment.</li> <li>Returns: <a href="#cluster_class_worker" class="type"><cluster.Worker></a></li> </ul> <p>Spawn a new worker process.</p> <p>This can only be called from the master process.</p> <h2>cluster.isMaster<span><a class="mark" href="#cluster_cluster_ismaster" id="cluster_cluster_ismaster">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.8.1</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>True if the process is a master. This is determined by the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is undefined, then <code>isMaster</code> is <code>true</code>.</p> <h2>cluster.isWorker<span><a class="mark" href="#cluster_cluster_isworker" id="cluster_cluster_isworker">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.6.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>True if the process is not a master (it is the negation of <code>cluster.isMaster</code>).</p> <h2>cluster.schedulingPolicy<span><a class="mark" href="#cluster_cluster_schedulingpolicy" id="cluster_cluster_schedulingpolicy">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.2</span> </div> <p>The scheduling policy, either <code>cluster.SCHED_RR</code> for round-robin or <code>cluster.SCHED_NONE</code> to leave it to the operating system. This is a global setting and effectively frozen once either the first worker is spawned, or <code>cluster.setupMaster()</code> is called, whichever comes first.</p> <p><code>SCHED_RR</code> is the default on all operating systems except Windows. Windows will change to <code>SCHED_RR</code> once libuv is able to effectively distribute IOCP handles without incurring a large performance hit.</p> <p><code>cluster.schedulingPolicy</code> can also be set through the <code>NODE_CLUSTER_SCHED_POLICY</code> environment variable. Valid values are <code>'rr'</code> and <code>'none'</code>.</p> <h2>cluster.settings<span><a class="mark" href="#cluster_cluster_settings" id="cluster_cluster_settings">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.5.0</td> <td><p>The <code>cwd</code> option is supported now.</p></td></tr> <tr><td>v9.4.0</td> <td><p>The <code>windowsHide</code> option is supported now.</p></td></tr> <tr><td>v8.2.0</td> <td><p>The <code>inspectPort</code> option is supported now.</p></td></tr> <tr><td>v6.4.0</td> <td><p>The <code>stdio</code> option is supported now.</p></td></tr> <tr><td>v0.7.1</td> <td><p><span>Added in: v0.7.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> List of string arguments passed to the Node.js executable. <strong>Default:</strong> <code>process.execArgv</code>.</li> <li><code>exec</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> File path to worker file. <strong>Default:</strong> <code>process.argv[1]</code>.</li> <li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> String arguments passed to worker. <strong>Default:</strong> <code>process.argv.slice(2)</code>.</li> <li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Current working directory of the worker process. <strong>Default:</strong> <code>undefined</code> (inherits from parent process).</li> <li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not to send output to parent's stdio. <strong>Default:</strong> <code>false</code>.</li> <li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must contain an <code>'ipc'</code> entry. When this option is provided, it overrides <code>silent</code>.</li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>.)</li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>.)</li> <li><code>inspectPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. By default each worker gets its own port, incremented from the master's <code>process.debugPort</code>.</li> <li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Hide the forked processes console window that would normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> </ul> <p>After calling <code>.setupMaster()</code> (or <code>.fork()</code>) this settings object will contain the settings, including the default values.</p> <p>This object is not intended to be changed or set manually.</p> <h2>cluster.setupMaster([settings])<span><a class="mark" href="#cluster_cluster_setupmaster_settings" id="cluster_cluster_setupmaster_settings">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.4.0</td> <td><p>The <code>stdio</code> option is supported now.</p></td></tr> <tr><td>v0.7.1</td> <td><p><span>Added in: v0.7.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>settings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#cluster_cluster_settings"><code>cluster.settings</code></a>.</li> </ul> <p><code>setupMaster</code> is used to change the default 'fork' behavior. Once called, the settings will be present in <code>cluster.settings</code>.</p> <p>Note that:</p> <ul> <li>Any settings changes only affect future calls to <code>.fork()</code> and have no effect on workers that are already running.</li> <li>The <em>only</em> attribute of a worker that cannot be set via <code>.setupMaster()</code> is the <code>env</code> passed to <code>.fork()</code>.</li> <li>The defaults above apply to the first call only, the defaults for later calls is the current value at the time of <code>cluster.setupMaster()</code> is called.</li> </ul> <pre><code class="language-js">const cluster = require('cluster'); cluster.setupMaster({ exec: 'worker.js', args: ['--use', 'https'], silent: true }); cluster.fork(); // https worker cluster.setupMaster({ exec: 'worker.js', args: ['--use', 'http'] }); cluster.fork(); // http worker </code></pre> <p>This can only be called from the master process.</p> <h2>cluster.worker<span><a class="mark" href="#cluster_cluster_worker" id="cluster_cluster_worker">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>A reference to the current worker object. Not available in the master process.</p> <pre><code class="language-js">const cluster = require('cluster'); if (cluster.isMaster) { console.log('I am master'); cluster.fork(); cluster.fork(); } else if (cluster.isWorker) { console.log(`I am worker #${cluster.worker.id}`); } </code></pre> <h2>cluster.workers<span><a class="mark" href="#cluster_cluster_workers" id="cluster_cluster_workers">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>A hash that stores the active worker objects, keyed by <code>id</code> field. Makes it easy to loop through all the workers. It is only available in the master process.</p> <p>A worker is removed from <code>cluster.workers</code> after the worker has disconnected <em>and</em> exited. The order between these two events cannot be determined in advance. However, it is guaranteed that the removal from the <code>cluster.workers</code> list happens before last <code>'disconnect'</code> or <code>'exit'</code> event is emitted.</p> <pre><code class="language-js">// Go through all workers function eachWorker(callback) { for (const id in cluster.workers) { callback(cluster.workers[id]); } } eachWorker((worker) => { worker.send('big announcement to all workers'); }); </code></pre> <p>Using the worker's unique id is the easiest way to locate the worker.</p> <pre><code class="language-js">socket.on('data', (id) => { const worker = cluster.workers[id]; }); </code></pre> <h1>Command Line Options<span><a class="mark" href="#cli_command_line_options" id="cli_command_line_options">#</a></span></h1> <p>Node.js comes with a variety of CLI options. These options expose built-in debugging, multiple ways to execute scripts, and other helpful runtime options.</p> <p>To view this documentation as a manual page in a terminal, run <code>man node</code>.</p> <h2>Synopsis<span><a class="mark" href="#cli_synopsis" id="cli_synopsis">#</a></span></h2> <p><code>node [options] [V8 options] [script.js | -e "script" | -] [--] [arguments]</code></p> <p><code>node inspect [script.js | -e "script" | <host>:<port>] …</code></p> <p><code>node --v8-options</code></p> <p>Execute without arguments to start the <a href="repl.html">REPL</a>.</p> <p><em>For more info about <code>node inspect</code>, please see the <a href="debugger.html">debugger</a> documentation.</em></p> <h2>Options<span><a class="mark" href="#cli_options" id="cli_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.12.0</td> <td><p>Underscores instead of dashes are now allowed for Node.js options as well, in addition to V8 options.</p></td></tr> </tbody></table> </details> </div> <p>All options, including V8 options, allow words to be separated by both dashes (<code>-</code>) or underscores (<code>_</code>).</p> <p>For example, <code>--pending-deprecation</code> is equivalent to <code>--pending_deprecation</code>.</p> <h3><code>-</code><span><a class="mark" href="#cli" id="cli">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <p>Alias for stdin, analogous to the use of - in other command line utilities, meaning that the script will be read from stdin, and the rest of the options are passed to that script.</p> <h3><code>--</code><span><a class="mark" href="#cli_1" id="cli_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.11.0</span> </div> <p>Indicate the end of node options. Pass the rest of the arguments to the script. If no script filename or eval/print script is supplied prior to this, then the next argument will be used as a script filename.</p> <h3><code>--abort-on-uncaught-exception</code><span><a class="mark" href="#cli_abort_on_uncaught_exception" id="cli_abort_on_uncaught_exception">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.10</span> </div> <p>Aborting instead of exiting causes a core file to be generated for post-mortem analysis using a debugger (such as <code>lldb</code>, <code>gdb</code>, and <code>mdb</code>).</p> <p>If this flag is passed, the behavior can still be set to not abort through <a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> (and through usage of the <code>domain</code> module that uses it).</p> <h3><code>--completion-bash</code><span><a class="mark" href="#cli_completion_bash" id="cli_completion_bash">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <p>Print source-able bash completion script for Node.js.</p> <pre><code class="language-console">$ node --completion-bash > node_bash_completion $ source node_bash_completion </code></pre> <h3><code>--enable-fips</code><span><a class="mark" href="#cli_enable_fips" id="cli_enable_fips">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <p>Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with <code>./configure --openssl-fips</code>.)</p> <h3><code>--experimental-modules</code><span><a class="mark" href="#cli_experimental_modules" id="cli_experimental_modules">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <p>Enable experimental ES module support and caching modules.</p> <h3><code>--experimental-repl-await</code><span><a class="mark" href="#cli_experimental_repl_await" id="cli_experimental_repl_await">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>Enable experimental top-level <code>await</code> keyword support in REPL.</p> <h3><code>--experimental-vm-modules</code><span><a class="mark" href="#cli_experimental_vm_modules" id="cli_experimental_vm_modules">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.6.0</span> </div> <p>Enable experimental ES Module support in the <code>vm</code> module.</p> <h3><code>--experimental-worker</code><span><a class="mark" href="#cli_experimental_worker" id="cli_experimental_worker">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Enable experimental worker threads using the <code>worker_threads</code> module.</p> <h3><code>--force-fips</code><span><a class="mark" href="#cli_force_fips" id="cli_force_fips">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <p>Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.) (Same requirements as <code>--enable-fips</code>.)</p> <h3><code>--icu-data-dir=file</code><span><a class="mark" href="#cli_icu_data_dir_file" id="cli_icu_data_dir_file">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.15</span> </div> <p>Specify ICU data load path. (Overrides <code>NODE_ICU_DATA</code>.)</p> <h3><code>--inspect-brk[=[host:]port]</code><span><a class="mark" href="#cli_inspect_brk_host_port" id="cli_inspect_brk_host_port">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.6.0</span> </div> <p>Activate inspector on <code>host:port</code> and break at start of user script. Default <code>host:port</code> is <code>127.0.0.1:9229</code>.</p> <h3><code>--inspect-port=[host:]port</code><span><a class="mark" href="#cli_inspect_port_host_port" id="cli_inspect_port_host_port">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.6.0</span> </div> <p>Set the <code>host:port</code> to be used when the inspector is activated. Useful when activating the inspector by sending the <code>SIGUSR1</code> signal.</p> <p>Default host is <code>127.0.0.1</code>.</p> <p>See the <a href="#inspector_security">security warning</a> below regarding the <code>host</code> parameter usage.</p> <h3><code>--inspect[=[host:]port]</code><span><a class="mark" href="#cli_inspect_host_port" id="cli_inspect_host_port">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.3.0</span> </div> <p>Activate inspector on <code>host:port</code>. Default is <code>127.0.0.1:9229</code>.</p> <p>V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug and profile Node.js instances. The tools attach to Node.js instances via a tcp port and communicate using the <a href="https://chromedevtools.github.io/devtools-protocol/">Chrome DevTools Protocol</a>.</p> <p><a id="inspector_security"></a></p> <h4>Warning: binding inspector to a public IP:port combination is insecure<span><a class="mark" href="#cli_warning_binding_inspector_to_a_public_ip_port_combination_is_insecure" id="cli_warning_binding_inspector_to_a_public_ip_port_combination_is_insecure">#</a></span></h4> <p>Binding the inspector to a public IP (including <code>0.0.0.0</code>) with an open port is insecure, as it allows external hosts to connect to the inspector and perform a <a href="https://www.owasp.org/index.php/Code_Injection">remote code execution</a> attack.</p> <p>If you specify a host, make sure that at least one of the following is true: either the host is not public, or the port is properly firewalled to disallow unwanted connections.</p> <p><strong>More specifically, <code>--inspect=0.0.0.0</code> is insecure if the port (<code>9229</code> by default) is not firewall-protected.</strong></p> <p>See the <a href="https://nodejs.org/en/docs/guides/debugging-getting-started/#security-implications">debugging security implications</a> section for more information.</p> <h3><code>--loader=file</code><span><a class="mark" href="#cli_loader_file" id="cli_loader_file">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span> </div> <p>Specify the <code>file</code> of the custom <a href="#esm_loader_hooks">experimental ECMAScript Module</a> loader.</p> <h3><code>--insecure-http-parser</code><span><a class="mark" href="#cli_insecure_http_parser" id="cli_insecure_http_parser">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.19.0</span> </div> <p>Use an insecure HTTP parser that accepts invalid HTTP headers. This may allow interoperability with non-conformant HTTP implementations. It may also allow request smuggling and other HTTP attacks that rely on invalid headers being accepted. Avoid using this option.</p> <h3><code>--max-http-header-size=size</code><span><a class="mark" href="#cli_max_http_header_size_size" id="cli_max_http_header_size_size">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.15.0</span> </div> <p>Specify the maximum size, in bytes, of HTTP headers. Defaults to 8KB.</p> <h3><code>--napi-modules</code><span><a class="mark" href="#cli_napi_modules" id="cli_napi_modules">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.10.0</span> </div> <p>This option is a no-op. It is kept for compatibility.</p> <h3><code>--no-deprecation</code><span><a class="mark" href="#cli_no_deprecation" id="cli_no_deprecation">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.8.0</span> </div> <p>Silence deprecation warnings.</p> <h3><code>--no-force-async-hooks-checks</code><span><a class="mark" href="#cli_no_force_async_hooks_checks" id="cli_no_force_async_hooks_checks">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span> </div> <p>Disables runtime checks for <code>async_hooks</code>. These will still be enabled dynamically when <code>async_hooks</code> is enabled.</p> <h3><code>--no-warnings</code><span><a class="mark" href="#cli_no_warnings" id="cli_no_warnings">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <p>Silence all process warnings (including deprecations).</p> <h3><code>--openssl-config=file</code><span><a class="mark" href="#cli_openssl_config_file" id="cli_openssl_config_file">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.9.0</span> </div> <p>Load an OpenSSL configuration file on startup. Among other uses, this can be used to enable FIPS-compliant crypto if Node.js is built with <code>./configure --openssl-fips</code>.</p> <h3><code>--pending-deprecation</code><span><a class="mark" href="#cli_pending_deprecation" id="cli_pending_deprecation">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <p>Emit pending deprecation warnings.</p> <p>Pending deprecations are generally identical to a runtime deprecation with the notable exception that they are turned <em>off</em> by default and will not be emitted unless either the <code>--pending-deprecation</code> command line flag, or the <code>NODE_PENDING_DEPRECATION=1</code> environment variable, is set. Pending deprecations are used to provide a kind of selective "early warning" mechanism that developers may leverage to detect deprecated API usage.</p> <h3><code>--preserve-symlinks</code><span><a class="mark" href="#cli_preserve_symlinks" id="cli_preserve_symlinks">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.3.0</span> </div> <p>Instructs the module loader to preserve symbolic links when resolving and caching modules.</p> <p>By default, when Node.js loads a module from a path that is symbolically linked to a different on-disk location, Node.js will dereference the link and use the actual on-disk "real path" of the module as both an identifier and as a root path to locate other dependency modules. In most cases, this default behavior is acceptable. However, when using symbolically linked peer dependencies, as illustrated in the example below, the default behavior causes an exception to be thrown if <code>moduleA</code> attempts to require <code>moduleB</code> as a peer dependency:</p> <pre><code class="language-text">{appDir} ├── app │ ├── index.js │ └── node_modules │ ├── moduleA -> {appDir}/moduleA │ └── moduleB │ ├── index.js │ └── package.json └── moduleA ├── index.js └── package.json </code></pre> <p>The <code>--preserve-symlinks</code> command line flag instructs Node.js to use the symlink path for modules as opposed to the real path, allowing symbolically linked peer dependencies to be found.</p> <p>Note, however, that using <code>--preserve-symlinks</code> can have other side effects. Specifically, symbolically linked <em>native</em> modules can fail to load if those are linked from more than one location in the dependency tree (Node.js would see those as two separate modules and would attempt to load the module multiple times, causing an exception to be thrown).</p> <p>The <code>--preserve-symlinks</code> flag does not apply to the main module, which allows <code>node --preserve-symlinks node_module/.bin/<foo></code> to work. To apply the same behavior for the main module, also use <code>--preserve-symlinks-main</code>.</p> <h3><code>--preserve-symlinks-main</code><span><a class="mark" href="#cli_preserve_symlinks_main" id="cli_preserve_symlinks_main">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.2.0</span> </div> <p>Instructs the module loader to preserve symbolic links when resolving and caching the main module (<code>require.main</code>).</p> <p>This flag exists so that the main module can be opted-in to the same behavior that <code>--preserve-symlinks</code> gives to all other imports; they are separate flags, however, for backward compatibility with older Node.js versions.</p> <p>Note that <code>--preserve-symlinks-main</code> does not imply <code>--preserve-symlinks</code>; it is expected that <code>--preserve-symlinks-main</code> will be used in addition to <code>--preserve-symlinks</code> when it is not desirable to follow symlinks before resolving relative paths.</p> <p>See <code>--preserve-symlinks</code> for more information.</p> <h3><code>--prof</code><span><a class="mark" href="#cli_prof" id="cli_prof">#</a></span></h3> <div class="api_metadata"> <span>Added in: v2.0.0</span> </div> <p>Generate V8 profiler output.</p> <h3><code>--prof-process</code><span><a class="mark" href="#cli_prof_process" id="cli_prof_process">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.2.0</span> </div> <p>Process V8 profiler output generated using the V8 option <code>--prof</code>.</p> <h3><code>--redirect-warnings=file</code><span><a class="mark" href="#cli_redirect_warnings_file" id="cli_redirect_warnings_file">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <p>Write process warnings to the given file instead of printing to stderr. The file will be created if it does not exist, and will be appended to if it does. If an error occurs while attempting to write the warning to the file, the warning will be written to stderr instead.</p> <h3><code>--throw-deprecation</code><span><a class="mark" href="#cli_throw_deprecation" id="cli_throw_deprecation">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <p>Throw errors for deprecations.</p> <h3><code>--title=title</code><span><a class="mark" href="#cli_title_title" id="cli_title_title">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.7.0</span> </div> <p>Set <code>process.title</code> on startup.</p> <h3><code>--tls-cipher-list=list</code><span><a class="mark" href="#cli_tls_cipher_list_list" id="cli_tls_cipher_list_list">#</a></span></h3> <div class="api_metadata"> <span>Added in: v4.0.0</span> </div> <p>Specify an alternative default TLS cipher list. Requires Node.js to be built with crypto support (default).</p> <h3><code>--tls-max-v1.2</code><span><a class="mark" href="#cli_tls_max_v1_2" id="cli_tls_max_v1_2">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> </div> <p>Does nothing, [<code>tls.DEFAULT_MAX_VERSION</code>][] is always 'TLSv1.2'. Exists for compatibility with Node.js 11.x and higher.</p> <h3><code>--tls-min-v1.0</code><span><a class="mark" href="#cli_tls_min_v1_0" id="cli_tls_min_v1_0">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> </div> <p>Set default [<code>tls.DEFAULT_MIN_VERSION</code>][] to 'TLSv1'. Use for compatibility with old TLS clients or servers.</p> <h3><code>--tls-min-v1.1</code><span><a class="mark" href="#cli_tls_min_v1_1" id="cli_tls_min_v1_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> </div> <p>Set default [<code>tls.DEFAULT_MIN_VERSION</code>][] to 'TLSv1.1'. Use for compatibility with old TLS clients or servers.</p> <h3><code>--tls-min-v1.2</code><span><a class="mark" href="#cli_tls_min_v1_2" id="cli_tls_min_v1_2">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> </div> <p>Set default [<code>tls.DEFAULT_MIN_VERSION</code>][] to 'TLSv1.2'. Use this to disable support for earlier TLS versions, which are less secure.</p> <h3><code>--trace-deprecation</code><span><a class="mark" href="#cli_trace_deprecation" id="cli_trace_deprecation">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.8.0</span> </div> <p>Print stack traces for deprecations.</p> <h3><code>--trace-event-categories</code><span><a class="mark" href="#cli_trace_event_categories" id="cli_trace_event_categories">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.7.0</span> </div> <p>A comma separated list of categories that should be traced when trace event tracing is enabled using <code>--trace-events-enabled</code>.</p> <h3><code>--trace-event-file-pattern</code><span><a class="mark" href="#cli_trace_event_file_pattern" id="cli_trace_event_file_pattern">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.8.0</span> </div> <p>Template string specifying the filepath for the trace event data, it supports <code>${rotation}</code> and <code>${pid}</code>.</p> <h3><code>--trace-events-enabled</code><span><a class="mark" href="#cli_trace_events_enabled" id="cli_trace_events_enabled">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.7.0</span> </div> <p>Enables the collection of trace event tracing information.</p> <h3><code>--trace-sync-io</code><span><a class="mark" href="#cli_trace_sync_io" id="cli_trace_sync_io">#</a></span></h3> <div class="api_metadata"> <span>Added in: v2.1.0</span> </div> <p>Prints a stack trace whenever synchronous I/O is detected after the first turn of the event loop.</p> <h3><code>--trace-warnings</code><span><a class="mark" href="#cli_trace_warnings" id="cli_trace_warnings">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <p>Print stack traces for process warnings (including deprecations).</p> <h3><code>--track-heap-objects</code><span><a class="mark" href="#cli_track_heap_objects" id="cli_track_heap_objects">#</a></span></h3> <div class="api_metadata"> <span>Added in: v2.4.0</span> </div> <p>Track heap object allocations for heap snapshots.</p> <h3><code>--unhandled-rejections=mode</code><span><a class="mark" href="#cli_unhandled_rejections_mode" id="cli_unhandled_rejections_mode">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.17.0</span> </div> <p>By default all unhandled rejections trigger a warning plus a deprecation warning for the very first unhandled rejection in case no <a href="#process_event_unhandledrejection"><code>unhandledRejection</code></a> hook is used.</p> <p>Using this flag allows to change what should happen when an unhandled rejection occurs. One of three modes can be chosen:</p> <ul> <li><code>strict</code>: Raise the unhandled rejection as an uncaught exception.</li> <li><code>warn</code>: Always trigger a warning, no matter if the <a href="#process_event_unhandledrejection"><code>unhandledRejection</code></a> hook is set or not but do not print the deprecation warning.</li> <li><code>none</code>: Silence all warnings.</li> </ul> <h3><code>--use-bundled-ca</code>, <code>--use-openssl-ca</code><span><a class="mark" href="#cli_use_bundled_ca_use_openssl_ca" id="cli_use_bundled_ca_use_openssl_ca">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.11.0</span> </div> <p>Use bundled Mozilla CA store as supplied by current Node.js version or use OpenSSL's default CA store. The default store is selectable at build-time.</p> <p>The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store that is fixed at release time. It is identical on all supported platforms.</p> <p>Using OpenSSL store allows for external modifications of the store. For most Linux and BSD distributions, this store is maintained by the distribution maintainers and system administrators. OpenSSL CA store location is dependent on configuration of the OpenSSL library but this can be altered at runtime using environment variables.</p> <p>See <code>SSL_CERT_DIR</code> and <code>SSL_CERT_FILE</code>.</p> <h3><code>--v8-options</code><span><a class="mark" href="#cli_v8_options" id="cli_v8_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.3</span> </div> <p>Print V8 command line options.</p> <h3><code>--v8-pool-size=num</code><span><a class="mark" href="#cli_v8_pool_size_num" id="cli_v8_pool_size_num">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.10.0</span> </div> <p>Set V8's thread pool size which will be used to allocate background jobs.</p> <p>If set to <code>0</code> then V8 will choose an appropriate size of the thread pool based on the number of online processors.</p> <p>If the value provided is larger than V8's maximum, then the largest value will be chosen.</p> <h3><code>--zero-fill-buffers</code><span><a class="mark" href="#cli_zero_fill_buffers" id="cli_zero_fill_buffers">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <p>Automatically zero-fills all newly allocated <a href="#buffer_class_buffer"><code>Buffer</code></a> and <a href="#buffer_class_slowbuffer"><code>SlowBuffer</code></a> instances.</p> <h3><code>-c</code>, <code>--check</code><span><a class="mark" href="#cli_c_check" id="cli_c_check">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>--require</code> option is now supported when checking a file.</p></td></tr> <tr><td>v5.0.0, v4.2.0</td> <td><p><span>Added in: v5.0.0, v4.2.0</span></p></td></tr> </tbody></table> </details> </div> <p>Syntax check the script without executing.</p> <h3><code>-e</code>, <code>--eval "script"</code><span><a class="mark" href="#cli_e_eval_script" id="cli_e_eval_script">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v5.11.0</td> <td><p>Built-in libraries are now available as predefined variables.</p></td></tr> <tr><td>v0.5.2</td> <td><p><span>Added in: v0.5.2</span></p></td></tr> </tbody></table> </details> </div> <p>Evaluate the following argument as JavaScript. The modules which are predefined in the REPL can also be used in <code>script</code>.</p> <p>On Windows, using <code>cmd.exe</code> a single quote will not work correctly because it only recognizes double <code>"</code> for quoting. In Powershell or Git bash, both <code>'</code> and <code>"</code> are usable.</p> <h3><code>-h</code>, <code>--help</code><span><a class="mark" href="#cli_h_help" id="cli_h_help">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.3</span> </div> <p>Print node command line options. The output of this option is less detailed than this document.</p> <h3><code>-i</code>, <code>--interactive</code><span><a class="mark" href="#cli_i_interactive" id="cli_i_interactive">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <p>Opens the REPL even if stdin does not appear to be a terminal.</p> <h3><code>-p</code>, <code>--print "script"</code><span><a class="mark" href="#cli_p_print_script" id="cli_p_print_script">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v5.11.0</td> <td><p>Built-in libraries are now available as predefined variables.</p></td></tr> <tr><td>v0.6.4</td> <td><p><span>Added in: v0.6.4</span></p></td></tr> </tbody></table> </details> </div> <p>Identical to <code>-e</code> but prints the result.</p> <h3><code>-r</code>, <code>--require module</code><span><a class="mark" href="#cli_r_require_module" id="cli_r_require_module">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.6.0</span> </div> <p>Preload the specified module at startup.</p> <p>Follows <code>require()</code>'s module resolution rules. <code>module</code> may be either a path to a file, or a node module name.</p> <h3><code>-v</code>, <code>--version</code><span><a class="mark" href="#cli_v_version" id="cli_v_version">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.3</span> </div> <p>Print node's version.</p> <h2>Environment Variables<span><a class="mark" href="#cli_environment_variables" id="cli_environment_variables">#</a></span></h2> <h3><code>NODE_DEBUG=module[,…]</code><span><a class="mark" href="#cli_node_debug_module" id="cli_node_debug_module">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.32</span> </div> <p><code>','</code>-separated list of core modules that should print debug information.</p> <h3><code>NODE_DEBUG_NATIVE=module[,…]</code><span><a class="mark" href="#cli_node_debug_native_module" id="cli_node_debug_native_module">#</a></span></h3> <p><code>','</code>-separated list of core C++ modules that should print debug information.</p> <h3><code>NODE_DISABLE_COLORS=1</code><span><a class="mark" href="#cli_node_disable_colors_1" id="cli_node_disable_colors_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <p>When set to <code>1</code> colors will not be used in the REPL.</p> <h3><code>NODE_EXTRA_CA_CERTS=file</code><span><a class="mark" href="#cli_node_extra_ca_certs_file" id="cli_node_extra_ca_certs_file">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.3.0</span> </div> <p>When set, the well known "root" CAs (like VeriSign) will be extended with the extra certificates in <code>file</code>. The file should consist of one or more trusted certificates in PEM format. A message will be emitted (once) with <a href="#process_process_emitwarning_warning_type_code_ctor"><code>process.emitWarning()</code></a> if the file is missing or malformed, but any errors are otherwise ignored.</p> <p>Note that neither the well known nor extra certificates are used when the <code>ca</code> options property is explicitly specified for a TLS or HTTPS client or server.</p> <p>This environment variable is ignored when <code>node</code> runs as setuid root or has Linux file capabilities set.</p> <h3><code>NODE_ICU_DATA=file</code><span><a class="mark" href="#cli_node_icu_data_file" id="cli_node_icu_data_file">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.15</span> </div> <p>Data path for ICU (<code>Intl</code> object) data. Will extend linked-in data when compiled with small-icu support.</p> <h3><code>NODE_NO_WARNINGS=1</code><span><a class="mark" href="#cli_node_no_warnings_1" id="cli_node_no_warnings_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.11.0</span> </div> <p>When set to <code>1</code>, process warnings are silenced.</p> <h3><code>NODE_OPTIONS=options...</code><span><a class="mark" href="#cli_node_options_options" id="cli_node_options_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <p>A space-separated list of command line options. <code>options...</code> are interpreted as if they had been specified on the command line before the actual command line (so they can be overridden). Node.js will exit with an error if an option that is not allowed in the environment is used, such as <code>-p</code> or a script file.</p> <p>In case an option value happens to contain a space (for example a path listed in <code>--require</code>), it must be escaped using double quotes. For example:</p> <pre><code class="language-bash">--require "./my path/file.js" </code></pre> <p>Node.js options that are allowed are:</p> <ul> <li><code>--enable-fips</code></li> <li><code>--experimental-modules</code></li> <li><code>--experimental-repl-await</code></li> <li><code>--experimental-vm-modules</code></li> <li><code>--experimental-worker</code></li> <li><code>--force-fips</code></li> <li><code>--icu-data-dir</code></li> <li><code>--insecure-http-parser</code></li> <li><code>--inspect</code></li> <li><code>--inspect-brk</code></li> <li><code>--inspect-port</code></li> <li><code>--loader</code></li> <li><code>--max-http-header-size</code></li> <li><code>--napi-modules</code></li> <li><code>--no-deprecation</code></li> <li><code>--no-force-async-hooks-checks</code></li> <li><code>--no-warnings</code></li> <li><code>--openssl-config</code></li> <li><code>--pending-deprecation</code></li> <li><code>--redirect-warnings</code></li> <li><code>--require</code>, <code>-r</code></li> <li><code>--throw-deprecation</code></li> <li><code>--title</code></li> <li><code>--tls-cipher-list</code></li> <li><code>--trace-deprecation</code></li> <li><code>--trace-event-categories</code></li> <li><code>--trace-event-file-pattern</code></li> <li><code>--trace-events-enabled</code></li> <li><code>--trace-sync-io</code></li> <li><code>--trace-warnings</code></li> <li><code>--track-heap-objects</code></li> <li><code>--unhandled-rejections</code></li> <li><code>--use-bundled-ca</code></li> <li><code>--use-openssl-ca</code></li> <li><code>--v8-pool-size</code></li> <li><code>--zero-fill-buffers</code></li> </ul> <p>V8 options that are allowed are:</p> <ul> <li><code>--abort-on-uncaught-exception</code></li> <li><code>--max-old-space-size</code></li> <li><code>--perf-basic-prof</code></li> <li><code>--perf-prof</code></li> <li><code>--stack-trace-limit</code></li> </ul> <h3><code>NODE_PATH=path[:…]</code><span><a class="mark" href="#cli_node_path_path" id="cli_node_path_path">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.32</span> </div> <p><code>':'</code>-separated list of directories prefixed to the module search path.</p> <p>On Windows, this is a <code>';'</code>-separated list instead.</p> <h3><code>NODE_PENDING_DEPRECATION=1</code><span><a class="mark" href="#cli_node_pending_deprecation_1" id="cli_node_pending_deprecation_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <p>When set to <code>1</code>, emit pending deprecation warnings.</p> <p>Pending deprecations are generally identical to a runtime deprecation with the notable exception that they are turned <em>off</em> by default and will not be emitted unless either the <code>--pending-deprecation</code> command line flag, or the <code>NODE_PENDING_DEPRECATION=1</code> environment variable, is set. Pending deprecations are used to provide a kind of selective "early warning" mechanism that developers may leverage to detect deprecated API usage.</p> <h3><code>NODE_PRESERVE_SYMLINKS=1</code><span><a class="mark" href="#cli_node_preserve_symlinks_1" id="cli_node_preserve_symlinks_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.1.0</span> </div> <p>When set to <code>1</code>, instructs the module loader to preserve symbolic links when resolving and caching modules.</p> <h3><code>NODE_REDIRECT_WARNINGS=file</code><span><a class="mark" href="#cli_node_redirect_warnings_file" id="cli_node_redirect_warnings_file">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <p>When set, process warnings will be emitted to the given file instead of printing to stderr. The file will be created if it does not exist, and will be appended to if it does. If an error occurs while attempting to write the warning to the file, the warning will be written to stderr instead. This is equivalent to using the <code>--redirect-warnings=file</code> command-line flag.</p> <h3><code>NODE_REPL_HISTORY=file</code><span><a class="mark" href="#cli_node_repl_history_file" id="cli_node_repl_history_file">#</a></span></h3> <div class="api_metadata"> <span>Added in: v3.0.0</span> </div> <p>Path to the file used to store the persistent REPL history. The default path is <code>~/.node_repl_history</code>, which is overridden by this variable. Setting the value to an empty string (<code>''</code> or <code>' '</code>) disables persistent REPL history.</p> <h3><code>NODE_TLS_REJECT_UNAUTHORIZED=value</code><span><a class="mark" href="#cli_node_tls_reject_unauthorized_value" id="cli_node_tls_reject_unauthorized_value">#</a></span></h3> <p>If <code>value</code> equals <code>'0'</code>, certificate validation is disabled for TLS connections. This makes TLS, and HTTPS by extension, insecure. The use of this environment variable is strongly discouraged.</p> <h3><code>NODE_V8_COVERAGE=dir</code><span><a class="mark" href="#cli_node_v8_coverage_dir" id="cli_node_v8_coverage_dir">#</a></span></h3> <p>When set, Node.js will begin outputting <a href="https://v8project.blogspot.com/2017/12/javascript-code-coverage.html">V8 JavaScript code coverage</a> to the directory provided as an argument. Coverage is output as an array of <a href="https://chromedevtools.github.io/devtools-protocol/tot/Profiler#type-ScriptCoverage">ScriptCoverage</a> objects:</p> <pre><code class="language-json">{ "result": [ { "scriptId": "67", "url": "internal/tty.js", "functions": [] } ] } </code></pre> <p><code>NODE_V8_COVERAGE</code> will automatically propagate to subprocesses, making it easier to instrument applications that call the <code>child_process.spawn()</code> family of functions. <code>NODE_V8_COVERAGE</code> can be set to an empty string, to prevent propagation.</p> <p>At this time coverage is only collected in the main thread and will not be output for code executed by worker threads.</p> <h3><code>OPENSSL_CONF=file</code><span><a class="mark" href="#cli_openssl_conf_file" id="cli_openssl_conf_file">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.11.0</span> </div> <p>Load an OpenSSL configuration file on startup. Among other uses, this can be used to enable FIPS-compliant crypto if Node.js is built with <code>./configure --openssl-fips</code>.</p> <p>If the <a href="#cli_openssl_config_file"><code>--openssl-config</code></a> command line option is used, the environment variable is ignored.</p> <h3><code>SSL_CERT_DIR=dir</code><span><a class="mark" href="#cli_ssl_cert_dir_dir" id="cli_ssl_cert_dir_dir">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.7.0</span> </div> <p>If <code>--use-openssl-ca</code> is enabled, this overrides and sets OpenSSL's directory containing trusted certificates.</p> <p>Be aware that unless the child environment is explicitly set, this environment variable will be inherited by any child processes, and if they use OpenSSL, it may cause them to trust the same CAs as node.</p> <h3><code>SSL_CERT_FILE=file</code><span><a class="mark" href="#cli_ssl_cert_file_file" id="cli_ssl_cert_file_file">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.7.0</span> </div> <p>If <code>--use-openssl-ca</code> is enabled, this overrides and sets OpenSSL's file containing trusted certificates.</p> <p>Be aware that unless the child environment is explicitly set, this environment variable will be inherited by any child processes, and if they use OpenSSL, it may cause them to trust the same CAs as node.</p> <h3><code>UV_THREADPOOL_SIZE=size</code><span><a class="mark" href="#cli_uv_threadpool_size_size" id="cli_uv_threadpool_size_size">#</a></span></h3> <p>Set the number of threads used in libuv's threadpool to <code>size</code> threads.</p> <p>Asynchronous system APIs are used by Node.js whenever possible, but where they do not exist, libuv's threadpool is used to create asynchronous node APIs based on synchronous system APIs. Node.js APIs that use the threadpool are:</p> <ul> <li>all <code>fs</code> APIs, other than the file watcher APIs and those that are explicitly synchronous</li> <li><code>crypto.pbkdf2()</code></li> <li><code>crypto.randomBytes()</code>, unless it is used without a callback</li> <li><code>crypto.randomFill()</code></li> <li><code>dns.lookup()</code></li> <li>all <code>zlib</code> APIs, other than those that are explicitly synchronous</li> </ul> <p>Because libuv's threadpool has a fixed size, it means that if for whatever reason any of these APIs takes a long time, other (seemingly unrelated) APIs that run in libuv's threadpool will experience degraded performance. In order to mitigate this issue, one potential solution is to increase the size of libuv's threadpool by setting the <code>'UV_THREADPOOL_SIZE'</code> environment variable to a value greater than <code>4</code> (its current default value). For more information, see the <a href="http://docs.libuv.org/en/latest/threadpool.html">libuv threadpool documentation</a>.</p> <h1>Console<span><a class="mark" href="#console_console" id="console_console">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>console</code> module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.</p> <p>The module exports two specific components:</p> <ul> <li>A <code>Console</code> class with methods such as <code>console.log()</code>, <code>console.error()</code> and <code>console.warn()</code> that can be used to write to any Node.js stream.</li> <li>A global <code>console</code> instance configured to write to <a href="#process_process_stdout"><code>process.stdout</code></a> and <a href="#process_process_stderr"><code>process.stderr</code></a>. The global <code>console</code> can be used without calling <code>require('console')</code>.</li> </ul> <p><strong><em>Warning</em></strong>: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the <a href="#process_a_note_on_process_i_o">note on process I/O</a> for more information.</p> <p>Example using the global <code>console</code>:</p> <pre><code class="language-js">console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to stderr const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr </code></pre> <p>Example using the <code>Console</code> class:</p> <pre><code class="language-js">const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err </code></pre> <h2>Class: Console<span><a class="mark" href="#console_class_console" id="console_class_console">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Errors that occur while writing to the underlying streams will now be ignored by default.</p></td></tr> </tbody></table> </details> </div> <p>The <code>Console</code> class can be used to create a simple logger with configurable output streams and can be accessed using either <code>require('console').Console</code> or <code>console.Console</code> (or their destructured counterparts):</p> <pre><code class="language-js">const { Console } = require('console'); </code></pre> <pre><code class="language-js">const { Console } = console; </code></pre> <h3>new Console(stdout[, stderr][, ignoreerrors])<span><a class="mark" href="#console_new_console_stdout_stderr_ignoreerrors" id="console_new_console_stdout_stderr_ignoreerrors">#</a></span></h3> <h3>new Console(options)<span><a class="mark" href="#console_new_console_options" id="console_new_console_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>Console</code> constructor now supports an <code>options</code> argument, and the <code>colorMode</code> option was introduced.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>ignoreErrors</code> option was introduced.</p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>stdout</code> <a href="#stream_class_stream_writable" class="type"><stream.Writable></a></li> <li><code>stderr</code> <a href="#stream_class_stream_writable" class="type"><stream.Writable></a></li> <li><code>ignoreErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Ignore errors when writing to the underlying streams. <strong>Default:</strong> <code>true</code>.</li> <li><code>colorMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Set color support for this <code>Console</code> instance. Setting to <code>true</code> enables coloring while inspecting values, setting to <code>'auto'</code> will make color support depend on the value of the <code>isTTY</code> property and the value returned by <code>getColorDepth()</code> on the respective stream. <strong>Default:</strong> <code>'auto'</code>.</li> </ul> </li> </ul> <p>Creates a new <code>Console</code> with one or two writable stream instances. <code>stdout</code> is a writable stream to print log or info output. <code>stderr</code> is used for warning or error output. If <code>stderr</code> is not provided, <code>stdout</code> is used for <code>stderr</code>.</p> <pre><code class="language-js">const output = fs.createWriteStream('./stdout.log'); const errorOutput = fs.createWriteStream('./stderr.log'); // custom simple logger const logger = new Console({ stdout: output, stderr: errorOutput }); // use it like console const count = 5; logger.log('count: %d', count); // in stdout.log: count 5 </code></pre> <p>The global <code>console</code> is a special <code>Console</code> whose output is sent to <a href="#process_process_stdout"><code>process.stdout</code></a> and <a href="#process_process_stderr"><code>process.stderr</code></a>. It is equivalent to calling:</p> <pre><code class="language-js">new Console({ stdout: process.stdout, stderr: process.stderr }); </code></pre> <h3>console.assert(value[, ...message])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L287">[src]</a><span><a class="mark" href="#console_console_assert_value_message" id="console_console_assert_value_message">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The implementation is now spec compliant and does not throw anymore.</p></td></tr> <tr><td>v0.1.101</td> <td><p><span>Added in: v0.1.101</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The value tested for being truthy.</li> <li><code>...message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> All arguments besides <code>value</code> are used as error message.</li> </ul> <p>A simple assertion test that verifies whether <code>value</code> is truthy. If it is not, <code>Assertion failed</code> is logged. If provided, the error <code>message</code> is formatted using <a href="#util_util_format_format_args"><code>util.format()</code></a> by passing along all message arguments. The output is used as the error message.</p> <pre><code class="language-js">console.assert(true, 'does nothing'); // OK console.assert(false, 'Whoops %s work', 'didn\'t'); // Assertion failed: Whoops didn't work </code></pre> <p>Calling <code>console.assert()</code> with a falsy assertion will only cause the <code>message</code> to be printed to the console without interrupting execution of subsequent code.</p> <h3>console.clear()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L295">[src]</a><span><a class="mark" href="#console_console_clear" id="console_console_clear">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.3.0</span> </div> <p>When <code>stdout</code> is a TTY, calling <code>console.clear()</code> will attempt to clear the TTY. When <code>stdout</code> is not a TTY, this method does nothing.</p> <p>The specific operation of <code>console.clear()</code> can vary across operating systems and terminal types. For most Linux operating systems, <code>console.clear()</code> operates similarly to the <code>clear</code> shell command. On Windows, <code>console.clear()</code> will clear only the output in the current terminal viewport for the Node.js binary.</p> <h3>console.count([label])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L308">[src]</a><span><a class="mark" href="#console_console_count_label" id="console_console_count_label">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.3.0</span> </div> <ul> <li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The display label for the counter. <strong>Default:</strong> <code>'default'</code>.</li> </ul> <p>Maintains an internal counter specific to <code>label</code> and outputs to <code>stdout</code> the number of times <code>console.count()</code> has been called with the given <code>label</code>.</p> <!-- eslint-skip --> <pre><code class="language-js">> console.count() default: 1 undefined > console.count('default') default: 2 undefined > console.count('abc') abc: 1 undefined > console.count('xyz') xyz: 1 undefined > console.count('abc') abc: 2 undefined > console.count() default: 3 undefined > </code></pre> <h3>console.countReset([label])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L327">[src]</a><span><a class="mark" href="#console_console_countreset_label" id="console_console_countreset_label">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.3.0</span> </div> <ul> <li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The display label for the counter. <strong>Default:</strong> <code>'default'</code>.</li> </ul> <p>Resets the internal counter specific to <code>label</code>.</p> <!-- eslint-skip --> <pre><code class="language-js">> console.count('abc'); abc: 1 undefined > console.countReset('abc'); undefined > console.count('abc'); abc: 1 undefined > </code></pre> <h3>console.debug(data[, ...args])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L213">[src]</a><span><a class="mark" href="#console_console_debug_data_args" id="console_console_debug_data_args">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.3.0</td> <td><p><code>console.debug</code> is now an alias for <code>console.log</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p><span>Added in: v8.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>The <code>console.debug()</code> function is an alias for <a href="#console_console_log_data_args"><code>console.log()</code></a>.</p> <h3>console.dir(obj[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L226">[src]</a><span><a class="mark" href="#console_console_dir_obj_options" id="console_console_dir_obj_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.101</span> </div> <ul> <li><code>obj</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>showHidden</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code> then the object's non-enumerable and symbol properties will be shown too. <strong>Default:</strong> <code>false</code>.</li> <li><code>depth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Tells <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> how many times to recurse while formatting the object. This is useful for inspecting large complicated objects. To make it recurse indefinitely, pass <code>null</code>. <strong>Default:</strong> <code>2</code>.</li> <li><code>colors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, then the output will be styled with ANSI color codes. Colors are customizable; see <a href="#util_customizing_util_inspect_colors">customizing <code>util.inspect()</code> colors</a>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> </ul> <p>Uses <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> on <code>obj</code> and prints the resulting string to <code>stdout</code>. This function bypasses any custom <code>inspect()</code> function defined on <code>obj</code>.</p> <h3>console.dirxml(...data)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L215">[src]</a><span><a class="mark" href="#console_console_dirxml_data" id="console_console_dirxml_data">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.3.0</td> <td><p><code>console.dirxml</code> now calls <code>console.log</code> for its arguments.</p></td></tr> <tr><td>v8.0.0</td> <td><p><span>Added in: v8.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>...data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>This method calls <code>console.log()</code> passing it the arguments received. Please note that this method does not produce any XML formatting.</p> <h3>console.error([data][, ...args])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L224">[src]</a><span><a class="mark" href="#console_console_error_data_args" id="console_console_error_data_args">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.100</span> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Prints to <code>stderr</code> with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to <a href="http://man7.org/linux/man-pages/man3/printf.3.html"><code>printf(3)</code></a> (the arguments are all passed to <a href="#util_util_format_format_args"><code>util.format()</code></a>).</p> <pre><code class="language-js">const code = 5; console.error('error #%d', code); // Prints: error #5, to stderr console.error('error', code); // Prints: error 5, to stderr </code></pre> <p>If formatting elements (e.g. <code>%d</code>) are not found in the first string then <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> is called on each argument and the resulting string values are concatenated. See <a href="#util_util_format_format_args"><code>util.format()</code></a> for more information.</p> <h3>console.group([...label])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L333">[src]</a><span><a class="mark" href="#console_console_group_label" id="console_console_group_label">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>...label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Increases indentation of subsequent lines by two spaces.</p> <p>If one or more <code>label</code>s are provided, those are printed first without the additional indentation.</p> <h3>console.groupCollapsed()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L339">[src]</a><span><a class="mark" href="#console_console_groupcollapsed" id="console_console_groupcollapsed">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <p>An alias for <a href="#console_console_group_label"><code>console.group()</code></a>.</p> <h3>console.groupEnd()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L341">[src]</a><span><a class="mark" href="#console_console_groupend" id="console_console_groupend">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <p>Decreases indentation of subsequent lines by two spaces.</p> <h3>console.info([data][, ...args])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L214">[src]</a><span><a class="mark" href="#console_console_info_data_args" id="console_console_info_data_args">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.100</span> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>The <code>console.info()</code> function is an alias for <a href="#console_console_log_data_args"><code>console.log()</code></a>.</p> <h3>console.log([data][, ...args])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L206">[src]</a><span><a class="mark" href="#console_console_log_data_args" id="console_console_log_data_args">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.100</span> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Prints to <code>stdout</code> with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to <a href="http://man7.org/linux/man-pages/man3/printf.3.html"><code>printf(3)</code></a> (the arguments are all passed to <a href="#util_util_format_format_args"><code>util.format()</code></a>).</p> <pre><code class="language-js">const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout </code></pre> <p>See <a href="#util_util_format_format_args"><code>util.format()</code></a> for more information.</p> <h3>console.table(tabularData[, properties])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L355">[src]</a><span><a class="mark" href="#console_console_table_tabulardata_properties" id="console_console_table_tabulardata_properties">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>tabularData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>properties</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Alternate properties for constructing the table.</li> </ul> <p>Try to construct a table with the columns of the properties of <code>tabularData</code> (or use <code>properties</code>) and rows of <code>tabularData</code> and log it. Falls back to just logging the argument if it can’t be parsed as tabular.</p> <pre><code class="language-js">// These can't be parsed as tabular data console.table(Symbol()); // Symbol() console.table(undefined); // undefined console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); // ┌─────────┬─────┬─────┐ // │ (index) │ a │ b │ // ├─────────┼─────┼─────┤ // │ 0 │ 1 │ 'Y' │ // │ 1 │ 'Z' │ 2 │ // └─────────┴─────┴─────┘ console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); // ┌─────────┬─────┐ // │ (index) │ a │ // ├─────────┼─────┤ // │ 0 │ 1 │ // │ 1 │ 'Z' │ // └─────────┴─────┘ </code></pre> <h3>console.time([label])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L237">[src]</a><span><a class="mark" href="#console_console_time_label" id="console_console_time_label">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.104</span> </div> <ul> <li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'default'</code></li> </ul> <p>Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique <code>label</code>. Use the same <code>label</code> when calling <a href="#console_console_timeend_label"><code>console.timeEnd()</code></a> to stop the timer and output the elapsed time in milliseconds to <code>stdout</code>. Timer durations are accurate to the sub-millisecond.</p> <h3>console.timeEnd([label])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L244">[src]</a><span><a class="mark" href="#console_console_timeend_label" id="console_console_timeend_label">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>This method no longer supports multiple calls that don’t map to individual <code>console.time()</code> calls; see below for details.</p></td></tr> <tr><td>v0.1.104</td> <td><p><span>Added in: v0.1.104</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'default'</code></li> </ul> <p>Stops a timer that was previously started by calling <a href="#console_console_time_label"><code>console.time()</code></a> and prints the result to <code>stdout</code>:</p> <pre><code class="language-js">console.time('100-elements'); for (let i = 0; i < 100; i++) {} console.timeEnd('100-elements'); // prints 100-elements: 225.438ms </code></pre> <h3>console.timeLog([label][, ...data])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L254">[src]</a><span><a class="mark" href="#console_console_timelog_label_data" id="console_console_timelog_label_data">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.7.0</span> </div> <ul> <li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'default'</code></li> <li><code>...data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>For a timer that was previously started by calling <a href="#console_console_time_label"><code>console.time()</code></a>, prints the elapsed time and other <code>data</code> arguments to <code>stdout</code>:</p> <pre><code class="language-js">console.time('process'); const value = expensiveProcess1(); // Returns 42 console.timeLog('process', value); // Prints "process: 365.227ms 42". doExpensiveProcess2(value); console.timeEnd('process'); </code></pre> <h3>console.trace([message][, ...args])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L278">[src]</a><span><a class="mark" href="#console_console_trace_message_args" id="console_console_trace_message_args">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.104</span> </div> <ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Prints to <code>stderr</code> the string <code>'Trace: '</code>, followed by the <a href="#util_util_format_format_args"><code>util.format()</code></a> formatted message and stack trace to the current position in the code.</p> <pre><code class="language-js">console.trace('Show me'); // Prints: (stack trace will vary based on where trace is called) // Trace: Show me // at repl:2:9 // at REPLServer.defaultEval (repl.js:248:27) // at bound (domain.js:287:14) // at REPLServer.runBound [as eval] (domain.js:300:12) // at REPLServer.<anonymous> (repl.js:412:12) // at emitOne (events.js:82:20) // at REPLServer.emit (events.js:169:7) // at REPLServer.Interface._onLine (readline.js:210:10) // at REPLServer.Interface._line (readline.js:549:8) // at REPLServer.Interface._ttyWrite (readline.js:826:14) </code></pre> <h3>console.warn([data][, ...args])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/console.js#L217">[src]</a><span><a class="mark" href="#console_console_warn_data_args" id="console_console_warn_data_args">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.100</span> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>The <code>console.warn()</code> function is an alias for <a href="#console_console_error_data_args"><code>console.error()</code></a>.</p> <h2>Inspector only methods<span><a class="mark" href="#console_inspector_only_methods" id="console_inspector_only_methods">#</a></span></h2> <p>The following methods are exposed by the V8 engine in the general API but do not display anything unless used in conjunction with the <a href="debugger.html">inspector</a> (<code>--inspect</code> flag).</p> <h3>console.markTimeline([label])<span><a class="mark" href="#console_console_marktimeline_label" id="console_console_marktimeline_label">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'default'</code></li> </ul> <p>This method does not display anything unless used in the inspector. The <code>console.markTimeline()</code> method is the deprecated form of <a href="#console_console_timestamp_label"><code>console.timeStamp()</code></a>.</p> <h3>console.profile([label])<span><a class="mark" href="#console_console_profile_label" id="console_console_profile_label">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>This method does not display anything unless used in the inspector. The <code>console.profile()</code> method starts a JavaScript CPU profile with an optional label until <a href="#console_console_profileend_label"><code>console.profileEnd()</code></a> is called. The profile is then added to the <strong>Profile</strong> panel of the inspector.</p> <pre><code class="language-js">console.profile('MyLabel'); // Some code console.profileEnd('MyLabel'); // Adds the profile 'MyLabel' to the Profiles panel of the inspector. </code></pre> <h3>console.profileEnd([label])<span><a class="mark" href="#console_console_profileend_label" id="console_console_profileend_label">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>This method does not display anything unless used in the inspector. Stops the current JavaScript CPU profiling session if one has been started and prints the report to the <strong>Profiles</strong> panel of the inspector. See <a href="#console_console_profile_label"><code>console.profile()</code></a> for an example.</p> <p>If this method is called without a label, the most recently started profile is stopped.</p> <h3>console.timeStamp([label])<span><a class="mark" href="#console_console_timestamp_label" id="console_console_timestamp_label">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>This method does not display anything unless used in the inspector. The <code>console.timeStamp()</code> method adds an event with the label <code>'label'</code> to the <strong>Timeline</strong> panel of the inspector.</p> <h3>console.timeline([label])<span><a class="mark" href="#console_console_timeline_label" id="console_console_timeline_label">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'default'</code></li> </ul> <p>This method does not display anything unless used in the inspector. The <code>console.timeline()</code> method is the deprecated form of <a href="#console_console_time_label"><code>console.time()</code></a>.</p> <h3>console.timelineEnd([label])<span><a class="mark" href="#console_console_timelineend_label" id="console_console_timelineend_label">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'default'</code></li> </ul> <p>This method does not display anything unless used in the inspector. The <code>console.timelineEnd()</code> method is the deprecated form of <a href="#console_console_timeend_label"><code>console.timeEnd()</code></a>.</p> <h1>Crypto<span><a class="mark" href="#crypto_crypto" id="crypto_crypto">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>crypto</code> module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.</p> <p>Use <code>require('crypto')</code> to access this module.</p> <pre><code class="language-js">const crypto = require('crypto'); const secret = 'abcdefg'; const hash = crypto.createHmac('sha256', secret) .update('I love cupcakes') .digest('hex'); console.log(hash); // Prints: // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e </code></pre> <h2>Determining if crypto support is unavailable<span><a class="mark" href="#crypto_determining_if_crypto_support_is_unavailable" id="crypto_determining_if_crypto_support_is_unavailable">#</a></span></h2> <p>It is possible for Node.js to be built without including support for the <code>crypto</code> module. In such cases, calling <code>require('crypto')</code> will result in an error being thrown.</p> <pre><code class="language-js">let crypto; try { crypto = require('crypto'); } catch (err) { console.log('crypto support is disabled!'); } </code></pre> <h2>Class: Certificate<span><a class="mark" href="#crypto_class_certificate" id="crypto_class_certificate">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.8</span> </div> <p>SPKAC is a Certificate Signing Request mechanism originally implemented by Netscape and was specified formally as part of <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen">HTML5's <code>keygen</code> element</a>.</p> <p>Note that <code><keygen></code> is deprecated since <a href="https://www.w3.org/TR/html52/changes.html#features-removed">HTML 5.2</a> and new projects should not use this element anymore.</p> <p>The <code>crypto</code> module provides the <code>Certificate</code> class for working with SPKAC data. The most common usage is handling output generated by the HTML5 <code><keygen></code> element. Node.js uses <a href="https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html">OpenSSL's SPKAC implementation</a> internally.</p> <h3>Certificate.exportChallenge(spkac)<span><a class="mark" href="#crypto_certificate_exportchallenge_spkac" id="crypto_certificate_exportchallenge_spkac">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span> </div> <ul> <li><code>spkac</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> The challenge component of the <code>spkac</code> data structure, which includes a public key and a challenge.</li> </ul> <pre><code class="language-js">const { Certificate } = require('crypto'); const spkac = getSpkacSomehow(); const challenge = Certificate.exportChallenge(spkac); console.log(challenge.toString('utf8')); // Prints: the challenge as a UTF8 string </code></pre> <h3>Certificate.exportPublicKey(spkac[, encoding])<span><a class="mark" href="#crypto_certificate_exportpublickey_spkac_encoding" id="crypto_certificate_exportpublickey_spkac_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span> </div> <ul> <li><code>spkac</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>spkac</code> string.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> The public key component of the <code>spkac</code> data structure, which includes a public key and a challenge.</li> </ul> <pre><code class="language-js">const { Certificate } = require('crypto'); const spkac = getSpkacSomehow(); const publicKey = Certificate.exportPublicKey(spkac); console.log(publicKey); // Prints: the public key as <Buffer ...> </code></pre> <h3>Certificate.verifySpkac(spkac)<span><a class="mark" href="#crypto_certificate_verifyspkac_spkac" id="crypto_certificate_verifyspkac_spkac">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span> </div> <ul> <li><code>spkac</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the given <code>spkac</code> data structure is valid, <code>false</code> otherwise.</li> </ul> <pre><code class="language-js">const { Certificate } = require('crypto'); const spkac = getSpkacSomehow(); console.log(Certificate.verifySpkac(Buffer.from(spkac))); // Prints: true or false </code></pre> <h3>Legacy API<span><a class="mark" href="#crypto_legacy_api" id="crypto_legacy_api">#</a></span></h3> <p>As a still supported legacy interface, it is possible (but not recommended) to create new instances of the <code>crypto.Certificate</code> class as illustrated in the examples below.</p> <h4>new crypto.Certificate()<span><a class="mark" href="#crypto_new_crypto_certificate" id="crypto_new_crypto_certificate">#</a></span></h4> <p>Instances of the <code>Certificate</code> class can be created using the <code>new</code> keyword or by calling <code>crypto.Certificate()</code> as a function:</p> <pre><code class="language-js">const crypto = require('crypto'); const cert1 = new crypto.Certificate(); const cert2 = crypto.Certificate(); </code></pre> <h4>certificate.exportChallenge(spkac)<span><a class="mark" href="#crypto_certificate_exportchallenge_spkac_1" id="crypto_certificate_exportchallenge_spkac_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.8</span> </div> <ul> <li><code>spkac</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> The challenge component of the <code>spkac</code> data structure, which includes a public key and a challenge.</li> </ul> <pre><code class="language-js">const cert = require('crypto').Certificate(); const spkac = getSpkacSomehow(); const challenge = cert.exportChallenge(spkac); console.log(challenge.toString('utf8')); // Prints: the challenge as a UTF8 string </code></pre> <h4>certificate.exportPublicKey(spkac)<span><a class="mark" href="#crypto_certificate_exportpublickey_spkac" id="crypto_certificate_exportpublickey_spkac">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.8</span> </div> <ul> <li><code>spkac</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> The public key component of the <code>spkac</code> data structure, which includes a public key and a challenge.</li> </ul> <pre><code class="language-js">const cert = require('crypto').Certificate(); const spkac = getSpkacSomehow(); const publicKey = cert.exportPublicKey(spkac); console.log(publicKey); // Prints: the public key as <Buffer ...> </code></pre> <h4>certificate.verifySpkac(spkac)<span><a class="mark" href="#crypto_certificate_verifyspkac_spkac_1" id="crypto_certificate_verifyspkac_spkac_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.8</span> </div> <ul> <li><code>spkac</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the given <code>spkac</code> data structure is valid, <code>false</code> otherwise.</li> </ul> <pre><code class="language-js">const cert = require('crypto').Certificate(); const spkac = getSpkacSomehow(); console.log(cert.verifySpkac(Buffer.from(spkac))); // Prints: true or false </code></pre> <h2>Class: Cipher<span><a class="mark" href="#crypto_class_cipher" id="crypto_class_cipher">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.94</span> </div> <p>Instances of the <code>Cipher</code> class are used to encrypt data. The class can be used in one of two ways:</p> <ul> <li>As a <a href="stream.html">stream</a> that is both readable and writable, where plain unencrypted data is written to produce encrypted data on the readable side, or</li> <li>Using the <a href="#crypto_cipher_update_data_inputencoding_outputencoding"><code>cipher.update()</code></a> and <a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> methods to produce the encrypted data.</li> </ul> <p>The <a href="#crypto_crypto_createcipher_algorithm_password_options"><code>crypto.createCipher()</code></a> or <a href="#crypto_crypto_createcipheriv_algorithm_key_iv_options"><code>crypto.createCipheriv()</code></a> methods are used to create <code>Cipher</code> instances. <code>Cipher</code> objects are not to be created directly using the <code>new</code> keyword.</p> <p>Example: Using <code>Cipher</code> objects as streams:</p> <pre><code class="language-js">const crypto = require('crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Key length is dependent on the algorithm. In this case for aes192, it is // 24 bytes (192 bits). // Use async `crypto.scrypt()` instead. const key = crypto.scryptSync(password, 'salt', 24); // Use `crypto.randomBytes()` to generate a random iv instead of the static iv // shown here. const iv = Buffer.alloc(16, 0); // Initialization vector. const cipher = crypto.createCipheriv(algorithm, key, iv); let encrypted = ''; cipher.on('readable', () => { let chunk; while (null !== (chunk = cipher.read())) { encrypted += chunk.toString('hex'); } }); cipher.on('end', () => { console.log(encrypted); // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa }); cipher.write('some clear text data'); cipher.end(); </code></pre> <p>Example: Using <code>Cipher</code> and piped streams:</p> <pre><code class="language-js">const crypto = require('crypto'); const fs = require('fs'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Use the async `crypto.scrypt()` instead. const key = crypto.scryptSync(password, 'salt', 24); // Use `crypto.randomBytes()` to generate a random iv instead of the static iv // shown here. const iv = Buffer.alloc(16, 0); // Initialization vector. const cipher = crypto.createCipheriv(algorithm, key, iv); const input = fs.createReadStream('test.js'); const output = fs.createWriteStream('test.enc'); input.pipe(cipher).pipe(output); </code></pre> <p>Example: Using the <a href="#crypto_cipher_update_data_inputencoding_outputencoding"><code>cipher.update()</code></a> and <a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> methods:</p> <pre><code class="language-js">const crypto = require('crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Use the async `crypto.scrypt()` instead. const key = crypto.scryptSync(password, 'salt', 24); // Use `crypto.randomBytes` to generate a random iv instead of the static iv // shown here. const iv = Buffer.alloc(16, 0); // Initialization vector. const cipher = crypto.createCipheriv(algorithm, key, iv); let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); encrypted += cipher.final('hex'); console.log(encrypted); // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa </code></pre> <h3>cipher.final([outputEncoding])<span><a class="mark" href="#crypto_cipher_final_outputencoding" id="crypto_cipher_final_outputencoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.94</span> </div> <ul> <li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Any remaining enciphered contents. If <code>outputEncoding</code> is specified, a string is returned. If an <code>outputEncoding</code> is not provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</li> </ul> <p>Once the <code>cipher.final()</code> method has been called, the <code>Cipher</code> object can no longer be used to encrypt data. Attempts to call <code>cipher.final()</code> more than once will result in an error being thrown.</p> <h3>cipher.setAAD(buffer[, options])<span><a class="mark" href="#crypto_cipher_setaad_buffer_options" id="crypto_cipher_setaad_buffer_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.0.0</span> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></p> <ul> <li><code>plaintextLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> </li> <li>Returns: <a href="#crypto_class_cipher" class="type"><Cipher></a> for method chaining.</li> </ul> <p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code> and <code>OCB</code> are currently supported), the <code>cipher.setAAD()</code> method sets the value used for the <em>additional authenticated data</em> (AAD) input parameter.</p> <p>The <code>options</code> argument is optional for <code>GCM</code> and <code>OCB</code>. When using <code>CCM</code>, the <code>plaintextLength</code> option must be specified and its value must match the length of the plaintext in bytes. See <a href="#crypto_ccm_mode">CCM mode</a>.</p> <p>The <code>cipher.setAAD()</code> method must be called before <a href="#crypto_cipher_update_data_inputencoding_outputencoding"><code>cipher.update()</code></a>.</p> <h3>cipher.getAuthTag()<span><a class="mark" href="#crypto_cipher_getauthtag" id="crypto_cipher_getauthtag">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.0.0</span> </div> <ul> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code> and <code>OCB</code> are currently supported), the <code>cipher.getAuthTag()</code> method returns a <a href="buffer.html"><code>Buffer</code></a> containing the <em>authentication tag</em> that has been computed from the given data.</li> </ul> <p>The <code>cipher.getAuthTag()</code> method should only be called after encryption has been completed using the <a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> method.</p> <h3>cipher.setAutoPadding([autoPadding])<span><a class="mark" href="#crypto_cipher_setautopadding_autopadding" id="crypto_cipher_setautopadding_autopadding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.1</span> </div> <ul> <li><code>autoPadding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code></li> <li>Returns: <a href="#crypto_class_cipher" class="type"><Cipher></a> for method chaining.</li> </ul> <p>When using block encryption algorithms, the <code>Cipher</code> class will automatically add padding to the input data to the appropriate block size. To disable the default padding call <code>cipher.setAutoPadding(false)</code>.</p> <p>When <code>autoPadding</code> is <code>false</code>, the length of the entire input data must be a multiple of the cipher's block size or <a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> will throw an error. Disabling automatic padding is useful for non-standard padding, for instance using <code>0x0</code> instead of PKCS padding.</p> <p>The <code>cipher.setAutoPadding()</code> method must be called before <a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a>.</p> <h3>cipher.update(data[, inputEncoding][, outputencoding])<span><a class="mark" href="#crypto_cipher_update_data_inputencoding_outputencoding" id="crypto_cipher_update_data_inputencoding_outputencoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr> <tr><td>v0.1.94</td> <td><p><span>Added in: v0.1.94</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the data.</li> <li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Updates the cipher with <code>data</code>. If the <code>inputEncoding</code> argument is given, the <code>data</code> argument is a string using the specified encoding. If the <code>inputEncoding</code> argument is not given, <code>data</code> must be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>, then <code>inputEncoding</code> is ignored.</p> <p>The <code>outputEncoding</code> specifies the output format of the enciphered data. If the <code>outputEncoding</code> is specified, a string using the specified encoding is returned. If no <code>outputEncoding</code> is provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <p>The <code>cipher.update()</code> method can be called multiple times with new data until <a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> is called. Calling <code>cipher.update()</code> after <a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> will result in an error being thrown.</p> <h2>Class: Decipher<span><a class="mark" href="#crypto_class_decipher" id="crypto_class_decipher">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.94</span> </div> <p>Instances of the <code>Decipher</code> class are used to decrypt data. The class can be used in one of two ways:</p> <ul> <li>As a <a href="stream.html">stream</a> that is both readable and writable, where plain encrypted data is written to produce unencrypted data on the readable side, or</li> <li>Using the <a href="#crypto_decipher_update_data_inputencoding_outputencoding"><code>decipher.update()</code></a> and <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> methods to produce the unencrypted data.</li> </ul> <p>The <a href="#crypto_crypto_createdecipher_algorithm_password_options"><code>crypto.createDecipher()</code></a> or <a href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options"><code>crypto.createDecipheriv()</code></a> methods are used to create <code>Decipher</code> instances. <code>Decipher</code> objects are not to be created directly using the <code>new</code> keyword.</p> <p>Example: Using <code>Decipher</code> objects as streams:</p> <pre><code class="language-js">const crypto = require('crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Key length is dependent on the algorithm. In this case for aes192, it is // 24 bytes (192 bits). // Use the async `crypto.scrypt()` instead. const key = crypto.scryptSync(password, 'salt', 24); // The IV is usually passed along with the ciphertext. const iv = Buffer.alloc(16, 0); // Initialization vector. const decipher = crypto.createDecipheriv(algorithm, key, iv); let decrypted = ''; decipher.on('readable', () => { while (null !== (chunk = decipher.read())) { decrypted += chunk.toString('utf8'); } }); decipher.on('end', () => { console.log(decrypted); // Prints: some clear text data }); // Encrypted with same algorithm, key and iv. const encrypted = 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; decipher.write(encrypted, 'hex'); decipher.end(); </code></pre> <p>Example: Using <code>Decipher</code> and piped streams:</p> <pre><code class="language-js">const crypto = require('crypto'); const fs = require('fs'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Use the async `crypto.scrypt()` instead. const key = crypto.scryptSync(password, 'salt', 24); // The IV is usually passed along with the ciphertext. const iv = Buffer.alloc(16, 0); // Initialization vector. const decipher = crypto.createDecipheriv(algorithm, key, iv); const input = fs.createReadStream('test.enc'); const output = fs.createWriteStream('test.js'); input.pipe(decipher).pipe(output); </code></pre> <p>Example: Using the <a href="#crypto_decipher_update_data_inputencoding_outputencoding"><code>decipher.update()</code></a> and <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> methods:</p> <pre><code class="language-js">const crypto = require('crypto'); const algorithm = 'aes-192-cbc'; const password = 'Password used to generate key'; // Use the async `crypto.scrypt()` instead. const key = crypto.scryptSync(password, 'salt', 24); // The IV is usually passed along with the ciphertext. const iv = Buffer.alloc(16, 0); // Initialization vector. const decipher = crypto.createDecipheriv(algorithm, key, iv); // Encrypted using same algorithm, key and iv. const encrypted = 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; let decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); console.log(decrypted); // Prints: some clear text data </code></pre> <h3>decipher.final([outputEncoding])<span><a class="mark" href="#crypto_decipher_final_outputencoding" id="crypto_decipher_final_outputencoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.94</span> </div> <ul> <li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Any remaining deciphered contents. If <code>outputEncoding</code> is specified, a string is returned. If an <code>outputEncoding</code> is not provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</li> </ul> <p>Once the <code>decipher.final()</code> method has been called, the <code>Decipher</code> object can no longer be used to decrypt data. Attempts to call <code>decipher.final()</code> more than once will result in an error being thrown.</p> <h3>decipher.setAAD(buffer[, options])<span><a class="mark" href="#crypto_decipher_setaad_buffer_options" id="crypto_decipher_setaad_buffer_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.2.0</td> <td><p>This method now returns a reference to <code>decipher</code>.</p></td></tr> <tr><td>v1.0.0</td> <td><p><span>Added in: v1.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></p> <ul> <li><code>plaintextLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> </li> <li>Returns: <a href="#crypto_class_decipher" class="type"><Decipher></a> for method chaining.</li> </ul> <p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code> and <code>OCB</code> are currently supported), the <code>decipher.setAAD()</code> method sets the value used for the <em>additional authenticated data</em> (AAD) input parameter.</p> <p>The <code>options</code> argument is optional for <code>GCM</code>. When using <code>CCM</code>, the <code>plaintextLength</code> option must be specified and its value must match the length of the plaintext in bytes. See <a href="#crypto_ccm_mode">CCM mode</a>.</p> <p>The <code>decipher.setAAD()</code> method must be called before <a href="#crypto_decipher_update_data_inputencoding_outputencoding"><code>decipher.update()</code></a>.</p> <h3>decipher.setAuthTag(buffer)<span><a class="mark" href="#crypto_decipher_setauthtag_buffer" id="crypto_decipher_setauthtag_buffer">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.2.0</td> <td><p>This method now returns a reference to <code>decipher</code>.</p></td></tr> <tr><td>v1.0.0</td> <td><p><span>Added in: v1.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li>Returns: <a href="#crypto_class_decipher" class="type"><Decipher></a> for method chaining.</li> </ul> <p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code> and <code>OCB</code> are currently supported), the <code>decipher.setAuthTag()</code> method is used to pass in the received <em>authentication tag</em>. If no tag is provided, or if the cipher text has been tampered with, <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> will throw, indicating that the cipher text should be discarded due to failed authentication.</p> <p>Note that this Node.js version does not verify the length of GCM authentication tags. Such a check <em>must</em> be implemented by applications and is crucial to the authenticity of the encrypted data, otherwise, an attacker can use an arbitrarily short authentication tag to increase the chances of successfully passing authentication (up to 0.39%). It is highly recommended to associate one of the values 16, 15, 14, 13, 12, 8 or 4 bytes with each key, and to only permit authentication tags of that length, see <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf">NIST SP 800-38D</a>.</p> <p>The <code>decipher.setAuthTag()</code> method must be called before <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a>.</p> <h3>decipher.setAutoPadding([autoPadding])<span><a class="mark" href="#crypto_decipher_setautopadding_autopadding" id="crypto_decipher_setautopadding_autopadding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.1</span> </div> <ul> <li><code>autoPadding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code></li> <li>Returns: <a href="#crypto_class_decipher" class="type"><Decipher></a> for method chaining.</li> </ul> <p>When data has been encrypted without standard block padding, calling <code>decipher.setAutoPadding(false)</code> will disable automatic padding to prevent <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> from checking for and removing padding.</p> <p>Turning auto padding off will only work if the input data's length is a multiple of the ciphers block size.</p> <p>The <code>decipher.setAutoPadding()</code> method must be called before <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a>.</p> <h3>decipher.update(data[, inputEncoding][, outputencoding])<span><a class="mark" href="#crypto_decipher_update_data_inputencoding_outputencoding" id="crypto_decipher_update_data_inputencoding_outputencoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr> <tr><td>v0.1.94</td> <td><p><span>Added in: v0.1.94</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>data</code> string.</li> <li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Updates the decipher with <code>data</code>. If the <code>inputEncoding</code> argument is given, the <code>data</code> argument is a string using the specified encoding. If the <code>inputEncoding</code> argument is not given, <code>data</code> must be a <a href="buffer.html"><code>Buffer</code></a>. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a> then <code>inputEncoding</code> is ignored.</p> <p>The <code>outputEncoding</code> specifies the output format of the enciphered data. If the <code>outputEncoding</code> is specified, a string using the specified encoding is returned. If no <code>outputEncoding</code> is provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <p>The <code>decipher.update()</code> method can be called multiple times with new data until <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> is called. Calling <code>decipher.update()</code> after <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> will result in an error being thrown.</p> <h2>Class: DiffieHellman<span><a class="mark" href="#crypto_class_diffiehellman" id="crypto_class_diffiehellman">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <p>The <code>DiffieHellman</code> class is a utility for creating Diffie-Hellman key exchanges.</p> <p>Instances of the <code>DiffieHellman</code> class can be created using the <a href="#crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding"><code>crypto.createDiffieHellman()</code></a> function.</p> <pre><code class="language-js">const crypto = require('crypto'); const assert = require('assert'); // Generate Alice's keys... const alice = crypto.createDiffieHellman(2048); const aliceKey = alice.generateKeys(); // Generate Bob's keys... const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator()); const bobKey = bob.generateKeys(); // Exchange and generate the secret... const aliceSecret = alice.computeSecret(bobKey); const bobSecret = bob.computeSecret(aliceKey); // OK assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); </code></pre> <h3>diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputencoding])<span><a class="mark" href="#crypto_diffiehellman_computesecret_otherpublickey_inputencoding_outputencoding" id="crypto_diffiehellman_computesecret_otherpublickey_inputencoding_outputencoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li><code>otherPublicKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of an <code>otherPublicKey</code> string.</li> <li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Computes the shared secret using <code>otherPublicKey</code> as the other party's public key and returns the computed shared secret. The supplied key is interpreted using the specified <code>inputEncoding</code>, and secret is encoded using specified <code>outputEncoding</code>. If the <code>inputEncoding</code> is not provided, <code>otherPublicKey</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p> <p>If <code>outputEncoding</code> is given a string is returned; otherwise, a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <h3>diffieHellman.generateKeys(<a href="#buffer_buffers_and_character_encodings">encoding</a>)<span><a class="mark" href="#crypto_diffiehellman_generatekeys_encoding" id="crypto_diffiehellman_generatekeys_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Generates private and public Diffie-Hellman key values, and returns the public key in the specified <code>encoding</code>. This key should be transferred to the other party. If <code>encoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <h3>diffieHellman.getGenerator(<a href="#buffer_buffers_and_character_encodings">encoding</a>)<span><a class="mark" href="#crypto_diffiehellman_getgenerator_encoding" id="crypto_diffiehellman_getgenerator_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the Diffie-Hellman generator in the specified <code>encoding</code>. If <code>encoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <h3>diffieHellman.getPrime(<a href="#buffer_buffers_and_character_encodings">encoding</a>)<span><a class="mark" href="#crypto_diffiehellman_getprime_encoding" id="crypto_diffiehellman_getprime_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the Diffie-Hellman prime in the specified <code>encoding</code>. If <code>encoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <h3>diffieHellman.getPrivateKey(<a href="#buffer_buffers_and_character_encodings">encoding</a>)<span><a class="mark" href="#crypto_diffiehellman_getprivatekey_encoding" id="crypto_diffiehellman_getprivatekey_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the Diffie-Hellman private key in the specified <code>encoding</code>. If <code>encoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <h3>diffieHellman.getPublicKey(<a href="#buffer_buffers_and_character_encodings">encoding</a>)<span><a class="mark" href="#crypto_diffiehellman_getpublickey_encoding" id="crypto_diffiehellman_getpublickey_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the Diffie-Hellman public key in the specified <code>encoding</code>. If <code>encoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <h3>diffieHellman.setPrivateKey(privateKey[, encoding])<span><a class="mark" href="#crypto_diffiehellman_setprivatekey_privatekey_encoding" id="crypto_diffiehellman_setprivatekey_privatekey_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li><code>privateKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>privateKey</code> string.</li> </ul> <p>Sets the Diffie-Hellman private key. If the <code>encoding</code> argument is provided, <code>privateKey</code> is expected to be a string. If no <code>encoding</code> is provided, <code>privateKey</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p> <h3>diffieHellman.setPublicKey(publicKey[, encoding])<span><a class="mark" href="#crypto_diffiehellman_setpublickey_publickey_encoding" id="crypto_diffiehellman_setpublickey_publickey_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li><code>publicKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>publicKey</code> string.</li> </ul> <p>Sets the Diffie-Hellman public key. If the <code>encoding</code> argument is provided, <code>publicKey</code> is expected to be a string. If no <code>encoding</code> is provided, <code>publicKey</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p> <h3>diffieHellman.verifyError<span><a class="mark" href="#crypto_diffiehellman_verifyerror" id="crypto_diffiehellman_verifyerror">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.12</span> </div> <p>A bit field containing any warnings and/or errors resulting from a check performed during initialization of the <code>DiffieHellman</code> object.</p> <p>The following values are valid for this property (as defined in <code>constants</code> module):</p> <ul> <li><code>DH_CHECK_P_NOT_SAFE_PRIME</code></li> <li><code>DH_CHECK_P_NOT_PRIME</code></li> <li><code>DH_UNABLE_TO_CHECK_GENERATOR</code></li> <li><code>DH_NOT_SUITABLE_GENERATOR</code></li> </ul> <h2>Class: ECDH<span><a class="mark" href="#crypto_class_ecdh" id="crypto_class_ecdh">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <p>The <code>ECDH</code> class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) key exchanges.</p> <p>Instances of the <code>ECDH</code> class can be created using the <a href="#crypto_crypto_createecdh_curvename"><code>crypto.createECDH()</code></a> function.</p> <pre><code class="language-js">const crypto = require('crypto'); const assert = require('assert'); // Generate Alice's keys... const alice = crypto.createECDH('secp521r1'); const aliceKey = alice.generateKeys(); // Generate Bob's keys... const bob = crypto.createECDH('secp521r1'); const bobKey = bob.generateKeys(); // Exchange and generate the secret... const aliceSecret = alice.computeSecret(bobKey); const bobSecret = bob.computeSecret(aliceKey); assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); // OK </code></pre> <h3>Class Method: ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])<span><a class="mark" href="#crypto_class_method_ecdh_convertkey_key_curve_inputencoding_outputencoding_format" id="crypto_class_method_ecdh_convertkey_key_curve_inputencoding_outputencoding_format">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>curve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>key</code> string.</li> <li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'uncompressed'</code></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Converts the EC Diffie-Hellman public key specified by <code>key</code> and <code>curve</code> to the format specified by <code>format</code>. The <code>format</code> argument specifies point encoding and can be <code>'compressed'</code>, <code>'uncompressed'</code> or <code>'hybrid'</code>. The supplied key is interpreted using the specified <code>inputEncoding</code>, and the returned key is encoded using the specified <code>outputEncoding</code>.</p> <p>Use <a href="#crypto_crypto_getcurves"><code>crypto.getCurves()</code></a> to obtain a list of available curve names. On recent OpenSSL releases, <code>openssl ecparam -list_curves</code> will also display the name and description of each available elliptic curve.</p> <p>If <code>format</code> is not specified the point will be returned in <code>'uncompressed'</code> format.</p> <p>If the <code>inputEncoding</code> is not provided, <code>key</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p> <p>Example (uncompressing a key):</p> <pre><code class="language-js">const { createECDH, ECDH } = require('crypto'); const ecdh = createECDH('secp256k1'); ecdh.generateKeys(); const compressedKey = ecdh.getPublicKey('hex', 'compressed'); const uncompressedKey = ECDH.convertKey(compressedKey, 'secp256k1', 'hex', 'hex', 'uncompressed'); // the converted key and the uncompressed public key should be the same console.log(uncompressedKey === ecdh.getPublicKey('hex')); </code></pre> <h3>ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputencoding])<span><a class="mark" href="#crypto_ecdh_computesecret_otherpublickey_inputencoding_outputencoding" id="crypto_ecdh_computesecret_otherpublickey_inputencoding_outputencoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Changed error format to better support invalid public key error</p></td></tr> <tr><td>v6.0.0</td> <td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code></p></td></tr> <tr><td>v0.11.14</td> <td><p><span>Added in: v0.11.14</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>otherPublicKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>otherPublicKey</code> string.</li> <li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Computes the shared secret using <code>otherPublicKey</code> as the other party's public key and returns the computed shared secret. The supplied key is interpreted using specified <code>inputEncoding</code>, and the returned secret is encoded using the specified <code>outputEncoding</code>. If the <code>inputEncoding</code> is not provided, <code>otherPublicKey</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p> <p>If <code>outputEncoding</code> is given a string will be returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <p><code>ecdh.computeSecret</code> will throw an <code>ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY</code> error when <code>otherPublicKey</code> lies outside of the elliptic curve. Since <code>otherPublicKey</code> is usually supplied from a remote user over an insecure network, its recommended for developers to handle this exception accordingly.</p> <h3>ecdh.generateKeys([encoding[, format]])<span><a class="mark" href="#crypto_ecdh_generatekeys_encoding_format" id="crypto_ecdh_generatekeys_encoding_format">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'uncompressed'</code></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Generates private and public EC Diffie-Hellman key values, and returns the public key in the specified <code>format</code> and <code>encoding</code>. This key should be transferred to the other party.</p> <p>The <code>format</code> argument specifies point encoding and can be <code>'compressed'</code> or <code>'uncompressed'</code>. If <code>format</code> is not specified, the point will be returned in <code>'uncompressed'</code> format.</p> <p>If <code>encoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <h3>ecdh.getPrivateKey(<a href="#buffer_buffers_and_character_encodings">encoding</a>)<span><a class="mark" href="#crypto_ecdh_getprivatekey_encoding" id="crypto_ecdh_getprivatekey_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The EC Diffie-Hellman in the specified <code>encoding</code>.</li> </ul> <p>If <code>encoding</code> is specified, a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <h3>ecdh.getPublicKey([encoding][, format])<span><a class="mark" href="#crypto_ecdh_getpublickey_encoding_format" id="crypto_ecdh_getpublickey_encoding_format">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'uncompressed'</code></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The EC Diffie-Hellman public key in the specified <code>encoding</code> and <code>format</code>.</li> </ul> <p>The <code>format</code> argument specifies point encoding and can be <code>'compressed'</code> or <code>'uncompressed'</code>. If <code>format</code> is not specified the point will be returned in <code>'uncompressed'</code> format.</p> <p>If <code>encoding</code> is specified, a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <h3>ecdh.setPrivateKey(privateKey[, encoding])<span><a class="mark" href="#crypto_ecdh_setprivatekey_privatekey_encoding" id="crypto_ecdh_setprivatekey_privatekey_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <ul> <li><code>privateKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>privateKey</code> string.</li> </ul> <p>Sets the EC Diffie-Hellman private key. If <code>encoding</code> is provided, <code>privateKey</code> is expected to be a string; otherwise <code>privateKey</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p> <p>If <code>privateKey</code> is not valid for the curve specified when the <code>ECDH</code> object was created, an error is thrown. Upon setting the private key, the associated public point (key) is also generated and set in the <code>ECDH</code> object.</p> <h3>ecdh.setPublicKey(publicKey[, encoding])<span><a class="mark" href="#crypto_ecdh_setpublickey_publickey_encoding" id="crypto_ecdh_setpublickey_publickey_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span><span>Deprecated since: v5.2.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p> <ul> <li><code>publicKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>publicKey</code> string.</li> </ul> <p>Sets the EC Diffie-Hellman public key. If <code>encoding</code> is provided <code>publicKey</code> is expected to be a string; otherwise a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p> <p>Note that there is not normally a reason to call this method because <code>ECDH</code> only requires a private key and the other party's public key to compute the shared secret. Typically either <a href="#crypto_ecdh_generatekeys_encoding_format"><code>ecdh.generateKeys()</code></a> or <a href="#crypto_ecdh_setprivatekey_privatekey_encoding"><code>ecdh.setPrivateKey()</code></a> will be called. The <a href="#crypto_ecdh_setprivatekey_privatekey_encoding"><code>ecdh.setPrivateKey()</code></a> method attempts to generate the public point/key associated with the private key being set.</p> <p>Example (obtaining a shared secret):</p> <pre><code class="language-js">const crypto = require('crypto'); const alice = crypto.createECDH('secp256k1'); const bob = crypto.createECDH('secp256k1'); // This is a shortcut way of specifying one of Alice's previous private // keys. It would be unwise to use such a predictable private key in a real // application. alice.setPrivateKey( crypto.createHash('sha256').update('alice', 'utf8').digest() ); // Bob uses a newly generated cryptographically strong // pseudorandom key pair bob.generateKeys(); const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); // aliceSecret and bobSecret should be the same shared secret value console.log(aliceSecret === bobSecret); </code></pre> <h2>Class: Hash<span><a class="mark" href="#crypto_class_hash" id="crypto_class_hash">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.92</span> </div> <p>The <code>Hash</code> class is a utility for creating hash digests of data. It can be used in one of two ways:</p> <ul> <li>As a <a href="stream.html">stream</a> that is both readable and writable, where data is written to produce a computed hash digest on the readable side, or</li> <li>Using the <a href="#crypto_hash_update_data_inputencoding"><code>hash.update()</code></a> and <a href="#crypto_hash_digest_encoding"><code>hash.digest()</code></a> methods to produce the computed hash.</li> </ul> <p>The <a href="#crypto_crypto_createhash_algorithm_options"><code>crypto.createHash()</code></a> method is used to create <code>Hash</code> instances. <code>Hash</code> objects are not to be created directly using the <code>new</code> keyword.</p> <p>Example: Using <code>Hash</code> objects as streams:</p> <pre><code class="language-js">const crypto = require('crypto'); const hash = crypto.createHash('sha256'); hash.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = hash.read(); if (data) { console.log(data.toString('hex')); // Prints: // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 } }); hash.write('some data to hash'); hash.end(); </code></pre> <p>Example: Using <code>Hash</code> and piped streams:</p> <pre><code class="language-js">const crypto = require('crypto'); const fs = require('fs'); const hash = crypto.createHash('sha256'); const input = fs.createReadStream('test.js'); input.pipe(hash).pipe(process.stdout); </code></pre> <p>Example: Using the <a href="#crypto_hash_update_data_inputencoding"><code>hash.update()</code></a> and <a href="#crypto_hash_digest_encoding"><code>hash.digest()</code></a> methods:</p> <pre><code class="language-js">const crypto = require('crypto'); const hash = crypto.createHash('sha256'); hash.update('some data to hash'); console.log(hash.digest('hex')); // Prints: // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 </code></pre> <h3>hash.digest(<a href="#buffer_buffers_and_character_encodings">encoding</a>)<span><a class="mark" href="#crypto_hash_digest_encoding" id="crypto_hash_digest_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.92</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Calculates the digest of all of the data passed to be hashed (using the <a href="#crypto_hash_update_data_inputencoding"><code>hash.update()</code></a> method). If <code>encoding</code> is provided a string will be returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <p>The <code>Hash</code> object can not be used again after <code>hash.digest()</code> method has been called. Multiple calls will cause an error to be thrown.</p> <h3>hash.update(data[, inputEncoding])<span><a class="mark" href="#crypto_hash_update_data_inputencoding" id="crypto_hash_update_data_inputencoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr> <tr><td>v0.1.92</td> <td><p><span>Added in: v0.1.92</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>data</code> string.</li> </ul> <p>Updates the hash content with the given <code>data</code>, the encoding of which is given in <code>inputEncoding</code>. If <code>encoding</code> is not provided, and the <code>data</code> is a string, an encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>, then <code>inputEncoding</code> is ignored.</p> <p>This can be called many times with new data as it is streamed.</p> <h2>Class: Hmac<span><a class="mark" href="#crypto_class_hmac" id="crypto_class_hmac">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.94</span> </div> <p>The <code>Hmac</code> Class is a utility for creating cryptographic HMAC digests. It can be used in one of two ways:</p> <ul> <li>As a <a href="stream.html">stream</a> that is both readable and writable, where data is written to produce a computed HMAC digest on the readable side, or</li> <li>Using the <a href="#crypto_hmac_update_data_inputencoding"><code>hmac.update()</code></a> and <a href="#crypto_hmac_digest_encoding"><code>hmac.digest()</code></a> methods to produce the computed HMAC digest.</li> </ul> <p>The <a href="#crypto_crypto_createhmac_algorithm_key_options"><code>crypto.createHmac()</code></a> method is used to create <code>Hmac</code> instances. <code>Hmac</code> objects are not to be created directly using the <code>new</code> keyword.</p> <p>Example: Using <code>Hmac</code> objects as streams:</p> <pre><code class="language-js">const crypto = require('crypto'); const hmac = crypto.createHmac('sha256', 'a secret'); hmac.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = hmac.read(); if (data) { console.log(data.toString('hex')); // Prints: // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e } }); hmac.write('some data to hash'); hmac.end(); </code></pre> <p>Example: Using <code>Hmac</code> and piped streams:</p> <pre><code class="language-js">const crypto = require('crypto'); const fs = require('fs'); const hmac = crypto.createHmac('sha256', 'a secret'); const input = fs.createReadStream('test.js'); input.pipe(hmac).pipe(process.stdout); </code></pre> <p>Example: Using the <a href="#crypto_hmac_update_data_inputencoding"><code>hmac.update()</code></a> and <a href="#crypto_hmac_digest_encoding"><code>hmac.digest()</code></a> methods:</p> <pre><code class="language-js">const crypto = require('crypto'); const hmac = crypto.createHmac('sha256', 'a secret'); hmac.update('some data to hash'); console.log(hmac.digest('hex')); // Prints: // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e </code></pre> <h3>hmac.digest(<a href="#buffer_buffers_and_character_encodings">encoding</a>)<span><a class="mark" href="#crypto_hmac_digest_encoding" id="crypto_hmac_digest_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.94</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Calculates the HMAC digest of all of the data passed using <a href="#crypto_hmac_update_data_inputencoding"><code>hmac.update()</code></a>. If <code>encoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned;</p> <p>The <code>Hmac</code> object can not be used again after <code>hmac.digest()</code> has been called. Multiple calls to <code>hmac.digest()</code> will result in an error being thrown.</p> <h3>hmac.update(data[, inputEncoding])<span><a class="mark" href="#crypto_hmac_update_data_inputencoding" id="crypto_hmac_update_data_inputencoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr> <tr><td>v0.1.94</td> <td><p><span>Added in: v0.1.94</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>data</code> string.</li> </ul> <p>Updates the <code>Hmac</code> content with the given <code>data</code>, the encoding of which is given in <code>inputEncoding</code>. If <code>encoding</code> is not provided, and the <code>data</code> is a string, an encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>, then <code>inputEncoding</code> is ignored.</p> <p>This can be called many times with new data as it is streamed.</p> <h2>Class: Sign<span><a class="mark" href="#crypto_class_sign" id="crypto_class_sign">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.92</span> </div> <p>The <code>Sign</code> Class is a utility for generating signatures. It can be used in one of two ways:</p> <ul> <li>As a writable <a href="stream.html">stream</a>, where data to be signed is written and the <a href="#crypto_sign_sign_privatekey_outputencoding"><code>sign.sign()</code></a> method is used to generate and return the signature, or</li> <li>Using the <a href="#crypto_sign_update_data_inputencoding"><code>sign.update()</code></a> and <a href="#crypto_sign_sign_privatekey_outputencoding"><code>sign.sign()</code></a> methods to produce the signature.</li> </ul> <p>The <a href="#crypto_crypto_createsign_algorithm_options"><code>crypto.createSign()</code></a> method is used to create <code>Sign</code> instances. The argument is the string name of the hash function to use. <code>Sign</code> objects are not to be created directly using the <code>new</code> keyword.</p> <p>Example: Using <code>Sign</code> objects as streams:</p> <pre><code class="language-js">const crypto = require('crypto'); const sign = crypto.createSign('SHA256'); sign.write('some data to sign'); sign.end(); const privateKey = getPrivateKeySomehow(); console.log(sign.sign(privateKey, 'hex')); // Prints: the calculated signature using the specified private key and // SHA-256. For RSA keys, the algorithm is RSASSA-PKCS1-v1_5 (see padding // parameter below for RSASSA-PSS). For EC keys, the algorithm is ECDSA. </code></pre> <p>Example: Using the <a href="#crypto_sign_update_data_inputencoding"><code>sign.update()</code></a> and <a href="#crypto_sign_sign_privatekey_outputencoding"><code>sign.sign()</code></a> methods:</p> <pre><code class="language-js">const crypto = require('crypto'); const sign = crypto.createSign('SHA256'); sign.update('some data to sign'); const privateKey = getPrivateKeySomehow(); console.log(sign.sign(privateKey, 'hex')); // Prints: the calculated signature </code></pre> <p>In some cases, a <code>Sign</code> instance can also be created by passing in a signature algorithm name, such as 'RSA-SHA256'. This will use the corresponding digest algorithm. This does not work for all signature algorithms, such as 'ecdsa-with-SHA256'. Use digest names instead.</p> <p>Example: signing using legacy signature algorithm name</p> <pre><code class="language-js">const crypto = require('crypto'); const sign = crypto.createSign('RSA-SHA256'); sign.update('some data to sign'); const privateKey = getPrivateKeySomehow(); console.log(sign.sign(privateKey, 'hex')); // Prints: the calculated signature </code></pre> <h3>sign.sign(privateKey[, outputEncoding])<span><a class="mark" href="#crypto_sign_sign_privatekey_outputencoding" id="crypto_sign_sign_privatekey_outputencoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Support for RSASSA-PSS and additional options was added.</p></td></tr> <tr><td>v0.1.92</td> <td><p><span>Added in: v0.1.92</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>privateKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>passphrase</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> </li> <li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Calculates the signature on all the data passed through using either <a href="#crypto_sign_update_data_inputencoding"><code>sign.update()</code></a> or <a href="#stream_writable_write_chunk_encoding_callback"><code>sign.write()</code></a>.</p> <p>The <code>privateKey</code> argument can be an object or a string. If <code>privateKey</code> is a string, it is treated as a raw key with no passphrase. If <code>privateKey</code> is an object, it must contain one or more of the following properties:</p> <ul> <li> <p><code>key</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> - PEM encoded private key (required)</p> </li> <li> <p><code>passphrase</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> - passphrase for the private key</p> </li> <li> <p><code>padding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> - Optional padding value for RSA, one of the following:</p> <ul> <li><code>crypto.constants.RSA_PKCS1_PADDING</code> (default)</li> <li><code>crypto.constants.RSA_PKCS1_PSS_PADDING</code></li> </ul> <p>Note that <code>RSA_PKCS1_PSS_PADDING</code> will use MGF1 with the same hash function used to sign the message as specified in section 3.1 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>.</p> </li> <li> <p><code>saltLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> - salt length for when padding is <code>RSA_PKCS1_PSS_PADDING</code>. The special value <code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest size, <code>crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN</code> (default) sets it to the maximum permissible value.</p> </li> </ul> <p>If <code>outputEncoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p> <p>The <code>Sign</code> object can not be again used after <code>sign.sign()</code> method has been called. Multiple calls to <code>sign.sign()</code> will result in an error being thrown.</p> <h3>sign.update(data[, inputEncoding])<span><a class="mark" href="#crypto_sign_update_data_inputencoding" id="crypto_sign_update_data_inputencoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr> <tr><td>v0.1.92</td> <td><p><span>Added in: v0.1.92</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>data</code> string.</li> </ul> <p>Updates the <code>Sign</code> content with the given <code>data</code>, the encoding of which is given in <code>inputEncoding</code>. If <code>encoding</code> is not provided, and the <code>data</code> is a string, an encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>, then <code>inputEncoding</code> is ignored.</p> <p>This can be called many times with new data as it is streamed.</p> <h2>Class: Verify<span><a class="mark" href="#crypto_class_verify" id="crypto_class_verify">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.92</span> </div> <p>The <code>Verify</code> class is a utility for verifying signatures. It can be used in one of two ways:</p> <ul> <li>As a writable <a href="stream.html">stream</a> where written data is used to validate against the supplied signature, or</li> <li>Using the <a href="#crypto_verify_update_data_inputencoding"><code>verify.update()</code></a> and <a href="#crypto_verify_verify_object_signature_signatureencoding"><code>verify.verify()</code></a> methods to verify the signature.</li> </ul> <p>The <a href="#crypto_crypto_createverify_algorithm_options"><code>crypto.createVerify()</code></a> method is used to create <code>Verify</code> instances. <code>Verify</code> objects are not to be created directly using the <code>new</code> keyword.</p> <p>Example: Using <code>Verify</code> objects as streams:</p> <pre><code class="language-js">const crypto = require('crypto'); const verify = crypto.createVerify('SHA256'); verify.write('some data to sign'); verify.end(); const publicKey = getPublicKeySomehow(); const signature = getSignatureToVerify(); console.log(verify.verify(publicKey, signature)); // Prints: true or false </code></pre> <p>Example: Using the <a href="#crypto_verify_update_data_inputencoding"><code>verify.update()</code></a> and <a href="#crypto_verify_verify_object_signature_signatureencoding"><code>verify.verify()</code></a> methods:</p> <pre><code class="language-js">const crypto = require('crypto'); const verify = crypto.createVerify('SHA256'); verify.update('some data to sign'); const publicKey = getPublicKeySomehow(); const signature = getSignatureToVerify(); console.log(verify.verify(publicKey, signature)); // Prints: true or false </code></pre> <h3>verify.update(data[, inputEncoding])<span><a class="mark" href="#crypto_verify_update_data_inputencoding" id="crypto_verify_update_data_inputencoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr> <tr><td>v0.1.92</td> <td><p><span>Added in: v0.1.92</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>data</code> string.</li> </ul> <p>Updates the <code>Verify</code> content with the given <code>data</code>, the encoding of which is given in <code>inputEncoding</code>. If <code>inputEncoding</code> is not provided, and the <code>data</code> is a string, an encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>, then <code>inputEncoding</code> is ignored.</p> <p>This can be called many times with new data as it is streamed.</p> <h3>verify.verify(object, signature[, signatureEncoding])<span><a class="mark" href="#crypto_verify_verify_object_signature_signatureencoding" id="crypto_verify_verify_object_signature_signatureencoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Support for RSASSA-PSS and additional options was added.</p></td></tr> <tr><td>v0.1.92</td> <td><p><span>Added in: v0.1.92</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>signature</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>signatureEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>signature</code> string.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> or <code>false</code> depending on the validity of the signature for the data and public key.</li> </ul> <p>Verifies the provided data using the given <code>object</code> and <code>signature</code>. The <code>object</code> argument can be either a string containing a PEM encoded object, which can be an RSA public key, a DSA public key, or an X.509 certificate, or an object with one or more of the following properties:</p> <ul> <li> <p><code>key</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> - PEM encoded public key (required)</p> </li> <li> <p><code>padding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> - Optional padding value for RSA, one of the following:</p> <ul> <li><code>crypto.constants.RSA_PKCS1_PADDING</code> (default)</li> <li><code>crypto.constants.RSA_PKCS1_PSS_PADDING</code></li> </ul> <p>Note that <code>RSA_PKCS1_PSS_PADDING</code> will use MGF1 with the same hash function used to verify the message as specified in section 3.1 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>.</p> </li> <li> <p><code>saltLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> - salt length for when padding is <code>RSA_PKCS1_PSS_PADDING</code>. The special value <code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest size, <code>crypto.constants.RSA_PSS_SALTLEN_AUTO</code> (default) causes it to be determined automatically.</p> </li> </ul> <p>The <code>signature</code> argument is the previously calculated signature for the data, in the <code>signatureEncoding</code>. If a <code>signatureEncoding</code> is specified, the <code>signature</code> is expected to be a string; otherwise <code>signature</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p> <p>The <code>verify</code> object can not be used again after <code>verify.verify()</code> has been called. Multiple calls to <code>verify.verify()</code> will result in an error being thrown.</p> <h2><code>crypto</code> module methods and properties<span><a class="mark" href="#crypto_crypto_module_methods_and_properties" id="crypto_crypto_module_methods_and_properties">#</a></span></h2> <h3>crypto.constants<span><a class="mark" href="#crypto_crypto_constants" id="crypto_crypto_constants">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.3.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in <a href="#crypto_crypto_constants_1">Crypto Constants</a>.</li> </ul> <h3>crypto.DEFAULT_ENCODING<span><a class="mark" href="#crypto_crypto_default_encoding" id="crypto_crypto_default_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.3</span><span>Deprecated since: v10.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p> <p>The default encoding to use for functions that can take either strings or <a href="buffer.html">buffers</a>. The default value is <code>'buffer'</code>, which makes methods default to <a href="buffer.html"><code>Buffer</code></a> objects.</p> <p>The <code>crypto.DEFAULT_ENCODING</code> mechanism is provided for backwards compatibility with legacy programs that expect <code>'latin1'</code> to be the default encoding.</p> <p>New applications should expect the default to be <code>'buffer'</code>.</p> <p>This property is deprecated.</p> <h3>crypto.fips<span><a class="mark" href="#crypto_crypto_fips" id="crypto_crypto_fips">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span><span>Deprecated since: v10.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p> <p>Property for checking and controlling whether a FIPS compliant crypto provider is currently in use. Setting to true requires a FIPS build of Node.js.</p> <p>This property is deprecated. Please use <code>crypto.setFips()</code> and <code>crypto.getFips()</code> instead.</p> <h3>crypto.createCipher(algorithm, password[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/crypto.js#L104">[src]</a><span><a class="mark" href="#crypto_crypto_createcipher_algorithm_password_options" id="crypto_crypto_createcipher_algorithm_password_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>Ciphers in OCB mode are now supported.</p></td></tr> <tr><td>v10.2.0</td> <td><p>The <code>authTagLength</code> option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes.</p></td></tr> <tr><td>v10.0.0</td> <td><p><span>Deprecated since: v10.0.0</span></p></td></tr> <tr><td>v0.1.94</td> <td><p><span>Added in: v0.1.94</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#crypto_crypto_createcipheriv_algorithm_key_iv_options"><code>crypto.createCipheriv()</code></a> instead.</div><p></p> <ul> <li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li> <li>Returns: <a href="#crypto_class_cipher" class="type"><Cipher></a></li> </ul> <p>Creates and returns a <code>Cipher</code> object that uses the given <code>algorithm</code> and <code>password</code>.</p> <p>The <code>options</code> argument controls stream behavior and is optional except when a cipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the <code>authTagLength</code> option is required and specifies the length of the authentication tag in bytes, see <a href="#crypto_ccm_mode">CCM mode</a>. In GCM mode, the <code>authTagLength</code> option is not required but can be used to set the length of the authentication tag that will be returned by <code>getAuthTag()</code> and defaults to 16 bytes.</p> <p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On recent OpenSSL releases, <code>openssl list -cipher-algorithms</code> (<code>openssl list-cipher-algorithms</code> for older versions of OpenSSL) will display the available cipher algorithms.</p> <p>The <code>password</code> is used to derive the cipher key and initialization vector (IV). The value must be either a <code>'latin1'</code> encoded string, a <a href="buffer.html"><code>Buffer</code></a>, a <code>TypedArray</code>, or a <code>DataView</code>.</p> <p>The implementation of <code>crypto.createCipher()</code> derives keys using the OpenSSL function <a href="https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> with the digest algorithm set to MD5, one iteration, and no salt. The lack of salt allows dictionary attacks as the same password always creates the same key. The low iteration count and non-cryptographically secure hash algorithm allow passwords to be tested very rapidly.</p> <p>In line with OpenSSL's recommendation to use a more modern algorithm instead of <a href="https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on their own using <a href="#crypto_crypto_scrypt_password_salt_keylen_options_callback"><code>crypto.scrypt()</code></a> and to use <a href="#crypto_crypto_createcipheriv_algorithm_key_iv_options"><code>crypto.createCipheriv()</code></a> to create the <code>Cipher</code> object. Users should not use ciphers with counter mode (e.g. CTR, GCM, or CCM) in <code>crypto.createCipher()</code>. A warning is emitted when they are used in order to avoid the risk of IV reuse that causes vulnerabilities. For the case when IV is reused in GCM, see <a href="https://github.com/nonce-disrespect/nonce-disrespect">Nonce-Disrespecting Adversaries</a> for details.</p> <h3>crypto.createCipheriv(algorithm, key, iv[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/crypto.js#L108">[src]</a><span><a class="mark" href="#crypto_crypto_createcipheriv_algorithm_key_iv_options" id="crypto_crypto_createcipheriv_algorithm_key_iv_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.17.0</td> <td><p>The cipher <code>chacha20-poly1305</code> is now supported.</p></td></tr> <tr><td>v10.10.0</td> <td><p>Ciphers in OCB mode are now supported.</p></td></tr> <tr><td>v10.2.0</td> <td><p>The <code>authTagLength</code> option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes.</p></td></tr> <tr><td>v9.9.0</td> <td><p>The <code>iv</code> parameter may now be <code>null</code> for ciphers which do not need an initialization vector.</p></td></tr> <tr><td>v0.1.94</td> <td><p><span>Added in: v0.1.94</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>iv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li> <li>Returns: <a href="#crypto_class_cipher" class="type"><Cipher></a></li> </ul> <p>Creates and returns a <code>Cipher</code> object, with the given <code>algorithm</code>, <code>key</code> and initialization vector (<code>iv</code>).</p> <p>The <code>options</code> argument controls stream behavior and is optional except when a cipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the <code>authTagLength</code> option is required and specifies the length of the authentication tag in bytes, see <a href="#crypto_ccm_mode">CCM mode</a>. In GCM mode, the <code>authTagLength</code> option is not required but can be used to set the length of the authentication tag that will be returned by <code>getAuthTag()</code> and defaults to 16 bytes.</p> <p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On recent OpenSSL releases, <code>openssl list -cipher-algorithms</code> (<code>openssl list-cipher-algorithms</code> for older versions of OpenSSL) will display the available cipher algorithms.</p> <p>The <code>key</code> is the raw key used by the <code>algorithm</code> and <code>iv</code> is an <a href="https://en.wikipedia.org/wiki/Initialization_vector">initialization vector</a>. Both arguments must be <code>'utf8'</code> encoded strings, <a href="buffer.html">Buffers</a>, <code>TypedArray</code>, or <code>DataView</code>s. If the cipher does not need an initialization vector, <code>iv</code> may be <code>null</code>.</p> <p>Initialization vectors should be unpredictable and unique; ideally, they will be cryptographically random. They do not have to be secret: IVs are typically just added to ciphertext messages unencrypted. It may sound contradictory that something has to be unpredictable and unique, but does not have to be secret; it is important to remember that an attacker must not be able to predict ahead of time what a given IV will be.</p> <h3>crypto.createCredentials(details)<span><a class="mark" href="#crypto_crypto_createcredentials_details" id="crypto_crypto_createcredentials_details">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.92</span><span>Deprecated since: v0.11.13</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> instead.</div><p></p> <ul> <li><code>details</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Identical to <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>.</li> <li>Returns: <a href="#tls_tls_createsecurecontext_options" class="type"><tls.SecureContext></a></li> </ul> <p>The <code>crypto.createCredentials()</code> method is a deprecated function for creating and returning a <code>tls.SecureContext</code>. It should not be used. Replace it with <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> which has the exact same arguments and return value.</p> <p>Returns a <code>tls.SecureContext</code>, as-if <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> had been called.</p> <h3>crypto.createDecipher(algorithm, password[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/crypto.js#L112">[src]</a><span><a class="mark" href="#crypto_crypto_createdecipher_algorithm_password_options" id="crypto_crypto_createdecipher_algorithm_password_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>Ciphers in OCB mode are now supported.</p></td></tr> <tr><td>v10.0.0</td> <td><p><span>Deprecated since: v10.0.0</span></p></td></tr> <tr><td>v0.1.94</td> <td><p><span>Added in: v0.1.94</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options"><code>crypto.createDecipheriv()</code></a> instead.</div><p></p> <ul> <li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li> <li>Returns: <a href="#crypto_class_decipher" class="type"><Decipher></a></li> </ul> <p>Creates and returns a <code>Decipher</code> object that uses the given <code>algorithm</code> and <code>password</code> (key).</p> <p>The <code>options</code> argument controls stream behavior and is optional except when a cipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the <code>authTagLength</code> option is required and specifies the length of the authentication tag in bytes, see <a href="#crypto_ccm_mode">CCM mode</a>.</p> <p>The implementation of <code>crypto.createDecipher()</code> derives keys using the OpenSSL function <a href="https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> with the digest algorithm set to MD5, one iteration, and no salt. The lack of salt allows dictionary attacks as the same password always creates the same key. The low iteration count and non-cryptographically secure hash algorithm allow passwords to be tested very rapidly.</p> <p>In line with OpenSSL's recommendation to use a more modern algorithm instead of <a href="https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on their own using <a href="#crypto_crypto_scrypt_password_salt_keylen_options_callback"><code>crypto.scrypt()</code></a> and to use <a href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options"><code>crypto.createDecipheriv()</code></a> to create the <code>Decipher</code> object.</p> <h3>crypto.createDecipheriv(algorithm, key, iv[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/crypto.js#L116">[src]</a><span><a class="mark" href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options" id="crypto_crypto_createdecipheriv_algorithm_key_iv_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.17.0</td> <td><p>The cipher <code>chacha20-poly1305</code> is now supported.</p></td></tr> <tr><td>v10.10.0</td> <td><p>Ciphers in OCB mode are now supported.</p></td></tr> <tr><td>v10.2.0</td> <td><p>The <code>authTagLength</code> option can now be used to restrict accepted GCM authentication tag lengths.</p></td></tr> <tr><td>v9.9.0</td> <td><p>The <code>iv</code> parameter may now be <code>null</code> for ciphers which do not need an initialization vector.</p></td></tr> <tr><td>v0.1.94</td> <td><p><span>Added in: v0.1.94</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>iv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li> <li>Returns: <a href="#crypto_class_decipher" class="type"><Decipher></a></li> </ul> <p>Creates and returns a <code>Decipher</code> object that uses the given <code>algorithm</code>, <code>key</code> and initialization vector (<code>iv</code>).</p> <p>The <code>options</code> argument controls stream behavior and is optional except when a cipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the <code>authTagLength</code> option is required and specifies the length of the authentication tag in bytes, see <a href="#crypto_ccm_mode">CCM mode</a>. In GCM mode, the <code>authTagLength</code> option is not required but can be used to restrict accepted authentication tags to those with the specified length.</p> <p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On recent OpenSSL releases, <code>openssl list -cipher-algorithms</code> (<code>openssl list-cipher-algorithms</code> for older versions of OpenSSL) will display the available cipher algorithms.</p> <p>The <code>key</code> is the raw key used by the <code>algorithm</code> and <code>iv</code> is an <a href="https://en.wikipedia.org/wiki/Initialization_vector">initialization vector</a>. Both arguments must be <code>'utf8'</code> encoded strings, <a href="buffer.html">Buffers</a>, <code>TypedArray</code>, or <code>DataView</code>s. If the cipher does not need an initialization vector, <code>iv</code> may be <code>null</code>.</p> <p>Initialization vectors should be unpredictable and unique; ideally, they will be cryptographically random. They do not have to be secret: IVs are typically just added to ciphertext messages unencrypted. It may sound contradictory that something has to be unpredictable and unique, but does not have to be secret; it is important to remember that an attacker must not be able to predict ahead of time what a given IV will be.</p> <h3>crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/crypto.js#L120">[src]</a><span><a class="mark" href="#crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding" id="crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>prime</code> argument can be any <code>TypedArray</code> or <code>DataView</code> now.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>prime</code> argument can be a <code>Uint8Array</code> now.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The default for the encoding parameters changed from <code>binary</code> to <code>utf8</code>.</p></td></tr> <tr><td>v0.11.12</td> <td><p><span>Added in: v0.11.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>prime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>primeEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>prime</code> string.</li> <li><code>generator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> <strong>Default:</strong> <code>2</code></li> <li><code>generatorEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>generator</code> string.</li> <li>Returns: <a href="#crypto_class_diffiehellman" class="type"><DiffieHellman></a></li> </ul> <p>Creates a <code>DiffieHellman</code> key exchange object using the supplied <code>prime</code> and an optional specific <code>generator</code>.</p> <p>The <code>generator</code> argument can be a number, string, or <a href="buffer.html"><code>Buffer</code></a>. If <code>generator</code> is not specified, the value <code>2</code> is used.</p> <p>If <code>primeEncoding</code> is specified, <code>prime</code> is expected to be a string; otherwise a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p> <p>If <code>generatorEncoding</code> is specified, <code>generator</code> is expected to be a string; otherwise a number, <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p> <h3>crypto.createDiffieHellman(primeLength[, generator])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/crypto.js#L120">[src]</a><span><a class="mark" href="#crypto_crypto_creatediffiehellman_primelength_generator" id="crypto_crypto_creatediffiehellman_primelength_generator">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li><code>primeLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>generator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> <strong>Default:</strong> <code>2</code></li> <li>Returns: <a href="#crypto_class_diffiehellman" class="type"><DiffieHellman></a></li> </ul> <p>Creates a <code>DiffieHellman</code> key exchange object and generates a prime of <code>primeLength</code> bits using an optional specific numeric <code>generator</code>. If <code>generator</code> is not specified, the value <code>2</code> is used.</p> <h3>crypto.createECDH(curveName)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/crypto.js#L128">[src]</a><span><a class="mark" href="#crypto_crypto_createecdh_curvename" id="crypto_crypto_createecdh_curvename">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <ul> <li><code>curveName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="#crypto_class_ecdh" class="type"><ECDH></a></li> </ul> <p>Creates an Elliptic Curve Diffie-Hellman (<code>ECDH</code>) key exchange object using a predefined curve specified by the <code>curveName</code> string. Use <a href="#crypto_crypto_getcurves"><code>crypto.getCurves()</code></a> to obtain a list of available curve names. On recent OpenSSL releases, <code>openssl ecparam -list_curves</code> will also display the name and description of each available elliptic curve.</p> <h3>crypto.createHash(algorithm[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/crypto.js#L100">[src]</a><span><a class="mark" href="#crypto_crypto_createhash_algorithm_options" id="crypto_crypto_createhash_algorithm_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.92</span> </div> <ul> <li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li> <li>Returns: <a href="#crypto_class_hash" class="type"><Hash></a></li> </ul> <p>Creates and returns a <code>Hash</code> object that can be used to generate hash digests using the given <code>algorithm</code>. Optional <code>options</code> argument controls stream behavior.</p> <p>The <code>algorithm</code> is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are <code>'sha256'</code>, <code>'sha512'</code>, etc. On recent releases of OpenSSL, <code>openssl list -digest-algorithms</code> (<code>openssl list-message-digest-algorithms</code> for older versions of OpenSSL) will display the available digest algorithms.</p> <p>Example: generating the sha256 sum of a file</p> <pre><code class="language-js">const filename = process.argv[2]; const crypto = require('crypto'); const fs = require('fs'); const hash = crypto.createHash('sha256'); const input = fs.createReadStream(filename); input.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = input.read(); if (data) hash.update(data); else { console.log(`${hash.digest('hex')} ${filename}`); } }); </code></pre> <h3>crypto.createHmac(algorithm, key[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/crypto.js#L132">[src]</a><span><a class="mark" href="#crypto_crypto_createhmac_algorithm_key_options" id="crypto_crypto_createhmac_algorithm_key_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.94</span> </div> <ul> <li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li> <li>Returns: <a href="#crypto_class_hmac" class="type"><Hmac></a></li> </ul> <p>Creates and returns an <code>Hmac</code> object that uses the given <code>algorithm</code> and <code>key</code>. Optional <code>options</code> argument controls stream behavior.</p> <p>The <code>algorithm</code> is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are <code>'sha256'</code>, <code>'sha512'</code>, etc. On recent releases of OpenSSL, <code>openssl list -digest-algorithms</code> (<code>openssl list-message-digest-algorithms</code> for older versions of OpenSSL) will display the available digest algorithms.</p> <p>The <code>key</code> is the HMAC key used to generate the cryptographic HMAC hash.</p> <p>Example: generating the sha256 HMAC of a file</p> <pre><code class="language-js">const filename = process.argv[2]; const crypto = require('crypto'); const fs = require('fs'); const hmac = crypto.createHmac('sha256', 'a secret'); const input = fs.createReadStream(filename); input.on('readable', () => { // Only one element is going to be produced by the // hash stream. const data = input.read(); if (data) hmac.update(data); else { console.log(`${hmac.digest('hex')} ${filename}`); } }); </code></pre> <h3>crypto.createSign(algorithm[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/crypto.js#L136">[src]</a><span><a class="mark" href="#crypto_crypto_createsign_algorithm_options" id="crypto_crypto_createsign_algorithm_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.92</span> </div> <ul> <li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#stream_constructor_new_stream_writable_options"><code>stream.Writable</code> options</a></li> <li>Returns: <a href="#crypto_class_sign" class="type"><Sign></a></li> </ul> <p>Creates and returns a <code>Sign</code> object that uses the given <code>algorithm</code>. Use <a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a> to obtain an array of names of the available signing algorithms. Optional <code>options</code> argument controls the <code>stream.Writable</code> behavior.</p> <h3>crypto.createVerify(algorithm[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/crypto.js#L140">[src]</a><span><a class="mark" href="#crypto_crypto_createverify_algorithm_options" id="crypto_crypto_createverify_algorithm_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.92</span> </div> <ul> <li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <a href="#stream_constructor_new_stream_writable_options"><code>stream.Writable</code> options</a></li> <li>Returns: <a href="#crypto_class_verify" class="type"><Verify></a></li> </ul> <p>Creates and returns a <code>Verify</code> object that uses the given algorithm. Use <a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a> to obtain an array of names of the available signing algorithms. Optional <code>options</code> argument controls the <code>stream.Writable</code> behavior.</p> <h3>crypto.generateKeyPair(type, options, callback)<span><a class="mark" href="#crypto_crypto_generatekeypair_type_options_callback" id="crypto_crypto_generatekeypair_type_options_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'rsa'</code>, <code>'dsa'</code> or <code>'ec'</code>.</li> <li> <p><code>options</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>modulusLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Key size in bits (RSA, DSA).</li> <li><code>publicExponent</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Public exponent (RSA). <strong>Default:</strong> <code>0x10001</code>.</li> <li><code>divisorLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Size of <code>q</code> in bits (DSA).</li> <li><code>namedCurve</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the curve to use (EC).</li> <li> <p><code>publicKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'pkcs1'</code> (RSA only) or <code>'spki'</code>.</li> <li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'pem'</code> or <code>'der'</code>.</li> </ul> </li> <li> <p><code>privateKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'pkcs1'</code> (RSA only), <code>'pkcs8'</code> or <code>'sec1'</code> (EC only).</li> <li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'pem'</code> or <code>'der'</code>.</li> <li><code>cipher</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If specified, the private key will be encrypted with the given <code>cipher</code> and <code>passphrase</code> using PKCS#5 v2.0 password based encryption.</li> <li><code>passphrase</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The passphrase to use for encryption, see <code>cipher</code>.</li> </ul> </li> </ul> </li> <li> <p><code>callback</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>publicKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>privateKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> </ul> <p>Generates a new asymmetric key pair of the given <code>type</code>. Only RSA, DSA and EC are currently supported.</p> <p>It is recommended to encode public keys as <code>'spki'</code> and private keys as <code>'pkcs8'</code> with encryption:</p> <pre><code class="language-js">const { generateKeyPair } = require('crypto'); generateKeyPair('rsa', { modulusLength: 4096, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: 'top secret' } }, (err, publicKey, privateKey) => { // Handle errors and use the generated key pair. }); </code></pre> <p>On completion, <code>callback</code> will be called with <code>err</code> set to <code>undefined</code> and <code>publicKey</code> / <code>privateKey</code> representing the generated key pair. When PEM encoding was selected, the result will be a string, otherwise it will be a buffer containing the data encoded as DER. Note that Node.js itself does not accept DER, it is supported for interoperability with other libraries such as WebCrypto only.</p> <p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns a <code>Promise</code> for an <code>Object</code> with <code>publicKey</code> and <code>privateKey</code> properties.</p> <h3>crypto.generateKeyPairSync(type, options)<span><a class="mark" href="#crypto_crypto_generatekeypairsync_type_options" id="crypto_crypto_generatekeypairsync_type_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'rsa'</code>, <code>'dsa'</code> or <code>'ec'</code>.</li> <li> <p><code>options</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>modulusLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Key size in bits (RSA, DSA).</li> <li><code>publicExponent</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Public exponent (RSA). <strong>Default:</strong> <code>0x10001</code>.</li> <li><code>divisorLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Size of <code>q</code> in bits (DSA).</li> <li><code>namedCurve</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of the curve to use (EC).</li> <li> <p><code>publicKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'pkcs1'</code> (RSA only) or <code>'spki'</code>.</li> <li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'pem'</code> or <code>'der'</code>.</li> </ul> </li> <li> <p><code>privateKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be one of <code>'pkcs1'</code> (RSA only), <code>'pkcs8'</code> or <code>'sec1'</code> (EC only).</li> <li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Must be <code>'pem'</code> or <code>'der'</code>.</li> <li><code>cipher</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If specified, the private key will be encrypted with the given <code>cipher</code> and <code>passphrase</code> using PKCS#5 v2.0 password based encryption.</li> <li><code>passphrase</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The passphrase to use for encryption, see <code>cipher</code>.</li> </ul> </li> </ul> </li> <li> <p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>publicKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>privateKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> </ul> <p>Generates a new asymmetric key pair of the given <code>type</code>. Only RSA, DSA and EC are currently supported.</p> <p>It is recommended to encode public keys as <code>'spki'</code> and private keys as <code>'pkcs8'</code> with encryption:</p> <pre><code class="language-js">const { generateKeyPairSync } = require('crypto'); const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 4096, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: 'top secret' } }); </code></pre> <p>The return value <code>{ publicKey, privateKey }</code> represents the generated key pair. When PEM encoding was selected, the respective key will be a string, otherwise it will be a buffer containing the data encoded as DER.</p> <h3>crypto.getCiphers()<span><a class="mark" href="#crypto_crypto_getciphers" id="crypto_crypto_getciphers">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.3</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array with the names of the supported cipher algorithms.</li> </ul> <pre><code class="language-js">const ciphers = crypto.getCiphers(); console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...] </code></pre> <h3>crypto.getCurves()<span><a class="mark" href="#crypto_crypto_getcurves" id="crypto_crypto_getcurves">#</a></span></h3> <div class="api_metadata"> <span>Added in: v2.3.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array with the names of the supported elliptic curves.</li> </ul> <pre><code class="language-js">const curves = crypto.getCurves(); console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] </code></pre> <h3>crypto.getDiffieHellman(groupName)<span><a class="mark" href="#crypto_crypto_getdiffiehellman_groupname" id="crypto_crypto_getdiffiehellman_groupname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.5</span> </div> <ul> <li><code>groupName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="#crypto_class_diffiehellman" class="type"><DiffieHellman></a></li> </ul> <p>Creates a predefined <code>DiffieHellman</code> key exchange object. The supported groups are: <code>'modp1'</code>, <code>'modp2'</code>, <code>'modp5'</code> (defined in <a href="https://www.rfc-editor.org/rfc/rfc2412.txt">RFC 2412</a>, but see <a href="#crypto_support_for_weak_or_compromised_algorithms">Caveats</a>) and <code>'modp14'</code>, <code>'modp15'</code>, <code>'modp16'</code>, <code>'modp17'</code>, <code>'modp18'</code> (defined in <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a>). The returned object mimics the interface of objects created by <a href="#crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding"><code>crypto.createDiffieHellman()</code></a>, but will not allow changing the keys (with <a href="#crypto_diffiehellman_setpublickey_publickey_encoding"><code>diffieHellman.setPublicKey()</code></a>, for example). The advantage of using this method is that the parties do not have to generate nor exchange a group modulus beforehand, saving both processor and communication time.</p> <p>Example (obtaining a shared secret):</p> <pre><code class="language-js">const crypto = require('crypto'); const alice = crypto.getDiffieHellman('modp14'); const bob = crypto.getDiffieHellman('modp14'); alice.generateKeys(); bob.generateKeys(); const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); /* aliceSecret and bobSecret should be the same */ console.log(aliceSecret === bobSecret); </code></pre> <h3>crypto.getFips()<span><a class="mark" href="#crypto_crypto_getfips" id="crypto_crypto_getfips">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if and only if a FIPS compliant crypto provider is currently in use.</li> </ul> <h3>crypto.getHashes()<span><a class="mark" href="#crypto_crypto_gethashes" id="crypto_crypto_gethashes">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.3</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array of the names of the supported hash algorithms, such as <code>'RSA-SHA256'</code>.</li> </ul> <pre><code class="language-js">const hashes = crypto.getHashes(); console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] </code></pre> <h3>crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)<span><a class="mark" href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback" id="crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>digest</code> parameter is always required now.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Calling this function without passing the <code>digest</code> parameter is deprecated now and will emit a warning.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The default encoding for <code>password</code> if it is a string changed from <code>binary</code> to <code>utf8</code>.</p></td></tr> <tr><td>v0.5.5</td> <td><p><span>Added in: v0.5.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>salt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>iterations</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>digest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>derivedKey</code> <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> </ul> <p>Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) implementation. A selected HMAC digest algorithm specified by <code>digest</code> is applied to derive a key of the requested byte length (<code>keylen</code>) from the <code>password</code>, <code>salt</code> and <code>iterations</code>.</p> <p>The supplied <code>callback</code> function is called with two arguments: <code>err</code> and <code>derivedKey</code>. If an error occurs while deriving the key, <code>err</code> will be set; otherwise <code>err</code> will be <code>null</code>. By default, the successfully generated <code>derivedKey</code> will be passed to the callback as a <a href="buffer.html"><code>Buffer</code></a>. An error will be thrown if any of the input arguments specify invalid values or types.</p> <p>If <code>digest</code> is <code>null</code>, <code>'sha1'</code> will be used. This behavior will be deprecated in a future version of Node.js.</p> <p>The <code>iterations</code> argument must be a number set as high as possible. The higher the number of iterations, the more secure the derived key will be, but will take a longer amount of time to complete.</p> <p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p> <pre><code class="language-js">const crypto = require('crypto'); crypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { if (err) throw err; console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' }); </code></pre> <p>The <code>crypto.DEFAULT_ENCODING</code> property can be used to change the way the <code>derivedKey</code> is passed to the callback. This property, however, has been deprecated and use should be avoided.</p> <pre><code class="language-js">const crypto = require('crypto'); crypto.DEFAULT_ENCODING = 'hex'; crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { if (err) throw err; console.log(derivedKey); // '3745e48...aa39b34' }); </code></pre> <p>An array of supported digest functions can be retrieved using <a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a>.</p> <p>Note that this API uses libuv's threadpool, which can have surprising and negative performance implications for some applications, see the <a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p> <h3>crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)<span><a class="mark" href="#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest" id="crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>Calling this function without passing the <code>digest</code> parameter is deprecated now and will emit a warning.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The default encoding for <code>password</code> if it is a string changed from <code>binary</code> to <code>utf8</code>.</p></td></tr> <tr><td>v0.9.3</td> <td><p><span>Added in: v0.9.3</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>salt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>iterations</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>digest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) implementation. A selected HMAC digest algorithm specified by <code>digest</code> is applied to derive a key of the requested byte length (<code>keylen</code>) from the <code>password</code>, <code>salt</code> and <code>iterations</code>.</p> <p>If an error occurs an <code>Error</code> will be thrown, otherwise the derived key will be returned as a <a href="buffer.html"><code>Buffer</code></a>.</p> <p>If <code>digest</code> is <code>null</code>, <code>'sha1'</code> will be used. This behavior will be deprecated in a future version of Node.js.</p> <p>The <code>iterations</code> argument must be a number set as high as possible. The higher the number of iterations, the more secure the derived key will be, but will take a longer amount of time to complete.</p> <p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p> <pre><code class="language-js">const crypto = require('crypto'); const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); console.log(key.toString('hex')); // '3745e48...08d59ae' </code></pre> <p>The <code>crypto.DEFAULT_ENCODING</code> property may be used to change the way the <code>derivedKey</code> is returned. This property, however, is deprecated and use should be avoided.</p> <pre><code class="language-js">const crypto = require('crypto'); crypto.DEFAULT_ENCODING = 'hex'; const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); console.log(key); // '3745e48...aa39b34' </code></pre> <p>An array of supported digest functions can be retrieved using <a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a>.</p> <h3>crypto.privateDecrypt(privateKey, buffer)<span><a class="mark" href="#crypto_crypto_privatedecrypt_privatekey_buffer" id="crypto_crypto_privatedecrypt_privatekey_buffer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <ul> <li> <p><code>privateKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A PEM encoded private key.</li> <li><code>passphrase</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> An optional passphrase for the private key.</li> <li><code>padding</code> <a href="#crypto_crypto_constants_1" class="type"><crypto.constants></a> An optional padding value defined in <code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code>, <code>crypto.constants.RSA_PKCS1_PADDING</code>, or <code>crypto.constants.RSA_PKCS1_OAEP_PADDING</code>.</li> </ul> </li> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> A new <code>Buffer</code> with the decrypted content.</li> </ul> <p>Decrypts <code>buffer</code> with <code>privateKey</code>. <code>buffer</code> was previously encrypted using the corresponding public key, for example using <a href="#crypto_crypto_publicencrypt_key_buffer"><code>crypto.publicEncrypt()</code></a>.</p> <p><code>privateKey</code> can be an object or a string. If <code>privateKey</code> is a string, it is treated as the key with no passphrase and will use <code>RSA_PKCS1_OAEP_PADDING</code>.</p> <h3>crypto.privateEncrypt(privateKey, buffer)<span><a class="mark" href="#crypto_crypto_privateencrypt_privatekey_buffer" id="crypto_crypto_privateencrypt_privatekey_buffer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.1.0</span> </div> <ul> <li> <p><code>privateKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A PEM encoded private key.</li> <li><code>passphrase</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> An optional passphrase for the private key.</li> <li><code>padding</code> <a href="#crypto_crypto_constants_1" class="type"><crypto.constants></a> An optional padding value defined in <code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code> or <code>crypto.constants.RSA_PKCS1_PADDING</code>.</li> </ul> </li> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> A new <code>Buffer</code> with the encrypted content.</li> </ul> <p>Encrypts <code>buffer</code> with <code>privateKey</code>. The returned data can be decrypted using the corresponding public key, for example using <a href="#crypto_crypto_publicdecrypt_key_buffer"><code>crypto.publicDecrypt()</code></a>.</p> <p><code>privateKey</code> can be an object or a string. If <code>privateKey</code> is a string, it is treated as the key with no passphrase and will use <code>RSA_PKCS1_PADDING</code>.</p> <h3>crypto.publicDecrypt(key, buffer)<span><a class="mark" href="#crypto_crypto_publicdecrypt_key_buffer" id="crypto_crypto_publicdecrypt_key_buffer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.1.0</span> </div> <ul> <li> <p><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A PEM encoded public or private key.</li> <li><code>passphrase</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> An optional passphrase for the private key.</li> <li><code>padding</code> <a href="#crypto_crypto_constants_1" class="type"><crypto.constants></a> An optional padding value defined in <code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code> or <code>crypto.constants.RSA_PKCS1_PADDING</code>.</li> </ul> </li> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> A new <code>Buffer</code> with the decrypted content.</li> </ul> <p>Decrypts <code>buffer</code> with <code>key</code>.<code>buffer</code> was previously encrypted using the corresponding private key, for example using <a href="#crypto_crypto_privateencrypt_privatekey_buffer"><code>crypto.privateEncrypt()</code></a>.</p> <p><code>key</code> can be an object or a string. If <code>key</code> is a string, it is treated as the key with no passphrase and will use <code>RSA_PKCS1_PADDING</code>.</p> <p>Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key.</p> <h3>crypto.publicEncrypt(key, buffer)<span><a class="mark" href="#crypto_crypto_publicencrypt_key_buffer" id="crypto_crypto_publicencrypt_key_buffer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <ul> <li> <p><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A PEM encoded public or private key.</li> <li><code>passphrase</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> An optional passphrase for the private key.</li> <li><code>padding</code> <a href="#crypto_crypto_constants_1" class="type"><crypto.constants></a> An optional padding value defined in <code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code>, <code>crypto.constants.RSA_PKCS1_PADDING</code>, or <code>crypto.constants.RSA_PKCS1_OAEP_PADDING</code>.</li> </ul> </li> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> A new <code>Buffer</code> with the encrypted content.</li> </ul> <p>Encrypts the content of <code>buffer</code> with <code>key</code> and returns a new <a href="buffer.html"><code>Buffer</code></a> with encrypted content. The returned data can be decrypted using the corresponding private key, for example using <a href="#crypto_crypto_privatedecrypt_privatekey_buffer"><code>crypto.privateDecrypt()</code></a>.</p> <p><code>key</code> can be an object or a string. If <code>key</code> is a string, it is treated as the key with no passphrase and will use <code>RSA_PKCS1_OAEP_PADDING</code>.</p> <p>Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key.</p> <h3>crypto.randomBytes(size[, callback])<span><a class="mark" href="#crypto_crypto_randombytes_size_callback" id="crypto_crypto_randombytes_size_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Passing <code>null</code> as the <code>callback</code> argument now throws <code>ERR_INVALID_CALLBACK</code>.</p></td></tr> <tr><td>v0.5.8</td> <td><p><span>Added in: v0.5.8</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>buf</code> <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> if the <code>callback</code> function is not provided.</li> </ul> <p>Generates cryptographically strong pseudo-random data. The <code>size</code> argument is a number indicating the number of bytes to generate.</p> <p>If a <code>callback</code> function is provided, the bytes are generated asynchronously and the <code>callback</code> function is invoked with two arguments: <code>err</code> and <code>buf</code>. If an error occurs, <code>err</code> will be an <code>Error</code> object; otherwise it is <code>null</code>. The <code>buf</code> argument is a <a href="buffer.html"><code>Buffer</code></a> containing the generated bytes.</p> <pre><code class="language-js">// Asynchronous const crypto = require('crypto'); crypto.randomBytes(256, (err, buf) => { if (err) throw err; console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); }); </code></pre> <p>If the <code>callback</code> function is not provided, the random bytes are generated synchronously and returned as a <a href="buffer.html"><code>Buffer</code></a>. An error will be thrown if there is a problem generating the bytes.</p> <pre><code class="language-js">// Synchronous const buf = crypto.randomBytes(256); console.log( `${buf.length} bytes of random data: ${buf.toString('hex')}`); </code></pre> <p>The <code>crypto.randomBytes()</code> method will not complete until there is sufficient entropy available. This should normally never take longer than a few milliseconds. The only time when generating the random bytes may conceivably block for a longer period of time is right after boot, when the whole system is still low on entropy.</p> <p>Note that this API uses libuv's threadpool, which can have surprising and negative performance implications for some applications, see the <a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p> <p>The asynchronous version of <code>crypto.randomBytes()</code> is carried out in a single threadpool request. To minimize threadpool task length variation, partition large <code>randomBytes</code> requests when doing so as part of fulfilling a client request.</p> <h3>crypto.randomFillSync(buffer[, offset][, size])<span><a class="mark" href="#crypto_crypto_randomfillsync_buffer_offset_size" id="crypto_crypto_randomfillsync_buffer_offset_size">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>The <code>buffer</code> argument may be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v7.10.0, v6.13.0</td> <td><p><span>Added in: v7.10.0, v6.13.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> Must be supplied.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>0</code></li> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>buffer.length - offset</code></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> The object passed as <code>buffer</code> argument.</li> </ul> <p>Synchronous version of <a href="#crypto_crypto_randomfill_buffer_offset_size_callback"><code>crypto.randomFill()</code></a>.</p> <pre><code class="language-js">const buf = Buffer.alloc(10); console.log(crypto.randomFillSync(buf).toString('hex')); crypto.randomFillSync(buf, 5); console.log(buf.toString('hex')); // The above is equivalent to the following: crypto.randomFillSync(buf, 5, 5); console.log(buf.toString('hex')); </code></pre> <p>Any <code>TypedArray</code> or <code>DataView</code> instance may be passed as <code>buffer</code>.</p> <pre><code class="language-js">const a = new Uint32Array(10); console.log(Buffer.from(crypto.randomFillSync(a).buffer, a.byteOffset, a.byteLength).toString('hex')); const b = new Float64Array(10); console.log(Buffer.from(crypto.randomFillSync(b).buffer, b.byteOffset, b.byteLength).toString('hex')); const c = new DataView(new ArrayBuffer(10)); console.log(Buffer.from(crypto.randomFillSync(c).buffer, c.byteOffset, c.byteLength).toString('hex')); </code></pre> <h3>crypto.randomFill(buffer[, offset][, size], callback)<span><a class="mark" href="#crypto_crypto_randomfill_buffer_offset_size_callback" id="crypto_crypto_randomfill_buffer_offset_size_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>The <code>buffer</code> argument may be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v7.10.0, v6.13.0</td> <td><p><span>Added in: v7.10.0, v6.13.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> Must be supplied.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>0</code></li> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>buffer.length - offset</code></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> <code>function(err, buf) {}</code>.</li> </ul> <p>This function is similar to <a href="#crypto_crypto_randombytes_size_callback"><code>crypto.randomBytes()</code></a> but requires the first argument to be a <a href="buffer.html"><code>Buffer</code></a> that will be filled. It also requires that a callback is passed in.</p> <p>If the <code>callback</code> function is not provided, an error will be thrown.</p> <pre><code class="language-js">const buf = Buffer.alloc(10); crypto.randomFill(buf, (err, buf) => { if (err) throw err; console.log(buf.toString('hex')); }); crypto.randomFill(buf, 5, (err, buf) => { if (err) throw err; console.log(buf.toString('hex')); }); // The above is equivalent to the following: crypto.randomFill(buf, 5, 5, (err, buf) => { if (err) throw err; console.log(buf.toString('hex')); }); </code></pre> <p>Any <code>TypedArray</code> or <code>DataView</code> instance may be passed as <code>buffer</code>.</p> <pre><code class="language-js">const a = new Uint32Array(10); crypto.randomFill(a, (err, buf) => { if (err) throw err; console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) .toString('hex')); }); const b = new Float64Array(10); crypto.randomFill(b, (err, buf) => { if (err) throw err; console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) .toString('hex')); }); const c = new DataView(new ArrayBuffer(10)); crypto.randomFill(c, (err, buf) => { if (err) throw err; console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) .toString('hex')); }); </code></pre> <p>Note that this API uses libuv's threadpool, which can have surprising and negative performance implications for some applications, see the <a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p> <p>The asynchronous version of <code>crypto.randomFill()</code> is carried out in a single threadpool request. To minimize threadpool task length variation, partition large <code>randomFill</code> requests when doing so as part of fulfilling a client request.</p> <h3>crypto.scrypt(password, salt, keylen[, options], callback)<span><a class="mark" href="#crypto_crypto_scrypt_password_salt_keylen_options_callback" id="crypto_crypto_scrypt_password_salt_keylen_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.17.0</td> <td><p>The <code>maxmem</code> value can now be any safe integer.</p></td></tr> <tr><td>v10.9.0</td> <td><p>The <code>cost</code>, <code>blockSize</code> and <code>parallelization</code> option names have been added.</p></td></tr> <tr><td>v10.5.0</td> <td><p><span>Added in: v10.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>salt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>cost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> CPU/memory cost parameter. Must be a power of two greater</li> <li><code>N</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> CPU/memory cost parameter. Must be a power of two greater than one. <strong>Default:</strong> <code>16384</code>.</li> <li><code>blockSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Block size parameter. <strong>Default:</strong> <code>8</code>.</li> <li><code>parallelization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Parallelization parameter. <strong>Default:</strong> <code>1</code>.</li> <li><code>N</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>cost</code>. Only one of both may be specified.</li> <li><code>r</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>blockSize</code>. Only one of both may be specified.</li> <li><code>p</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>parallelization</code>. Only one of both may be specified.</li> <li><code>maxmem</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Memory upper bound. It is an error when (approximately) <code>128 * N * r > maxmem</code>. <strong>Default:</strong> <code>32 * 1024 * 1024</code>.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>derivedKey</code> <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> </ul> <p>Provides an asynchronous <a href="https://en.wikipedia.org/wiki/Scrypt">scrypt</a> implementation. Scrypt is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.</p> <p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p> <p>The <code>callback</code> function is called with two arguments: <code>err</code> and <code>derivedKey</code>. <code>err</code> is an exception object when key derivation fails, otherwise <code>err</code> is <code>null</code>. <code>derivedKey</code> is passed to the callback as a <a href="buffer.html"><code>Buffer</code></a>.</p> <p>An exception is thrown when any of the input arguments specify invalid values or types.</p> <pre><code class="language-js">const crypto = require('crypto'); // Using the factory defaults. crypto.scrypt('secret', 'salt', 64, (err, derivedKey) => { if (err) throw err; console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' }); // Using a custom N parameter. Must be a power of two. crypto.scrypt('secret', 'salt', 64, { N: 1024 }, (err, derivedKey) => { if (err) throw err; console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' }); </code></pre> <h3>crypto.scryptSync(password, salt, keylen[, options])<span><a class="mark" href="#crypto_crypto_scryptsync_password_salt_keylen_options" id="crypto_crypto_scryptsync_password_salt_keylen_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.17.0</td> <td><p>The <code>maxmem</code> value can now be any safe integer.</p></td></tr> <tr><td>v10.9.0</td> <td><p>The <code>cost</code>, <code>blockSize</code> and <code>parallelization</code> option names have been added.</p></td></tr> <tr><td>v10.5.0</td> <td><p><span>Added in: v10.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>salt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>cost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> CPU/memory cost parameter. Must be a power of two greater</li> <li><code>N</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> CPU/memory cost parameter. Must be a power of two greater than one. <strong>Default:</strong> <code>16384</code>.</li> <li><code>blockSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Block size parameter. <strong>Default:</strong> <code>8</code>.</li> <li><code>parallelization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Parallelization parameter. <strong>Default:</strong> <code>1</code>.</li> <li><code>N</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>cost</code>. Only one of both may be specified.</li> <li><code>r</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>blockSize</code>. Only one of both may be specified.</li> <li><code>p</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Alias for <code>parallelization</code>. Only one of both may be specified.</li> <li><code>maxmem</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Memory upper bound. It is an error when (approximately) <code>128 * N * r > maxmem</code>. <strong>Default:</strong> <code>32 * 1024 * 1024</code>.</li> </ul> </li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Provides a synchronous <a href="https://en.wikipedia.org/wiki/Scrypt">scrypt</a> implementation. Scrypt is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.</p> <p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p> <p>An exception is thrown when key derivation fails, otherwise the derived key is returned as a <a href="buffer.html"><code>Buffer</code></a>.</p> <p>An exception is thrown when any of the input arguments specify invalid values or types.</p> <pre><code class="language-js">const crypto = require('crypto'); // Using the factory defaults. const key1 = crypto.scryptSync('secret', 'salt', 64); console.log(key1.toString('hex')); // '3745e48...08d59ae' // Using a custom N parameter. Must be a power of two. const key2 = crypto.scryptSync('secret', 'salt', 64, { N: 1024 }); console.log(key2.toString('hex')); // '3745e48...aa39b34' </code></pre> <h3>crypto.setEngine(engine[, flags])<span><a class="mark" href="#crypto_crypto_setengine_engine_flags" id="crypto_crypto_setengine_engine_flags">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.11</span> </div> <ul> <li><code>engine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>flags</code> <a href="#crypto_crypto_constants_1" class="type"><crypto.constants></a> <strong>Default:</strong> <code>crypto.constants.ENGINE_METHOD_ALL</code></li> </ul> <p>Load and set the <code>engine</code> for some or all OpenSSL functions (selected by flags).</p> <p><code>engine</code> could be either an id or a path to the engine's shared library.</p> <p>The optional <code>flags</code> argument uses <code>ENGINE_METHOD_ALL</code> by default. The <code>flags</code> is a bit field taking one of or a mix of the following flags (defined in <code>crypto.constants</code>):</p> <ul> <li><code>crypto.constants.ENGINE_METHOD_RSA</code></li> <li><code>crypto.constants.ENGINE_METHOD_DSA</code></li> <li><code>crypto.constants.ENGINE_METHOD_DH</code></li> <li><code>crypto.constants.ENGINE_METHOD_RAND</code></li> <li><code>crypto.constants.ENGINE_METHOD_EC</code></li> <li><code>crypto.constants.ENGINE_METHOD_CIPHERS</code></li> <li><code>crypto.constants.ENGINE_METHOD_DIGESTS</code></li> <li><code>crypto.constants.ENGINE_METHOD_PKEY_METHS</code></li> <li><code>crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS</code></li> <li><code>crypto.constants.ENGINE_METHOD_ALL</code></li> <li><code>crypto.constants.ENGINE_METHOD_NONE</code></li> </ul> <p>The flags below are deprecated in OpenSSL-1.1.0.</p> <ul> <li><code>crypto.constants.ENGINE_METHOD_ECDH</code></li> <li><code>crypto.constants.ENGINE_METHOD_ECDSA</code></li> <li><code>crypto.constants.ENGINE_METHOD_STORE</code></li> </ul> <h3>crypto.setFips(bool)<span><a class="mark" href="#crypto_crypto_setfips_bool" id="crypto_crypto_setfips_bool">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>bool</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to enable FIPS mode.</li> </ul> <p>Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available.</p> <h3>crypto.timingSafeEqual(a, b)<span><a class="mark" href="#crypto_crypto_timingsafeequal_a_b" id="crypto_crypto_timingsafeequal_a_b">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.6.0</span> </div> <ul> <li><code>a</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>b</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>This function is based on a constant-time algorithm. Returns true if <code>a</code> is equal to <code>b</code>, without leaking timing information that would allow an attacker to guess one of the values. This is suitable for comparing HMAC digests or secret values like authentication cookies or <a href="https://www.w3.org/TR/capability-urls/">capability urls</a>.</p> <p><code>a</code> and <code>b</code> must both be <code>Buffer</code>s, <code>TypedArray</code>s, or <code>DataView</code>s, and they must have the same length.</p> <p>Use of <code>crypto.timingSafeEqual</code> does not guarantee that the <em>surrounding</em> code is timing-safe. Care should be taken to ensure that the surrounding code does not introduce timing vulnerabilities.</p> <h2>Notes<span><a class="mark" href="#crypto_notes" id="crypto_notes">#</a></span></h2> <h3>Legacy Streams API (pre Node.js v0.10)<span><a class="mark" href="#crypto_legacy_streams_api_pre_node_js_v0_10" id="crypto_legacy_streams_api_pre_node_js_v0_10">#</a></span></h3> <p>The Crypto module was added to Node.js before there was the concept of a unified Stream API, and before there were <a href="buffer.html"><code>Buffer</code></a> objects for handling binary data. As such, the many of the <code>crypto</code> defined classes have methods not typically found on other Node.js classes that implement the <a href="stream.html">streams</a> API (e.g. <code>update()</code>, <code>final()</code>, or <code>digest()</code>). Also, many methods accepted and returned <code>'latin1'</code> encoded strings by default rather than <code>Buffer</code>s. This default was changed after Node.js v0.8 to use <a href="buffer.html"><code>Buffer</code></a> objects by default instead.</p> <h3>Recent ECDH Changes<span><a class="mark" href="#crypto_recent_ecdh_changes" id="crypto_recent_ecdh_changes">#</a></span></h3> <p>Usage of <code>ECDH</code> with non-dynamically generated key pairs has been simplified. Now, <a href="#crypto_ecdh_setprivatekey_privatekey_encoding"><code>ecdh.setPrivateKey()</code></a> can be called with a preselected private key and the associated public point (key) will be computed and stored in the object. This allows code to only store and provide the private part of the EC key pair. <a href="#crypto_ecdh_setprivatekey_privatekey_encoding"><code>ecdh.setPrivateKey()</code></a> now also validates that the private key is valid for the selected curve.</p> <p>The <a href="#crypto_ecdh_setpublickey_publickey_encoding"><code>ecdh.setPublicKey()</code></a> method is now deprecated as its inclusion in the API is not useful. Either a previously stored private key should be set, which automatically generates the associated public key, or <a href="#crypto_ecdh_generatekeys_encoding_format"><code>ecdh.generateKeys()</code></a> should be called. The main drawback of using <a href="#crypto_ecdh_setpublickey_publickey_encoding"><code>ecdh.setPublicKey()</code></a> is that it can be used to put the ECDH key pair into an inconsistent state.</p> <h3>Support for weak or compromised algorithms<span><a class="mark" href="#crypto_support_for_weak_or_compromised_algorithms" id="crypto_support_for_weak_or_compromised_algorithms">#</a></span></h3> <p>The <code>crypto</code> module still supports some algorithms which are already compromised and are not currently recommended for use. The API also allows the use of ciphers and hashes with a small key size that are considered to be too weak for safe use.</p> <p>Users should take full responsibility for selecting the crypto algorithm and key size according to their security requirements.</p> <p>Based on the recommendations of <a href="https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf">NIST SP 800-131A</a>:</p> <ul> <li>MD5 and SHA-1 are no longer acceptable where collision resistance is required such as digital signatures.</li> <li>The key used with RSA, DSA, and DH algorithms is recommended to have at least 2048 bits and that of the curve of ECDSA and ECDH at least 224 bits, to be safe to use for several years.</li> <li>The DH groups of <code>modp1</code>, <code>modp2</code> and <code>modp5</code> have a key size smaller than 2048 bits and are not recommended.</li> </ul> <p>See the reference for other recommendations and details.</p> <h3>CCM mode<span><a class="mark" href="#crypto_ccm_mode" id="crypto_ccm_mode">#</a></span></h3> <p>CCM is one of the supported <a href="https://en.wikipedia.org/wiki/Authenticated_encryption">AEAD algorithms</a>. Applications which use this mode must adhere to certain restrictions when using the cipher API:</p> <ul> <li>The authentication tag length must be specified during cipher creation by setting the <code>authTagLength</code> option and must be one of 4, 6, 8, 10, 12, 14 or 16 bytes.</li> <li>The length of the initialization vector (nonce) <code>N</code> must be between 7 and 13 bytes (<code>7 ≤ N ≤ 13</code>).</li> <li>The length of the plaintext is limited to <code>2 ** (8 * (15 - N))</code> bytes.</li> <li>When decrypting, the authentication tag must be set via <code>setAuthTag()</code> before specifying additional authenticated data or calling <code>update()</code>. Otherwise, decryption will fail and <code>final()</code> will throw an error in compliance with section 2.6 of <a href="https://www.rfc-editor.org/rfc/rfc3610.txt">RFC 3610</a>.</li> <li>Using stream methods such as <code>write(data)</code>, <code>end(data)</code> or <code>pipe()</code> in CCM mode might fail as CCM cannot handle more than one chunk of data per instance.</li> <li>When passing additional authenticated data (AAD), the length of the actual message in bytes must be passed to <code>setAAD()</code> via the <code>plaintextLength</code> option. This is not necessary if no AAD is used.</li> <li>As CCM processes the whole message at once, <code>update()</code> can only be called once.</li> <li>Even though calling <code>update()</code> is sufficient to encrypt/decrypt the message, applications <em>must</em> call <code>final()</code> to compute or verify the authentication tag.</li> </ul> <pre><code class="language-js">const crypto = require('crypto'); const key = 'keykeykeykeykeykeykeykey'; const nonce = crypto.randomBytes(12); const aad = Buffer.from('0123456789', 'hex'); const cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, { authTagLength: 16 }); const plaintext = 'Hello world'; cipher.setAAD(aad, { plaintextLength: Buffer.byteLength(plaintext) }); const ciphertext = cipher.update(plaintext, 'utf8'); cipher.final(); const tag = cipher.getAuthTag(); // Now transmit { ciphertext, nonce, tag }. const decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, { authTagLength: 16 }); decipher.setAuthTag(tag); decipher.setAAD(aad, { plaintextLength: ciphertext.length }); const receivedPlaintext = decipher.update(ciphertext, null, 'utf8'); try { decipher.final(); } catch (err) { console.error('Authentication failed!'); } console.log(receivedPlaintext); </code></pre> <h2>Crypto Constants<span><a class="mark" href="#crypto_crypto_constants_1" id="crypto_crypto_constants_1">#</a></span></h2> <p>The following constants exported by <code>crypto.constants</code> apply to various uses of the <code>crypto</code>, <code>tls</code>, and <code>https</code> modules and are generally specific to OpenSSL.</p> <h3>OpenSSL Options<span><a class="mark" href="#crypto_openssl_options" id="crypto_openssl_options">#</a></span></h3> <!--lint disable maximum-line-length--> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>SSL_OP_ALL</code></td> <td>Applies multiple bug workarounds within OpenSSL. See <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a> for detail.</td> </tr> <tr> <td><code>SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION</code></td> <td>Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a>.</td> </tr> <tr> <td><code>SSL_OP_CIPHER_SERVER_PREFERENCE</code></td> <td>Attempts to use the server's preferences instead of the client's when selecting a cipher. Behavior depends on protocol version. See <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a>.</td> </tr> <tr> <td><code>SSL_OP_CISCO_ANYCONNECT</code></td> <td>Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER.</td> </tr> <tr> <td><code>SSL_OP_COOKIE_EXCHANGE</code></td> <td>Instructs OpenSSL to turn on cookie exchange.</td> </tr> <tr> <td><code>SSL_OP_CRYPTOPRO_TLSEXT_BUG</code></td> <td>Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft.</td> </tr> <tr> <td><code>SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS</code></td> <td>Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d.</td> </tr> <tr> <td><code>SSL_OP_EPHEMERAL_RSA</code></td> <td>Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations.</td> </tr> <tr> <td><code>SSL_OP_LEGACY_SERVER_CONNECT</code></td> <td>Allows initial connection to servers that do not support RI.</td> </tr> <tr> <td><code>SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_MICROSOFT_SESS_ID_BUG</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_MSIE_SSLV2_RSA_PADDING</code></td> <td>Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation.</td> </tr> <tr> <td><code>SSL_OP_NETSCAPE_CA_DN_BUG</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_NETSCAPE_CHALLENGE_BUG</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_NO_COMPRESSION</code></td> <td>Instructs OpenSSL to disable support for SSL/TLS compression.</td> </tr> <tr> <td><code>SSL_OP_NO_QUERY_MTU</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION</code></td> <td>Instructs OpenSSL to always start a new session when performing renegotiation.</td> </tr> <tr> <td><code>SSL_OP_NO_SSLv2</code></td> <td>Instructs OpenSSL to turn off SSL v2</td> </tr> <tr> <td><code>SSL_OP_NO_SSLv3</code></td> <td>Instructs OpenSSL to turn off SSL v3</td> </tr> <tr> <td><code>SSL_OP_NO_TICKET</code></td> <td>Instructs OpenSSL to disable use of RFC4507bis tickets.</td> </tr> <tr> <td><code>SSL_OP_NO_TLSv1</code></td> <td>Instructs OpenSSL to turn off TLS v1</td> </tr> <tr> <td><code>SSL_OP_NO_TLSv1_1</code></td> <td>Instructs OpenSSL to turn off TLS v1.1</td> </tr> <tr> <td><code>SSL_OP_NO_TLSv1_2</code></td> <td>Instructs OpenSSL to turn off TLS v1.2</td> </tr> <tr><td><code>SSL_OP_PKCS1_CHECK_1</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_PKCS1_CHECK_2</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_SINGLE_DH_USE</code></td> <td>Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters.</td> </tr> <tr> <td><code>SSL_OP_SINGLE_ECDH_USE</code></td> <td>Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters.</td> </tr> <tr><td><code>SSL_OP_SSLEAY_080_CLIENT_DH_BUG</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_TLS_BLOCK_PADDING_BUG</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_TLS_D5_BUG</code></td> <td></td> </tr> <tr> <td><code>SSL_OP_TLS_ROLLBACK_BUG</code></td> <td>Instructs OpenSSL to disable version rollback attack detection.</td> </tr> </tbody></table> <h3>OpenSSL Engine Constants<span><a class="mark" href="#crypto_openssl_engine_constants" id="crypto_openssl_engine_constants">#</a></span></h3> <!--lint enable maximum-line-length remark-lint--> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>ENGINE_METHOD_RSA</code></td> <td>Limit engine usage to RSA</td> </tr> <tr> <td><code>ENGINE_METHOD_DSA</code></td> <td>Limit engine usage to DSA</td> </tr> <tr> <td><code>ENGINE_METHOD_DH</code></td> <td>Limit engine usage to DH</td> </tr> <tr> <td><code>ENGINE_METHOD_RAND</code></td> <td>Limit engine usage to RAND</td> </tr> <tr> <td><code>ENGINE_METHOD_EC</code></td> <td>Limit engine usage to EC</td> </tr> <tr> <td><code>ENGINE_METHOD_CIPHERS</code></td> <td>Limit engine usage to CIPHERS</td> </tr> <tr> <td><code>ENGINE_METHOD_DIGESTS</code></td> <td>Limit engine usage to DIGESTS</td> </tr> <tr> <td><code>ENGINE_METHOD_PKEY_METHS</code></td> <td>Limit engine usage to PKEY_METHDS</td> </tr> <tr> <td><code>ENGINE_METHOD_PKEY_ASN1_METHS</code></td> <td>Limit engine usage to PKEY_ASN1_METHS</td> </tr> <tr> <td><code>ENGINE_METHOD_ALL</code></td> <td></td> </tr> <tr> <td><code>ENGINE_METHOD_NONE</code></td> <td></td> </tr> </tbody></table> <h3>Other OpenSSL Constants<span><a class="mark" href="#crypto_other_openssl_constants" id="crypto_other_openssl_constants">#</a></span></h3> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>DH_CHECK_P_NOT_SAFE_PRIME</code></td> <td></td> </tr> <tr> <td><code>DH_CHECK_P_NOT_PRIME</code></td> <td></td> </tr> <tr> <td><code>DH_UNABLE_TO_CHECK_GENERATOR</code></td> <td></td> </tr> <tr> <td><code>DH_NOT_SUITABLE_GENERATOR</code></td> <td></td> </tr> <tr> <td><code>ALPN_ENABLED</code></td> <td></td> </tr> <tr> <td><code>RSA_PKCS1_PADDING</code></td> <td></td> </tr> <tr> <td><code>RSA_SSLV23_PADDING</code></td> <td></td> </tr> <tr> <td><code>RSA_NO_PADDING</code></td> <td></td> </tr> <tr> <td><code>RSA_PKCS1_OAEP_PADDING</code></td> <td></td> </tr> <tr> <td><code>RSA_X931_PADDING</code></td> <td></td> </tr> <tr> <td><code>RSA_PKCS1_PSS_PADDING</code></td> <td></td> </tr> <tr> <td><code>RSA_PSS_SALTLEN_DIGEST</code></td> <td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the digest size when signing or verifying.</td> </tr> <tr> <td><code>RSA_PSS_SALTLEN_MAX_SIGN</code></td> <td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the maximum permissible value when signing data.</td> </tr> <tr> <td><code>RSA_PSS_SALTLEN_AUTO</code></td> <td>Causes the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to be determined automatically when verifying a signature.</td> </tr> <tr> <td><code>POINT_CONVERSION_COMPRESSED</code></td> <td></td> </tr> <tr> <td><code>POINT_CONVERSION_UNCOMPRESSED</code></td> <td></td> </tr> <tr> <td><code>POINT_CONVERSION_HYBRID</code></td> <td></td> </tr> </tbody></table> <h3>Node.js Crypto Constants<span><a class="mark" href="#crypto_node_js_crypto_constants" id="crypto_node_js_crypto_constants">#</a></span></h3> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>defaultCoreCipherList</code></td> <td>Specifies the built-in default cipher list used by Node.js.</td> </tr> <tr> <td><code>defaultCipherList</code></td> <td>Specifies the active default cipher list used by the current Node.js process.</td> </tr> </tbody></table> <h1>Debugger<span><a class="mark" href="#debugger_debugger" id="debugger_debugger">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>Node.js includes an out-of-process debugging utility accessible via a <a href="#debugger_v8_inspector_integration_for_node_js">V8 Inspector</a> and built-in debugging client. To use it, start Node.js with the <code>inspect</code> argument followed by the path to the script to debug; a prompt will be displayed indicating successful launch of the debugger:</p> <pre><code class="language-txt">$ node inspect myscript.js < Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba < For help, see: https://nodejs.org/en/docs/inspector < Debugger attached. Break on start in myscript.js:1 > 1 (function (exports, require, module, __filename, __dirname) { global.x = 5; 2 setTimeout(() => { 3 console.log('world'); debug> </code></pre> <p>Node.js's debugger client is not a full-featured debugger, but simple step and inspection are possible.</p> <p>Inserting the statement <code>debugger;</code> into the source code of a script will enable a breakpoint at that position in the code:</p> <!-- eslint-disable no-debugger --> <pre><code class="language-js">// myscript.js global.x = 5; setTimeout(() => { debugger; console.log('world'); }, 1000); console.log('hello'); </code></pre> <p>Once the debugger is run, a breakpoint will occur at line 3:</p> <pre><code class="language-txt">$ node inspect myscript.js < Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba < For help, see: https://nodejs.org/en/docs/inspector < Debugger attached. Break on start in myscript.js:1 > 1 (function (exports, require, module, __filename, __dirname) { global.x = 5; 2 setTimeout(() => { 3 debugger; debug> cont < hello break in myscript.js:3 1 (function (exports, require, module, __filename, __dirname) { global.x = 5; 2 setTimeout(() => { > 3 debugger; 4 console.log('world'); 5 }, 1000); debug> next break in myscript.js:4 2 setTimeout(() => { 3 debugger; > 4 console.log('world'); 5 }, 1000); 6 console.log('hello'); debug> repl Press Ctrl + C to leave debug repl > x 5 > 2 + 2 4 debug> next < world break in myscript.js:5 3 debugger; 4 console.log('world'); > 5 }, 1000); 6 console.log('hello'); 7 debug> .exit </code></pre> <p>The <code>repl</code> command allows code to be evaluated remotely. The <code>next</code> command steps to the next line. Type <code>help</code> to see what other commands are available.</p> <p>Pressing <code>enter</code> without typing a command will repeat the previous debugger command.</p> <h2>Watchers<span><a class="mark" href="#debugger_watchers" id="debugger_watchers">#</a></span></h2> <p>It is possible to watch expression and variable values while debugging. On every breakpoint, each expression from the watchers list will be evaluated in the current context and displayed immediately before the breakpoint's source code listing.</p> <p>To begin watching an expression, type <code>watch('my_expression')</code>. The command <code>watchers</code> will print the active watchers. To remove a watcher, type <code>unwatch('my_expression')</code>.</p> <h2>Command reference<span><a class="mark" href="#debugger_command_reference" id="debugger_command_reference">#</a></span></h2> <h3>Stepping<span><a class="mark" href="#debugger_stepping" id="debugger_stepping">#</a></span></h3> <ul> <li><code>cont</code>, <code>c</code> - Continue execution</li> <li><code>next</code>, <code>n</code> - Step next</li> <li><code>step</code>, <code>s</code> - Step in</li> <li><code>out</code>, <code>o</code> - Step out</li> <li><code>pause</code> - Pause running code (like pause button in Developer Tools)</li> </ul> <h3>Breakpoints<span><a class="mark" href="#debugger_breakpoints" id="debugger_breakpoints">#</a></span></h3> <ul> <li><code>setBreakpoint()</code>, <code>sb()</code> - Set breakpoint on current line</li> <li><code>setBreakpoint(line)</code>, <code>sb(line)</code> - Set breakpoint on specific line</li> <li><code>setBreakpoint('fn()')</code>, <code>sb(...)</code> - Set breakpoint on a first statement in functions body</li> <li><code>setBreakpoint('script.js', 1)</code>, <code>sb(...)</code> - Set breakpoint on first line of <code>script.js</code></li> <li><code>clearBreakpoint('script.js', 1)</code>, <code>cb(...)</code> - Clear breakpoint in <code>script.js</code> on line 1</li> </ul> <p>It is also possible to set a breakpoint in a file (module) that is not loaded yet:</p> <pre><code class="language-txt">$ node inspect main.js < Debugger listening on ws://127.0.0.1:9229/4e3db158-9791-4274-8909-914f7facf3bd < For help, see: https://nodejs.org/en/docs/inspector < Debugger attached. Break on start in main.js:1 > 1 (function (exports, require, module, __filename, __dirname) { const mod = require('./mod.js'); 2 mod.hello(); 3 mod.hello(); debug> setBreakpoint('mod.js', 22) Warning: script 'mod.js' was not loaded yet. debug> c break in mod.js:22 20 // USE OR OTHER DEALINGS IN THE SOFTWARE. 21 >22 exports.hello = function() { 23 return 'hello from module'; 24 }; debug> </code></pre> <h3>Information<span><a class="mark" href="#debugger_information" id="debugger_information">#</a></span></h3> <ul> <li><code>backtrace</code>, <code>bt</code> - Print backtrace of current execution frame</li> <li><code>list(5)</code> - List scripts source code with 5 line context (5 lines before and after)</li> <li><code>watch(expr)</code> - Add expression to watch list</li> <li><code>unwatch(expr)</code> - Remove expression from watch list</li> <li><code>watchers</code> - List all watchers and their values (automatically listed on each breakpoint)</li> <li><code>repl</code> - Open debugger's repl for evaluation in debugging script's context</li> <li><code>exec expr</code> - Execute an expression in debugging script's context</li> </ul> <h3>Execution control<span><a class="mark" href="#debugger_execution_control" id="debugger_execution_control">#</a></span></h3> <ul> <li><code>run</code> - Run script (automatically runs on debugger's start)</li> <li><code>restart</code> - Restart script</li> <li><code>kill</code> - Kill script</li> </ul> <h3>Various<span><a class="mark" href="#debugger_various" id="debugger_various">#</a></span></h3> <ul> <li><code>scripts</code> - List all loaded scripts</li> <li><code>version</code> - Display V8's version</li> </ul> <h2>Advanced Usage<span><a class="mark" href="#debugger_advanced_usage" id="debugger_advanced_usage">#</a></span></h2> <h3>V8 Inspector Integration for Node.js<span><a class="mark" href="#debugger_v8_inspector_integration_for_node_js" id="debugger_v8_inspector_integration_for_node_js">#</a></span></h3> <p>V8 Inspector integration allows attaching Chrome DevTools to Node.js instances for debugging and profiling. It uses the <a href="https://chromedevtools.github.io/devtools-protocol/">Chrome DevTools Protocol</a>.</p> <p>V8 Inspector can be enabled by passing the <code>--inspect</code> flag when starting a Node.js application. It is also possible to supply a custom port with that flag, e.g. <code>--inspect=9222</code> will accept DevTools connections on port 9222.</p> <p>To break on the first line of the application code, pass the <code>--inspect-brk</code> flag instead of <code>--inspect</code>.</p> <pre><code class="language-txt">$ node --inspect index.js Debugger listening on 127.0.0.1:9229. To start debugging, open the following URL in Chrome: chrome-devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws=127.0.0.1:9229/dc9010dd-f8b8-4ac5-a510-c1a114ec7d29 </code></pre> <p>(In the example above, the UUID dc9010dd-f8b8-4ac5-a510-c1a114ec7d29 at the end of the URL is generated on the fly, it varies in different debugging sessions.)</p> <p>If the Chrome browser is older than 66.0.3345.0, use <code>inspector.html</code> instead of <code>js_app.html</code> in the above URL.</p> <h1>Deprecated APIs<span><a class="mark" href="#deprecations_deprecated_apis" id="deprecations_deprecated_apis">#</a></span></h1> <p>Node.js may deprecate APIs when either: (a) use of the API is considered to be unsafe, (b) an improved alternative API is available, or (c) breaking changes to the API are expected in a future major release.</p> <p>Node.js utilizes three kinds of Deprecations:</p> <ul> <li>Documentation-only</li> <li>Runtime</li> <li>End-of-Life</li> </ul> <p>A Documentation-only deprecation is one that is expressed only within the Node.js API docs. These generate no side-effects while running Node.js. Some Documentation-only deprecations trigger a runtime warning when launched with <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a> flag (or its alternative, <code>NODE_PENDING_DEPRECATION=1</code> environment variable), similarly to Runtime deprecations below. Documentation-only deprecations that support that flag are explicitly labeled as such in the <a href="#deprecations_list_of_deprecated_apis">list of Deprecated APIs</a>.</p> <p>A Runtime deprecation will, by default, generate a process warning that will be printed to <code>stderr</code> the first time the deprecated API is used. When the <code>--throw-deprecation</code> command-line flag is used, a Runtime deprecation will cause an error to be thrown.</p> <p>An End-of-Life deprecation is used when functionality is or will soon be removed from Node.js.</p> <h2>Revoking deprecations<span><a class="mark" href="#deprecations_revoking_deprecations" id="deprecations_revoking_deprecations">#</a></span></h2> <p>Occasionally, the deprecation of an API may be reversed. In such situations, this document will be updated with information relevant to the decision. However, the deprecation identifier will not be modified.</p> <h2>List of Deprecated APIs<span><a class="mark" href="#deprecations_list_of_deprecated_apis" id="deprecations_list_of_deprecated_apis">#</a></span></h2> <p><a id="DEP0001"></a></p> <h3>DEP0001: http.OutgoingMessage.prototype.flush<span><a class="mark" href="#deprecations_dep0001_http_outgoingmessage_prototype_flush" id="deprecations_dep0001_http_outgoingmessage_prototype_flush">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v1.6.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <code>OutgoingMessage.prototype.flush()</code> method is deprecated. Use <code>OutgoingMessage.prototype.flushHeaders()</code> instead.</p> <p><a id="DEP0002"></a></p> <h3>DEP0002: require('_linklist')<span><a class="mark" href="#deprecations_dep0002_require_linklist" id="deprecations_dep0002_require_linklist">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v5.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>The <code>_linklist</code> module is deprecated. Please use a userland alternative.</p> <p><a id="DEP0003"></a></p> <h3>DEP0003: _writableState.buffer<span><a class="mark" href="#deprecations_dep0003_writablestate_buffer" id="deprecations_dep0003_writablestate_buffer">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.11.15</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <code>_writableState.buffer</code> property is deprecated. Use the <code>_writableState.getBuffer()</code> method instead.</p> <p><a id="DEP0004"></a></p> <h3>DEP0004: CryptoStream.prototype.readyState<span><a class="mark" href="#deprecations_dep0004_cryptostream_prototype_readystate" id="deprecations_dep0004_cryptostream_prototype_readystate">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>0.4.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>The <code>CryptoStream.prototype.readyState</code> property was removed.</p> <p><a id="DEP0005"></a></p> <h3>DEP0005: Buffer() constructor<span><a class="mark" href="#deprecations_dep0005_buffer_constructor" id="deprecations_dep0005_buffer_constructor">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime (supports <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a>)</p> <p>The <code>Buffer()</code> function and <code>new Buffer()</code> constructor are deprecated due to API usability issues that can potentially lead to accidental security issues.</p> <p>As an alternative, use of the following methods of constructing <code>Buffer</code> objects is strongly recommended:</p> <ul> <li><a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc(size[, fill[, encoding]])</code></a> - Create a <code>Buffer</code> with <em>initialized</em> memory.</li> <li><a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe(size)</code></a> - Create a <code>Buffer</code> with <em>uninitialized</em> memory.</li> <li><a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow(size)</code></a> - Create a <code>Buffer</code> with <em>uninitialized</em> memory.</li> <li><a href="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a> - Create a <code>Buffer</code> with a copy of <code>array</code></li> <li><a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a> - Create a <code>Buffer</code> that wraps the given <code>arrayBuffer</code>.</li> <li><a href="#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a> - Create a <code>Buffer</code> that copies <code>buffer</code>.</li> <li><a href="#buffer_class_method_buffer_from_string_encoding"><code>Buffer.from(string[, encoding])</code></a> - Create a <code>Buffer</code> that copies <code>string</code>.</li> </ul> <p>As of v10.0.0, a deprecation warning is printed at runtime when <code>--pending-deprecation</code> is used or when the calling code is outside <code>node_modules</code> in order to better target developers, rather than users.</p> <p><a id="DEP0006"></a></p> <h3>DEP0006: child_process options.customFds<span><a class="mark" href="#deprecations_dep0006_child_process_options_customfds" id="deprecations_dep0006_child_process_options_customfds">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.11.14</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v0.5.11</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>Within the <a href="child_process.html"><code>child_process</code></a> module's <code>spawn()</code>, <code>fork()</code>, and <code>exec()</code> methods, the <code>options.customFds</code> option is deprecated. The <code>options.stdio</code> option should be used instead.</p> <p><a id="DEP0007"></a></p> <h3>DEP0007: Replace cluster worker.suicide with worker.exitedAfterDisconnect<span><a class="mark" href="#deprecations_dep0007_replace_cluster_worker_suicide_with_worker_exitedafterdisconnect" id="deprecations_dep0007_replace_cluster_worker_suicide_with_worker_exitedafterdisconnect">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v7.0.0</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>In an earlier version of the Node.js <code>cluster</code>, a boolean property with the name <code>suicide</code> was added to the <code>Worker</code> object. The intent of this property was to provide an indication of how and why the <code>Worker</code> instance exited. In Node.js 6.0.0, the old property was deprecated and replaced with a new <a href="#cluster_worker_exitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a> property. The old property name did not precisely describe the actual semantics and was unnecessarily emotion-laden.</p> <p><a id="DEP0008"></a></p> <h3>DEP0008: require('constants')<span><a class="mark" href="#deprecations_dep0008_require_constants" id="deprecations_dep0008_require_constants">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v6.3.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <code>constants</code> module is deprecated. When requiring access to constants relevant to specific Node.js builtin modules, developers should instead refer to the <code>constants</code> property exposed by the relevant module. For instance, <code>require('fs').constants</code> and <code>require('os').constants</code>.</p> <p><a id="DEP0009"></a></p> <h3>DEP0009: crypto.pbkdf2 without digest<span><a class="mark" href="#deprecations_dep0009_crypto_pbkdf2_without_digest" id="deprecations_dep0009_crypto_pbkdf2_without_digest">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>Use of the <a href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback"><code>crypto.pbkdf2()</code></a> API without specifying a digest was deprecated in Node.js 6.0 because the method defaulted to using the non-recommended <code>'SHA1'</code> digest. Previously, a deprecation warning was printed. Starting in Node.js 8.0.0, calling <code>crypto.pbkdf2()</code> or <code>crypto.pbkdf2Sync()</code> with an undefined <code>digest</code> will throw a <code>TypeError</code>.</p> <p><a id="DEP0010"></a></p> <h3>DEP0010: crypto.createCredentials<span><a class="mark" href="#deprecations_dep0010_crypto_createcredentials" id="deprecations_dep0010_crypto_createcredentials">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.11.13</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <a href="#crypto_crypto_createcredentials_details"><code>crypto.createCredentials()</code></a> API is deprecated. Please use <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> instead.</p> <p><a id="DEP0011"></a></p> <h3>DEP0011: crypto.Credentials<span><a class="mark" href="#deprecations_dep0011_crypto_credentials" id="deprecations_dep0011_crypto_credentials">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.11.13</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <code>crypto.Credentials</code> class is deprecated. Please use <a href="#tls_tls_createsecurecontext_options"><code>tls.SecureContext</code></a> instead.</p> <p><a id="DEP0012"></a></p> <h3>DEP0012: Domain.dispose<span><a class="mark" href="#deprecations_dep0012_domain_dispose" id="deprecations_dep0012_domain_dispose">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.11.7</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p><code>Domain.dispose()</code> has been removed. Recover from failed I/O actions explicitly via error event handlers set on the domain instead.</p> <p><a id="DEP0013"></a></p> <h3>DEP0013: fs asynchronous function without callback<span><a class="mark" href="#deprecations_dep0013_fs_asynchronous_function_without_callback" id="deprecations_dep0013_fs_asynchronous_function_without_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v7.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>Calling an asynchronous function without a callback throws a <code>TypeError</code> in Node.js 10.0.0 onwards. (See <a href="https://github.com/nodejs/node/pull/12562">https://github.com/nodejs/node/pull/12562</a>.)</p> <p><a id="DEP0014"></a></p> <h3>DEP0014: fs.read legacy String interface<span><a class="mark" href="#deprecations_dep0014_fs_read_legacy_string_interface" id="deprecations_dep0014_fs_read_legacy_string_interface">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.1.96</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>The <a href="#fs_fs_read_fd_buffer_offset_length_position_callback"><code>fs.read()</code></a> legacy <code>String</code> interface is deprecated. Use the <code>Buffer</code> API as mentioned in the documentation instead.</p> <p><a id="DEP0015"></a></p> <h3>DEP0015: fs.readSync legacy String interface<span><a class="mark" href="#deprecations_dep0015_fs_readsync_legacy_string_interface" id="deprecations_dep0015_fs_readsync_legacy_string_interface">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.1.96</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>The <a href="#fs_fs_readsync_fd_buffer_offset_length_position"><code>fs.readSync()</code></a> legacy <code>String</code> interface is deprecated. Use the <code>Buffer</code> API as mentioned in the documentation instead.</p> <p><a id="DEP0016"></a></p> <h3>DEP0016: GLOBAL/root<span><a class="mark" href="#deprecations_dep0016_global_root" id="deprecations_dep0016_global_root">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <code>GLOBAL</code> and <code>root</code> aliases for the <code>global</code> property are deprecated and should no longer be used.</p> <p><a id="DEP0017"></a></p> <h3>DEP0017: Intl.v8BreakIterator<span><a class="mark" href="#deprecations_dep0017_intl_v8breakiterator" id="deprecations_dep0017_intl_v8breakiterator">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v7.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p><code>Intl.v8BreakIterator</code> was a non-standard extension and has been removed. See <a href="https://github.com/tc39/proposal-intl-segmenter"><code>Intl.Segmenter</code></a>.</p> <p><a id="DEP0018"></a></p> <h3>DEP0018: Unhandled promise rejections<span><a class="mark" href="#deprecations_dep0018_unhandled_promise_rejections" id="deprecations_dep0018_unhandled_promise_rejections">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.</p> <p><a id="DEP0019"></a></p> <h3>DEP0019: require('.') resolved outside directory<span><a class="mark" href="#deprecations_dep0019_require_resolved_outside_directory" id="deprecations_dep0019_require_resolved_outside_directory">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v1.8.1</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>In certain cases, <code>require('.')</code> may resolve outside the package directory. This behavior is deprecated and will be removed in a future major Node.js release.</p> <p><a id="DEP0020"></a></p> <h3>DEP0020: Server.connections<span><a class="mark" href="#deprecations_dep0020_server_connections" id="deprecations_dep0020_server_connections">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.9.7</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <a href="#net_server_connections"><code>Server.connections</code></a> property is deprecated. Please use the <a href="#net_server_getconnections_callback"><code>Server.getConnections()</code></a> method instead.</p> <p><a id="DEP0021"></a></p> <h3>DEP0021: Server.listenFD<span><a class="mark" href="#deprecations_dep0021_server_listenfd" id="deprecations_dep0021_server_listenfd">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.7.12</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <code>Server.listenFD()</code> method is deprecated. Please use <a href="#net_server_listen_handle_backlog_callback"><code>Server.listen({fd: <number>})</code></a> instead.</p> <p><a id="DEP0022"></a></p> <h3>DEP0022: os.tmpDir()<span><a class="mark" href="#deprecations_dep0022_os_tmpdir" id="deprecations_dep0022_os_tmpdir">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <code>os.tmpDir()</code> API is deprecated. Please use <a href="#os_os_tmpdir"><code>os.tmpdir()</code></a> instead.</p> <p><a id="DEP0023"></a></p> <h3>DEP0023: os.getNetworkInterfaces()<span><a class="mark" href="#deprecations_dep0023_os_getnetworkinterfaces" id="deprecations_dep0023_os_getnetworkinterfaces">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.6.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <code>os.getNetworkInterfaces()</code> method is deprecated. Please use the <a href="#os_os_networkinterfaces"><code>os.networkInterfaces</code></a> property instead.</p> <p><a id="DEP0024"></a></p> <h3>DEP0024: REPLServer.prototype.convertToContext()<span><a class="mark" href="#deprecations_dep0024_replserver_prototype_converttocontext" id="deprecations_dep0024_replserver_prototype_converttocontext">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v7.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>The <code>REPLServer.prototype.convertToContext()</code> API has been removed.</p> <p><a id="DEP0025"></a></p> <h3>DEP0025: require('sys')<span><a class="mark" href="#deprecations_dep0025_require_sys" id="deprecations_dep0025_require_sys">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v1.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <code>sys</code> module is deprecated. Please use the <a href="util.html"><code>util</code></a> module instead.</p> <p><a id="DEP0026"></a></p> <h3>DEP0026: util.print()<span><a class="mark" href="#deprecations_dep0026_util_print" id="deprecations_dep0026_util_print">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.11.3</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <a href="#util_util_print_strings"><code>util.print()</code></a> API is deprecated. Please use <a href="#console_console_log_data_args"><code>console.log()</code></a> instead.</p> <p><a id="DEP0027"></a></p> <h3>DEP0027: util.puts()<span><a class="mark" href="#deprecations_dep0027_util_puts" id="deprecations_dep0027_util_puts">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.11.3</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <a href="#util_util_puts_strings"><code>util.puts()</code></a> API is deprecated. Please use <a href="#console_console_log_data_args"><code>console.log()</code></a> instead.</p> <p><a id="DEP0028"></a></p> <h3>DEP0028: util.debug()<span><a class="mark" href="#deprecations_dep0028_util_debug" id="deprecations_dep0028_util_debug">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.11.3</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <a href="#util_util_debug_string"><code>util.debug()</code></a> API is deprecated. Please use <a href="#console_console_error_data_args"><code>console.error()</code></a> instead.</p> <p><a id="DEP0029"></a></p> <h3>DEP0029: util.error()<span><a class="mark" href="#deprecations_dep0029_util_error" id="deprecations_dep0029_util_error">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.11.3</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <a href="#util_util_error_strings"><code>util.error()</code></a> API is deprecated. Please use <a href="#console_console_error_data_args"><code>console.error()</code></a> instead.</p> <p><a id="DEP0030"></a></p> <h3>DEP0030: SlowBuffer<span><a class="mark" href="#deprecations_dep0030_slowbuffer" id="deprecations_dep0030_slowbuffer">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#buffer_class_slowbuffer"><code>SlowBuffer</code></a> class is deprecated. Please use <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow(size)</code></a> instead.</p> <p><a id="DEP0031"></a></p> <h3>DEP0031: ecdh.setPublicKey()<span><a class="mark" href="#deprecations_dep0031_ecdh_setpublickey" id="deprecations_dep0031_ecdh_setpublickey">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v5.2.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#crypto_ecdh_setpublickey_publickey_encoding"><code>ecdh.setPublicKey()</code></a> method is now deprecated as its inclusion in the API is not useful.</p> <p><a id="DEP0032"></a></p> <h3>DEP0032: domain module<span><a class="mark" href="#deprecations_dep0032_domain_module" id="deprecations_dep0032_domain_module">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v1.4.2</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="domain.html"><code>domain</code></a> module is deprecated and should not be used.</p> <p><a id="DEP0033"></a></p> <h3>DEP0033: EventEmitter.listenerCount()<span><a class="mark" href="#deprecations_dep0033_eventemitter_listenercount" id="deprecations_dep0033_eventemitter_listenercount">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.2.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#events_eventemitter_listenercount_emitter_eventname"><code>EventEmitter.listenerCount(emitter, eventName)</code></a> API is deprecated. Please use <a href="#events_emitter_listenercount_eventname"><code>emitter.listenerCount(eventName)</code></a> instead.</p> <p><a id="DEP0034"></a></p> <h3>DEP0034: fs.exists(path, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L195">[src]</a><span><a class="mark" href="#deprecations_dep0034_fs_exists_path_callback" id="deprecations_dep0034_fs_exists_path_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v1.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#fs_fs_exists_path_callback"><code>fs.exists(path, callback)</code></a> API is deprecated. Please use <a href="#fs_fs_stat_path_options_callback"><code>fs.stat()</code></a> or <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a> instead.</p> <p><a id="DEP0035"></a></p> <h3>DEP0035: fs.lchmod(path, mode, callback)<span><a class="mark" href="#deprecations_dep0035_fs_lchmod_path_mode_callback" id="deprecations_dep0035_fs_lchmod_path_mode_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.4.7</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#fs_fs_lchmod_path_mode_callback"><code>fs.lchmod(path, mode, callback)</code></a> API is deprecated.</p> <p><a id="DEP0036"></a></p> <h3>DEP0036: fs.lchmodSync(path, mode)<span><a class="mark" href="#deprecations_dep0036_fs_lchmodsync_path_mode" id="deprecations_dep0036_fs_lchmodsync_path_mode">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.4.7</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#fs_fs_lchmodsync_path_mode"><code>fs.lchmodSync(path, mode)</code></a> API is deprecated.</p> <p><a id="DEP0037"></a></p> <h3>DEP0037: fs.lchown(path, uid, gid, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1030">[src]</a><span><a class="mark" href="#deprecations_dep0037_fs_lchown_path_uid_gid_callback" id="deprecations_dep0037_fs_lchown_path_uid_gid_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.6.0</td> <td><p>Deprecation revoked.</p></td></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.4.7</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Deprecation revoked</p> <p>The <a href="#fs_fs_lchown_path_uid_gid_callback"><code>fs.lchown(path, uid, gid, callback)</code></a> API is deprecated.</p> <p><a id="DEP0038"></a></p> <h3>DEP0038: fs.lchownSync(path, uid, gid)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1041">[src]</a><span><a class="mark" href="#deprecations_dep0038_fs_lchownsync_path_uid_gid" id="deprecations_dep0038_fs_lchownsync_path_uid_gid">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.6.0</td> <td><p>Deprecation revoked.</p></td></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.4.7</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Deprecation revoked</p> <p>The <a href="#fs_fs_lchownsync_path_uid_gid"><code>fs.lchownSync(path, uid, gid)</code></a> API is deprecated.</p> <p><a id="DEP0039"></a></p> <h3>DEP0039: require.extensions<span><a class="mark" href="#deprecations_dep0039_require_extensions" id="deprecations_dep0039_require_extensions">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.10.6</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#modules_require_extensions"><code>require.extensions</code></a> property is deprecated.</p> <p><a id="DEP0040"></a></p> <h3>DEP0040: punycode module<span><a class="mark" href="#deprecations_dep0040_punycode_module" id="deprecations_dep0040_punycode_module">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="punycode.html"><code>punycode</code></a> module is deprecated. Please use a userland alternative instead.</p> <p><a id="DEP0041"></a></p> <h3>DEP0041: NODE_REPL_HISTORY_FILE environment variable<span><a class="mark" href="#deprecations_dep0041_node_repl_history_file_environment_variable" id="deprecations_dep0041_node_repl_history_file_environment_variable">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>The <code>NODE_REPL_HISTORY_FILE</code> environment variable was removed. Please use <code>NODE_REPL_HISTORY</code> instead.</p> <p><a id="DEP0042"></a></p> <h3>DEP0042: tls.CryptoStream<span><a class="mark" href="#deprecations_dep0042_tls_cryptostream" id="deprecations_dep0042_tls_cryptostream">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v0.11.3</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>The <a href="#tls_class_cryptostream"><code>tls.CryptoStream</code></a> class was removed. Please use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</p> <p><a id="DEP0043"></a></p> <h3>DEP0043: tls.SecurePair<span><a class="mark" href="#deprecations_dep0043_tls_securepair" id="deprecations_dep0043_tls_securepair">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> <tr><td>v0.11.15</td> <td><p>Deprecation revoked.</p></td></tr> <tr><td>v0.11.3</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#tls_class_securepair"><code>tls.SecurePair</code></a> class is deprecated. Please use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</p> <p><a id="DEP0044"></a></p> <h3>DEP0044: util.isArray()<span><a class="mark" href="#deprecations_dep0044_util_isarray" id="deprecations_dep0044_util_isarray">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isarray_object"><code>util.isArray()</code></a> API is deprecated. Please use <code>Array.isArray()</code> instead.</p> <p><a id="DEP0045"></a></p> <h3>DEP0045: util.isBoolean()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L197">[src]</a><span><a class="mark" href="#deprecations_dep0045_util_isboolean" id="deprecations_dep0045_util_isboolean">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isboolean_object"><code>util.isBoolean()</code></a> API is deprecated.</p> <p><a id="DEP0046"></a></p> <h3>DEP0046: util.isBuffer()<span><a class="mark" href="#deprecations_dep0046_util_isbuffer" id="deprecations_dep0046_util_isbuffer">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isbuffer_object"><code>util.isBuffer()</code></a> API is deprecated. Please use <a href="#buffer_class_method_buffer_isbuffer_obj"><code>Buffer.isBuffer()</code></a> instead.</p> <p><a id="DEP0047"></a></p> <h3>DEP0047: util.isDate()<span><a class="mark" href="#deprecations_dep0047_util_isdate" id="deprecations_dep0047_util_isdate">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isdate_object"><code>util.isDate()</code></a> API is deprecated.</p> <p><a id="DEP0048"></a></p> <h3>DEP0048: util.isError()<span><a class="mark" href="#deprecations_dep0048_util_iserror" id="deprecations_dep0048_util_iserror">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_iserror_object"><code>util.isError()</code></a> API is deprecated.</p> <p><a id="DEP0049"></a></p> <h3>DEP0049: util.isFunction()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L229">[src]</a><span><a class="mark" href="#deprecations_dep0049_util_isfunction" id="deprecations_dep0049_util_isfunction">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isfunction_object"><code>util.isFunction()</code></a> API is deprecated.</p> <p><a id="DEP0050"></a></p> <h3>DEP0050: util.isNull()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L201">[src]</a><span><a class="mark" href="#deprecations_dep0050_util_isnull" id="deprecations_dep0050_util_isnull">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isnull_object"><code>util.isNull()</code></a> API is deprecated.</p> <p><a id="DEP0051"></a></p> <h3>DEP0051: util.isNullOrUndefined()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L205">[src]</a><span><a class="mark" href="#deprecations_dep0051_util_isnullorundefined" id="deprecations_dep0051_util_isnullorundefined">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isnullorundefined_object"><code>util.isNullOrUndefined()</code></a> API is deprecated.</p> <p><a id="DEP0052"></a></p> <h3>DEP0052: util.isNumber()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L209">[src]</a><span><a class="mark" href="#deprecations_dep0052_util_isnumber" id="deprecations_dep0052_util_isnumber">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isnumber_object"><code>util.isNumber()</code></a> API is deprecated.</p> <p><a id="DEP0053"></a></p> <h3>DEP0053 util.isObject()<span><a class="mark" href="#deprecations_dep0053_util_isobject" id="deprecations_dep0053_util_isobject">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isobject_object"><code>util.isObject()</code></a> API is deprecated.</p> <p><a id="DEP0054"></a></p> <h3>DEP0054: util.isPrimitive()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L233">[src]</a><span><a class="mark" href="#deprecations_dep0054_util_isprimitive" id="deprecations_dep0054_util_isprimitive">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isprimitive_object"><code>util.isPrimitive()</code></a> API is deprecated.</p> <p><a id="DEP0055"></a></p> <h3>DEP0055: util.isRegExp()<span><a class="mark" href="#deprecations_dep0055_util_isregexp" id="deprecations_dep0055_util_isregexp">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isregexp_object"><code>util.isRegExp()</code></a> API is deprecated.</p> <p><a id="DEP0056"></a></p> <h3>DEP0056: util.isString()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L213">[src]</a><span><a class="mark" href="#deprecations_dep0056_util_isstring" id="deprecations_dep0056_util_isstring">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isstring_object"><code>util.isString()</code></a> API is deprecated.</p> <p><a id="DEP0057"></a></p> <h3>DEP0057: util.isSymbol()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L217">[src]</a><span><a class="mark" href="#deprecations_dep0057_util_issymbol" id="deprecations_dep0057_util_issymbol">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_issymbol_object"><code>util.isSymbol()</code></a> API is deprecated.</p> <p><a id="DEP0058"></a></p> <h3>DEP0058: util.isUndefined()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L221">[src]</a><span><a class="mark" href="#deprecations_dep0058_util_isundefined" id="deprecations_dep0058_util_isundefined">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.8.6, v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v3.3.1, v4.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_isundefined_object"><code>util.isUndefined()</code></a> API is deprecated.</p> <p><a id="DEP0059"></a></p> <h3>DEP0059: util.log()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L255">[src]</a><span><a class="mark" href="#deprecations_dep0059_util_log" id="deprecations_dep0059_util_log">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_log_string"><code>util.log()</code></a> API is deprecated.</p> <p><a id="DEP0060"></a></p> <h3>DEP0060: util._extend()<span><a class="mark" href="#deprecations_dep0060_util_extend" id="deprecations_dep0060_util_extend">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#util_util_extend_target_source"><code>util._extend()</code></a> API is deprecated.</p> <p><a id="DEP0061"></a></p> <h3>DEP0061: fs.SyncWriteStream<span><a class="mark" href="#deprecations_dep0061_fs_syncwritestream" id="deprecations_dep0061_fs_syncwritestream">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v7.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <code>fs.SyncWriteStream</code> class was never intended to be a publicly accessible API. No alternative API is available. Please use a userland alternative.</p> <p><a id="DEP0062"></a></p> <h3>DEP0062: node --debug<span><a class="mark" href="#deprecations_dep0062_node_debug" id="deprecations_dep0062_node_debug">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>--debug</code> activates the legacy V8 debugger interface, which was removed as of V8 5.8. It is replaced by Inspector which is activated with <code>--inspect</code> instead.</p> <p><a id="DEP0063"></a></p> <h3>DEP0063: ServerResponse.prototype.writeHeader()<span><a class="mark" href="#deprecations_dep0063_serverresponse_prototype_writeheader" id="deprecations_dep0063_serverresponse_prototype_writeheader">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <code>http</code> module <code>ServerResponse.prototype.writeHeader()</code> API is deprecated. Please use <code>ServerResponse.prototype.writeHead()</code> instead.</p> <p>The <code>ServerResponse.prototype.writeHeader()</code> method was never documented as an officially supported API.</p> <p><a id="DEP0064"></a></p> <h3>DEP0064: tls.createSecurePair()<span><a class="mark" href="#deprecations_dep0064_tls_createsecurepair" id="deprecations_dep0064_tls_createsecurepair">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v6.12.0</td> <td><p>A deprecation code has been assigned.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> <tr><td>v0.11.15</td> <td><p>Deprecation revoked.</p></td></tr> <tr><td>v0.11.3</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <code>tls.createSecurePair()</code> API was deprecated in documentation in Node.js 0.11.3. Users should use <code>tls.Socket</code> instead.</p> <p><a id="DEP0065"></a></p> <h3>DEP0065: repl.REPL_MODE_MAGIC and NODE_REPL_MODE=magic<span><a class="mark" href="#deprecations_dep0065_repl_repl_mode_magic_and_node_repl_mode_magic" id="deprecations_dep0065_repl_repl_mode_magic_and_node_repl_mode_magic">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v8.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>The <code>repl</code> module's <code>REPL_MODE_MAGIC</code> constant, used for <code>replMode</code> option, has been removed. Its behavior has been functionally identical to that of <code>REPL_MODE_SLOPPY</code> since Node.js 6.0.0, when V8 5.0 was imported. Please use <code>REPL_MODE_SLOPPY</code> instead.</p> <p>The <code>NODE_REPL_MODE</code> environment variable is used to set the underlying <code>replMode</code> of an interactive <code>node</code> session. Its value, <code>magic</code>, is also removed. Please use <code>sloppy</code> instead.</p> <p><a id="DEP0066"></a></p> <h3>DEP0066: outgoingMessage._headers, outgoingMessage._headerNames<span><a class="mark" href="#deprecations_dep0066_outgoingmessage_headers_outgoingmessage_headernames" id="deprecations_dep0066_outgoingmessage_headers_outgoingmessage_headernames">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <code>http</code> module <code>outgoingMessage._headers</code> and <code>outgoingMessage._headerNames</code> properties are deprecated. Use one of the public methods (e.g. <code>outgoingMessage.getHeader()</code>, <code>outgoingMessage.getHeaders()</code>, <code>outgoingMessage.getHeaderNames()</code>, <code>outgoingMessage.hasHeader()</code>, <code>outgoingMessage.removeHeader()</code>, <code>outgoingMessage.setHeader()</code>) for working with outgoing headers.</p> <p>The <code>outgoingMessage._headers</code> and <code>outgoingMessage._headerNames</code> properties were never documented as officially supported properties.</p> <p><a id="DEP0067"></a></p> <h3>DEP0067: OutgoingMessage.prototype._renderHeaders<span><a class="mark" href="#deprecations_dep0067_outgoingmessage_prototype_renderheaders" id="deprecations_dep0067_outgoingmessage_prototype_renderheaders">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <code>http</code> module <code>OutgoingMessage.prototype._renderHeaders()</code> API is deprecated.</p> <p>The <code>OutgoingMessage.prototype._renderHeaders</code> property was never documented as an officially supported API.</p> <p><a id="DEP0068"></a></p> <h3>DEP0068: node debug<span><a class="mark" href="#deprecations_dep0068_node_debug" id="deprecations_dep0068_node_debug">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>node debug</code> corresponds to the legacy CLI debugger which has been replaced with a V8-inspector based CLI debugger available through <code>node inspect</code>.</p> <p><a id="DEP0069"></a></p> <h3>DEP0069: vm.runInDebugContext(string)<span><a class="mark" href="#deprecations_dep0069_vm_runindebugcontext_string" id="deprecations_dep0069_vm_runindebugcontext_string">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v9.0.0</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v8.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>DebugContext has been removed in V8 and is not available in Node.js 10+.</p> <p>DebugContext was an experimental API.</p> <p><a id="DEP0070"></a></p> <h3>DEP0070: async_hooks.currentId()<span><a class="mark" href="#deprecations_dep0070_async_hooks_currentid" id="deprecations_dep0070_async_hooks_currentid">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v8.2.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p><code>async_hooks.currentId()</code> was renamed to <code>async_hooks.executionAsyncId()</code> for clarity.</p> <p>This change was made while <code>async_hooks</code> was an experimental API.</p> <p><a id="DEP0071"></a></p> <h3>DEP0071: async_hooks.triggerId()<span><a class="mark" href="#deprecations_dep0071_async_hooks_triggerid" id="deprecations_dep0071_async_hooks_triggerid">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v8.2.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p><code>async_hooks.triggerId()</code> was renamed to <code>async_hooks.triggerAsyncId()</code> for clarity.</p> <p>This change was made while <code>async_hooks</code> was an experimental API.</p> <p><a id="DEP0072"></a></p> <h3>DEP0072: async_hooks.AsyncResource.triggerId()<span><a class="mark" href="#deprecations_dep0072_async_hooks_asyncresource_triggerid" id="deprecations_dep0072_async_hooks_asyncresource_triggerid">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v8.2.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p><code>async_hooks.AsyncResource.triggerId()</code> was renamed to <code>async_hooks.AsyncResource.triggerAsyncId()</code> for clarity.</p> <p>This change was made while <code>async_hooks</code> was an experimental API.</p> <p><a id="DEP0073"></a></p> <h3>DEP0073: Several internal properties of net.Server<span><a class="mark" href="#deprecations_dep0073_several_internal_properties_of_net_server" id="deprecations_dep0073_several_internal_properties_of_net_server">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v9.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>Accessing several internal, undocumented properties of <code>net.Server</code> instances with inappropriate names is deprecated.</p> <p>As the original API was undocumented and not generally useful for non-internal code, no replacement API is provided.</p> <p><a id="DEP0074"></a></p> <h3>DEP0074: REPLServer.bufferedCommand<span><a class="mark" href="#deprecations_dep0074_replserver_bufferedcommand" id="deprecations_dep0074_replserver_bufferedcommand">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <code>REPLServer.bufferedCommand</code> property was deprecated in favor of <a href="#repl_replserver_clearbufferedcommand"><code>REPLServer.clearBufferedCommand()</code></a>.</p> <p><a id="DEP0075"></a></p> <h3>DEP0075: REPLServer.parseREPLKeyword()<span><a class="mark" href="#deprecations_dep0075_replserver_parsereplkeyword" id="deprecations_dep0075_replserver_parsereplkeyword">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>REPLServer.parseREPLKeyword()</code> was removed from userland visibility.</p> <p><a id="DEP0076"></a></p> <h3>DEP0076: tls.parseCertString()<span><a class="mark" href="#deprecations_dep0076_tls_parsecertstring" id="deprecations_dep0076_tls_parsecertstring">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v8.6.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>tls.parseCertString()</code> is a trivial parsing helper that was made public by mistake. This function can usually be replaced with:</p> <pre><code class="language-js">const querystring = require('querystring'); querystring.parse(str, '\n', '='); </code></pre> <p>This function is not completely equivalent to <code>querystring.parse()</code>. One difference is that <code>querystring.parse()</code> does url decoding:</p> <pre><code class="language-sh">> querystring.parse('%E5%A5%BD=1', '\n', '='); { '好': '1' } > tls.parseCertString('%E5%A5%BD=1'); { '%E5%A5%BD': '1' } </code></pre> <p><a id="DEP0077"></a></p> <h3>DEP0077: Module._debug()<span><a class="mark" href="#deprecations_dep0077_module_debug" id="deprecations_dep0077_module_debug">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>Module._debug()</code> is deprecated.</p> <p>The <code>Module._debug()</code> function was never documented as an officially supported API.</p> <p><a id="DEP0078"></a></p> <h3>DEP0078: REPLServer.turnOffEditorMode()<span><a class="mark" href="#deprecations_dep0078_replserver_turnoffeditormode" id="deprecations_dep0078_replserver_turnoffeditormode">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>REPLServer.turnOffEditorMode()</code> was removed from userland visibility.</p> <p><a id="DEP0079"></a></p> <h3>DEP0079: Custom inspection function on Objects via .inspect()<span><a class="mark" href="#deprecations_dep0079_custom_inspection_function_on_objects_via_inspect" id="deprecations_dep0079_custom_inspection_function_on_objects_via_inspect">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v8.7.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>Using a property named <code>inspect</code> on an object to specify a custom inspection function for <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> is deprecated. Use <a href="#util_util_inspect_custom"><code>util.inspect.custom</code></a> instead. For backward compatibility with Node.js prior to version 6.4.0, both may be specified.</p> <p><a id="DEP0080"></a></p> <h3>DEP0080: path._makeLong()<span><a class="mark" href="#deprecations_dep0080_path_makelong" id="deprecations_dep0080_path_makelong">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The internal <code>path._makeLong()</code> was not intended for public use. However, userland modules have found it useful. The internal API is deprecated and replaced with an identical, public <code>path.toNamespacedPath()</code> method.</p> <p><a id="DEP0081"></a></p> <h3>DEP0081: fs.truncate() using a file descriptor<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L601">[src]</a><span><a class="mark" href="#deprecations_dep0081_fs_truncate_using_a_file_descriptor" id="deprecations_dep0081_fs_truncate_using_a_file_descriptor">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>fs.truncate()</code> <code>fs.truncateSync()</code> usage with a file descriptor is deprecated. Please use <code>fs.ftruncate()</code> or <code>fs.ftruncateSync()</code> to work with file descriptors.</p> <p><a id="DEP0082"></a></p> <h3>DEP0082: REPLServer.prototype.memory()<span><a class="mark" href="#deprecations_dep0082_replserver_prototype_memory" id="deprecations_dep0082_replserver_prototype_memory">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>REPLServer.prototype.memory()</code> is only necessary for the internal mechanics of the <code>REPLServer</code> itself. Do not use this function.</p> <p><a id="DEP0083"></a></p> <h3>DEP0083: Disabling ECDH by setting ecdhCurve to false<span><a class="mark" href="#deprecations_dep0083_disabling_ecdh_by_setting_ecdhcurve_to_false" id="deprecations_dep0083_disabling_ecdh_by_setting_ecdhcurve_to_false">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v9.2.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life.</p> <p>The <code>ecdhCurve</code> option to <code>tls.createSecureContext()</code> and <code>tls.TLSSocket</code> could be set to <code>false</code> to disable ECDH entirely on the server only. This mode was deprecated in preparation for migrating to OpenSSL 1.1.0 and consistency with the client and is now unsupported. Use the <code>ciphers</code> parameter instead.</p> <p><a id="DEP0084"></a></p> <h3>DEP0084: requiring bundled internal dependencies<span><a class="mark" href="#deprecations_dep0084_requiring_bundled_internal_dependencies" id="deprecations_dep0084_requiring_bundled_internal_dependencies">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>Since Node.js versions 4.4.0 and 5.2.0, several modules only intended for internal usage are mistakenly exposed to user code through <code>require()</code>. These modules are:</p> <ul> <li><code>v8/tools/codemap</code></li> <li><code>v8/tools/consarray</code></li> <li><code>v8/tools/csvparser</code></li> <li><code>v8/tools/logreader</code></li> <li><code>v8/tools/profile_view</code></li> <li><code>v8/tools/profile</code></li> <li><code>v8/tools/SourceMap</code></li> <li><code>v8/tools/splaytree</code></li> <li><code>v8/tools/tickprocessor-driver</code></li> <li><code>v8/tools/tickprocessor</code></li> <li><code>node-inspect/lib/_inspect</code> (from 7.6.0)</li> <li><code>node-inspect/lib/internal/inspect_client</code> (from 7.6.0)</li> <li><code>node-inspect/lib/internal/inspect_repl</code> (from 7.6.0)</li> </ul> <p>The <code>v8/*</code> modules do not have any exports, and if not imported in a specific order would in fact throw errors. As such there are virtually no legitimate use cases for importing them through <code>require()</code>.</p> <p>On the other hand, <code>node-inspect</code> may be installed locally through a package manager, as it is published on the npm registry under the same name. No source code modification is necessary if that is done.</p> <p><a id="DEP0085"></a></p> <h3>DEP0085: AsyncHooks Sensitive API<span><a class="mark" href="#deprecations_dep0085_asynchooks_sensitive_api" id="deprecations_dep0085_asynchooks_sensitive_api">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>10.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v8.10.0, v9.4.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>The AsyncHooks Sensitive API was never documented and had various minor issues. (See <a href="https://github.com/nodejs/node/issues/15572">https://github.com/nodejs/node/issues/15572</a>.) Use the <code>AsyncResource</code> API instead.</p> <p><a id="DEP0086"></a></p> <h3>DEP0086: Remove runInAsyncIdScope<span><a class="mark" href="#deprecations_dep0086_remove_runinasyncidscope" id="deprecations_dep0086_remove_runinasyncidscope">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>10.0.0</td> <td><p>End-of-Life.</p></td></tr> <tr><td>v8.10.0, v9.4.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p><code>runInAsyncIdScope</code> doesn't emit the <code>'before'</code> or <code>'after'</code> event and can thus cause a lot of issues. See <a href="https://github.com/nodejs/node/issues/14328">https://github.com/nodejs/node/issues/14328</a> for more details.</p> <p><a id="DEP0089"></a></p> <h3>DEP0089: require('assert')<span><a class="mark" href="#deprecations_dep0089_require_assert" id="deprecations_dep0089_require_assert">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.9.0, v10.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>Importing assert directly is not recommended as the exposed functions will use loose equality checks. Use <code>require('assert').strict</code> instead. The API is the same as the legacy assert but it will always use strict equality checks.</p> <p><a id="DEP0090"></a></p> <h3>DEP0090: Invalid GCM authentication tag lengths<span><a class="mark" href="#deprecations_dep0090_invalid_gcm_authentication_tag_lengths" id="deprecations_dep0090_invalid_gcm_authentication_tag_lengths">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>Node.js supports all GCM authentication tag lengths which are accepted by OpenSSL when calling <a href="#crypto_decipher_setauthtag_buffer"><code>decipher.setAuthTag()</code></a>. This behavior will change in a future version at which point only authentication tag lengths of 128, 120, 112, 104, 96, 64, and 32 bits will be allowed. Authentication tags whose length is not included in this list will be considered invalid in compliance with <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf">NIST SP 800-38D</a>.</p> <p><a id="DEP0091"></a></p> <h3>DEP0091: crypto.DEFAULT_ENCODING<span><a class="mark" href="#deprecations_dep0091_crypto_default_encoding" id="deprecations_dep0091_crypto_default_encoding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The <a href="#crypto_crypto_default_encoding"><code>crypto.DEFAULT_ENCODING</code></a> property is deprecated.</p> <p><a id="DEP0092"></a></p> <h3>DEP0092: Top-level <code>this</code> bound to <code>module.exports</code><span><a class="mark" href="#deprecations_dep0092_top_level_this_bound_to_module_exports" id="deprecations_dep0092_top_level_this_bound_to_module_exports">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>Assigning properties to the top-level <code>this</code> as an alternative to <code>module.exports</code> is deprecated. Developers should use <code>exports</code> or <code>module.exports</code> instead.</p> <p><a id="DEP0093"></a></p> <h3>DEP0093: crypto.fips is deprecated and replaced.<span><a class="mark" href="#deprecations_dep0093_crypto_fips_is_deprecated_and_replaced" id="deprecations_dep0093_crypto_fips_is_deprecated_and_replaced">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <a href="#crypto_crypto_fips"><code>crypto.fips</code></a> property is deprecated. Please use <code>crypto.setFips()</code> and <code>crypto.getFips()</code> instead.</p> <p><a id="DEP0094"></a></p> <h3>DEP0094: Using <code>assert.fail()</code> with more than one argument.<span><a class="mark" href="#deprecations_dep0094_using_assert_fail_with_more_than_one_argument" id="deprecations_dep0094_using_assert_fail_with_more_than_one_argument">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>Using <code>assert.fail()</code> with more than one argument is deprecated. Use <code>assert.fail()</code> with only one argument or use a different <code>assert</code> module method.</p> <p><a id="DEP0095"></a></p> <h3>DEP0095: timers.enroll()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/timers.js#L366">[src]</a><span><a class="mark" href="#deprecations_dep0095_timers_enroll" id="deprecations_dep0095_timers_enroll">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>timers.enroll()</code> is deprecated. Please use the publicly documented <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a> or <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a> instead.</p> <p><a id="DEP0096"></a></p> <h3>DEP0096: timers.unenroll()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/timers.js#L339">[src]</a><span><a class="mark" href="#deprecations_dep0096_timers_unenroll" id="deprecations_dep0096_timers_unenroll">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>timers.unenroll()</code> is deprecated. Please use the publicly documented <a href="#timers_cleartimeout_timeout"><code>clearTimeout()</code></a> or <a href="#timers_clearinterval_timeout"><code>clearInterval()</code></a> instead.</p> <p><a id="DEP0097"></a></p> <h3>DEP0097: MakeCallback with domain property<span><a class="mark" href="#deprecations_dep0097_makecallback_with_domain_property" id="deprecations_dep0097_makecallback_with_domain_property">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>Users of <code>MakeCallback</code> that add the <code>domain</code> property to carry context, should start using the <code>async_context</code> variant of <code>MakeCallback</code> or <code>CallbackScope</code>, or the high-level <code>AsyncResource</code> class.</p> <p><a id="DEP0098"></a></p> <h3>DEP0098: AsyncHooks Embedder AsyncResource.emitBefore and AsyncResource.emitAfter APIs<span><a class="mark" href="#deprecations_dep0098_asynchooks_embedder_asyncresource_emitbefore_and_asyncresource_emitafter_apis" id="deprecations_dep0098_asynchooks_embedder_asyncresource_emitbefore_and_asyncresource_emitafter_apis">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.12.0, v9.6.0, v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>The embedded API provided by AsyncHooks exposes <code>.emitBefore()</code> and <code>.emitAfter()</code> methods which are very easy to use incorrectly which can lead to unrecoverable errors.</p> <p>Use <a href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args"><code>asyncResource.runInAsyncScope()</code></a> API instead which provides a much safer, and more convenient, alternative. See <a href="https://github.com/nodejs/node/pull/18513">https://github.com/nodejs/node/pull/18513</a> for more details.</p> <p><a id="DEP0099"></a></p> <h3>DEP0099: async context-unaware node::MakeCallback C++ APIs<span><a class="mark" href="#deprecations_dep0099_async_context_unaware_node_makecallback_c_apis" id="deprecations_dep0099_async_context_unaware_node_makecallback_c_apis">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Compile-time deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Compile-time</p> <p>Certain versions of <code>node::MakeCallback</code> APIs available to native modules are deprecated. Please use the versions of the API that accept an <code>async_context</code> parameter.</p> <p><a id="DEP0100"></a></p> <h3>DEP0100: process.assert()<span><a class="mark" href="#deprecations_dep0100_process_assert" id="deprecations_dep0100_process_assert">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> <tr><td>v0.3.7</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>process.assert()</code> is deprecated. Please use the <a href="assert.html"><code>assert</code></a> module instead.</p> <p>This was never a documented feature.</p> <p><a id="DEP0101"></a></p> <h3>DEP0101: --with-lttng<span><a class="mark" href="#deprecations_dep0101_with_lttng" id="deprecations_dep0101_with_lttng">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>End-of-Life.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>The <code>--with-lttng</code> compile-time option has been removed.</p> <p><a id="DEP0102"></a></p> <h3>DEP0102: Using <code>noAssert</code> in Buffer#(read|write) operations.<span><a class="mark" href="#deprecations_dep0102_using_noassert_in_buffer_read_write_operations" id="deprecations_dep0102_using_noassert_in_buffer_read_write_operations">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>End-of-Life.</p></td></tr> </tbody></table> </details> </div> <p>Type: End-of-Life</p> <p>Using the <code>noAssert</code> argument has no functionality anymore. All input is going to be verified, no matter if it is set to true or not. Skipping the verification could lead to hard to find errors and crashes.</p> <p><a id="DEP0103"></a></p> <h3>DEP0103: process.binding('util').is[...] typechecks<span><a class="mark" href="#deprecations_dep0103_process_binding_util_is_typechecks" id="deprecations_dep0103_process_binding_util_is_typechecks">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.9.0</td> <td><p>Superseded by <a href="#DEP0111">DEP0111</a>.</p></td></tr> <tr><td>v10.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only (supports <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a>)</p> <p>Using <code>process.binding()</code> in general should be avoided. The type checking methods in particular can be replaced by using <a href="#util_util_types"><code>util.types</code></a>.</p> <p>This deprecation has been superseded by the deprecation of the <code>process.binding()</code> API (<a href="#DEP0111">DEP0111</a>).</p> <p><a id="DEP0104"></a></p> <h3>DEP0104: process.env string coercion<span><a class="mark" href="#deprecations_dep0104_process_env_string_coercion" id="deprecations_dep0104_process_env_string_coercion">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only (supports <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a>)</p> <p>When assigning a non-string property to <a href="#process_process_env"><code>process.env</code></a>, the assigned value is implicitly converted to a string. This behavior is deprecated if the assigned value is not a string, boolean, or number. In the future, such assignment may result in a thrown error. Please convert the property to a string before assigning it to <code>process.env</code>.</p> <p><a id="DEP0105"></a></p> <h3>DEP0105: decipher.finaltol<span><a class="mark" href="#deprecations_dep0105_decipher_finaltol" id="deprecations_dep0105_decipher_finaltol">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p><code>decipher.finaltol()</code> has never been documented and is currently an alias for <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a>. In the future, this API will likely be removed, and it is recommended to use <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> instead.</p> <p><a id="DEP0106"></a></p> <h3>DEP0106: crypto.createCipher and crypto.createDecipher<span><a class="mark" href="#deprecations_dep0106_crypto_createcipher_and_crypto_createdecipher" id="deprecations_dep0106_crypto_createcipher_and_crypto_createdecipher">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>Using <a href="#crypto_crypto_createcipher_algorithm_password_options"><code>crypto.createCipher()</code></a> and <a href="#crypto_crypto_createdecipher_algorithm_password_options"><code>crypto.createDecipher()</code></a> should be avoided as they use a weak key derivation function (MD5 with no salt) and static initialization vectors. It is recommended to derive a key using <a href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback"><code>crypto.pbkdf2()</code></a> or <a href="#crypto_crypto_scrypt_password_salt_keylen_options_callback"><code>crypto.scrypt()</code></a> and to use <a href="#crypto_crypto_createcipheriv_algorithm_key_iv_options"><code>crypto.createCipheriv()</code></a> and <a href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options"><code>crypto.createDecipheriv()</code></a> to obtain the <a href="#crypto_class_cipher"><code>Cipher</code></a> and <a href="#crypto_class_decipher"><code>Decipher</code></a> objects respectively.</p> <p><a id="DEP0107"></a></p> <h3>DEP0107: tls.convertNPNProtocols()<span><a class="mark" href="#deprecations_dep0107_tls_convertnpnprotocols" id="deprecations_dep0107_tls_convertnpnprotocols">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Runtime deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Runtime</p> <p>This was an undocumented helper function not intended for use outside Node.js core and obsoleted by the removal of NPN (Next Protocol Negotiation) support.</p> <p><a id="DEP0108"></a></p> <h3>DEP0108: zlib.bytesRead<span><a class="mark" href="#deprecations_dep0108_zlib_bytesread" id="deprecations_dep0108_zlib_bytesread">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>Deprecated alias for <a href="#zlib_zlib_byteswritten"><code>zlib.bytesWritten</code></a>. This original name was chosen because it also made sense to interpret the value as the number of bytes read by the engine, but is inconsistent with other streams in Node.js that expose values under these names.</p> <p><a id="DEP0110"></a></p> <h3>DEP0110: vm.Script cached data<span><a class="mark" href="#deprecations_dep0110_vm_script_cached_data" id="deprecations_dep0110_vm_script_cached_data">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.6.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p>The <code>produceCachedData</code> option is deprecated. Use <a href="#vm_script_createcacheddata"><code>script.createCachedData()</code></a> instead.</p> <p><a id="DEP0111"></a></p> <h3>DEP0111: process.binding()<span><a class="mark" href="#deprecations_dep0111_process_binding" id="deprecations_dep0111_process_binding">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.9.0</td> <td><p>Documentation-only deprecation.</p></td></tr> </tbody></table> </details> </div> <p>Type: Documentation-only</p> <p><code>process.binding()</code> is for use by Node.js internal code only.</p> <h1>DNS<span><a class="mark" href="#dns_dns" id="dns_dns">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>dns</code> module contains functions belonging to two different categories:</p> <p>1) Functions that use the underlying operating system facilities to perform name resolution, and that do not necessarily perform any network communication. This category contains only one function: <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>. <strong>Developers looking to perform name resolution in the same way that other applications on the same operating system behave should use <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</strong></p> <p>For example, looking up <code>iana.org</code>.</p> <pre><code class="language-js">const dns = require('dns'); dns.lookup('iana.org', (err, address, family) => { console.log('address: %j family: IPv%s', address, family); }); // address: "192.0.43.8" family: IPv4 </code></pre> <p>2) Functions that connect to an actual DNS server to perform name resolution, and that <em>always</em> use the network to perform DNS queries. This category contains all functions in the <code>dns</code> module <em>except</em> <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>. These functions do not use the same set of configuration files used by <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> (e.g. <code>/etc/hosts</code>). These functions should be used by developers who do not want to use the underlying operating system's facilities for name resolution, and instead want to <em>always</em> perform DNS queries.</p> <p>Below is an example that resolves <code>'archive.org'</code> then reverse resolves the IP addresses that are returned.</p> <pre><code class="language-js">const dns = require('dns'); dns.resolve4('archive.org', (err, addresses) => { if (err) throw err; console.log(`addresses: ${JSON.stringify(addresses)}`); addresses.forEach((a) => { dns.reverse(a, (err, hostnames) => { if (err) { throw err; } console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); }); }); }); </code></pre> <p>There are subtle consequences in choosing one over the other, please consult the <a href="#dns_implementation_considerations">Implementation considerations section</a> for more information.</p> <h2>Class: <code>dns.Resolver</code><span><a class="mark" href="#dns_class_dns_resolver" id="dns_class_dns_resolver">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.3.0</span> </div> <p>An independent resolver for DNS requests.</p> <p>Note that creating a new resolver uses the default server settings. Setting the servers used for a resolver using <a href="#dns_dns_setservers_servers"><code>resolver.setServers()</code></a> does not affect other resolvers:</p> <pre><code class="language-js">const { Resolver } = require('dns'); const resolver = new Resolver(); resolver.setServers(['4.4.4.4']); // This request will use the server at 4.4.4.4, independent of global settings. resolver.resolve4('example.org', (err, addresses) => { // ... }); </code></pre> <p>The following methods from the <code>dns</code> module are available:</p> <ul> <li><a href="#dns_dns_getservers"><code>resolver.getServers()</code></a></li> <li><a href="#dns_dns_resolve_hostname_rrtype_callback"><code>resolver.resolve()</code></a></li> <li><a href="#dns_dns_resolve4_hostname_options_callback"><code>resolver.resolve4()</code></a></li> <li><a href="#dns_dns_resolve6_hostname_options_callback"><code>resolver.resolve6()</code></a></li> <li><a href="#dns_dns_resolveany_hostname_callback"><code>resolver.resolveAny()</code></a></li> <li><a href="#dns_dns_resolvecname_hostname_callback"><code>resolver.resolveCname()</code></a></li> <li><a href="#dns_dns_resolvemx_hostname_callback"><code>resolver.resolveMx()</code></a></li> <li><a href="#dns_dns_resolvenaptr_hostname_callback"><code>resolver.resolveNaptr()</code></a></li> <li><a href="#dns_dns_resolvens_hostname_callback"><code>resolver.resolveNs()</code></a></li> <li><a href="#dns_dns_resolveptr_hostname_callback"><code>resolver.resolvePtr()</code></a></li> <li><a href="#dns_dns_resolvesoa_hostname_callback"><code>resolver.resolveSoa()</code></a></li> <li><a href="#dns_dns_resolvesrv_hostname_callback"><code>resolver.resolveSrv()</code></a></li> <li><a href="#dns_dns_resolvetxt_hostname_callback"><code>resolver.resolveTxt()</code></a></li> <li><a href="#dns_dns_reverse_ip_callback"><code>resolver.reverse()</code></a></li> <li><a href="#dns_dns_setservers_servers"><code>resolver.setServers()</code></a></li> </ul> <h3><code>resolver.cancel()</code><span><a class="mark" href="#dns_resolver_cancel" id="dns_resolver_cancel">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.3.0</span> </div> <p>Cancel all outstanding DNS queries made by this resolver. The corresponding callbacks will be called with an error with code <code>ECANCELLED</code>.</p> <h2><code>dns.getServers()</code><span><a class="mark" href="#dns_dns_getservers" id="dns_dns_getservers">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.3</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Returns an array of IP address strings, formatted according to <a href="https://tools.ietf.org/html/rfc5952#section-6">rfc5952</a>, that are currently configured for DNS resolution. A string will include a port section if a custom port is used.</p> <!-- eslint-disable semi--> <pre><code class="language-js">[ '4.4.4.4', '2001:4860:4860::8888', '4.4.4.4:1053', '[2001:4860:4860::8888]:1053' ] </code></pre> <h2><code>dns.lookup(hostname[, options], callback)</code><span><a class="mark" href="#dns_dns_lookup_hostname_options_callback" id="dns_dns_lookup_hostname_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.5.0</td> <td><p>The <code>verbatim</code> option is supported now.</p></td></tr> <tr><td>v1.2.0</td> <td><p>The <code>all</code> option is supported now.</p></td></tr> <tr><td>v0.1.90</td> <td><p><span>Added in: v0.1.90</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The record family. Must be <code>4</code> or <code>6</code>. IPv4 and IPv6 addresses are both returned by default.</li> <li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> One or more <a href="#dns_supported_getaddrinfo_flags">supported <code>getaddrinfo</code> flags</a>. Multiple flags may be passed by bitwise <code>OR</code>ing their values.</li> <li><code>all</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the callback returns all resolved addresses in an array. Otherwise, returns a single address. <strong>Default:</strong> <code>false</code>.</li> <li><code>verbatim</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When <code>false</code>, IPv4 addresses are placed before IPv6 addresses. <strong>Default:</strong> currently <code>false</code> (addresses are reordered) but this is expected to change in the not too distant future. New code should use <code>{ verbatim: true }</code>.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string representation of an IPv4 or IPv6 address.</li> <li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <code>4</code> or <code>6</code>, denoting the family of <code>address</code>.</li> </ul> </li> </ul> <p>Resolves a hostname (e.g. <code>'nodejs.org'</code>) into the first found A (IPv4) or AAAA (IPv6) record. All <code>option</code> properties are optional. If <code>options</code> is an integer, then it must be <code>4</code> or <code>6</code> – if <code>options</code> is not provided, then IPv4 and IPv6 addresses are both returned if found.</p> <p>With the <code>all</code> option set to <code>true</code>, the arguments for <code>callback</code> change to <code>(err, addresses)</code>, with <code>addresses</code> being an array of objects with the properties <code>address</code> and <code>family</code>.</p> <p>On error, <code>err</code> is an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is the error code. Keep in mind that <code>err.code</code> will be set to <code>'ENOENT'</code> not only when the hostname does not exist but also when the lookup fails in other ways such as no available file descriptors.</p> <p><code>dns.lookup()</code> does not necessarily have anything to do with the DNS protocol. The implementation uses an operating system facility that can associate names with addresses, and vice versa. This implementation can have subtle but important consequences on the behavior of any Node.js program. Please take some time to consult the <a href="#dns_implementation_considerations">Implementation considerations section</a> before using <code>dns.lookup()</code>.</p> <p>Example usage:</p> <pre><code class="language-js">const dns = require('dns'); const options = { family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED, }; dns.lookup('example.com', options, (err, address, family) => console.log('address: %j family: IPv%s', address, family)); // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 // When options.all is true, the result will be an Array. options.all = true; dns.lookup('example.com', options, (err, addresses) => console.log('addresses: %j', addresses)); // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] </code></pre> <p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, and <code>all</code> is not set to <code>true</code>, it returns a <code>Promise</code> for an <code>Object</code> with <code>address</code> and <code>family</code> properties.</p> <h3>Supported getaddrinfo flags<span><a class="mark" href="#dns_supported_getaddrinfo_flags" id="dns_supported_getaddrinfo_flags">#</a></span></h3> <p>The following flags can be passed as hints to <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</p> <ul> <li><code>dns.ADDRCONFIG</code>: Returned address types are determined by the types of addresses supported by the current system. For example, IPv4 addresses are only returned if the current system has at least one IPv4 address configured. Loopback addresses are not considered.</li> <li><code>dns.V4MAPPED</code>: If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. Note that it is not supported on some operating systems (e.g FreeBSD 10.1).</li> </ul> <h2><code>dns.lookupService(address, port, callback)</code><span><a class="mark" href="#dns_dns_lookupservice_address_port_callback" id="dns_dns_lookupservice_address_port_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <ul> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> e.g. <code>example.com</code></li> <li><code>service</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> e.g. <code>http</code></li> </ul> </li> </ul> <p>Resolves the given <code>address</code> and <code>port</code> into a hostname and service using the operating system's underlying <code>getnameinfo</code> implementation.</p> <p>If <code>address</code> is not a valid IP address, a <code>TypeError</code> will be thrown. The <code>port</code> will be coerced to a number. If it is not a legal port, a <code>TypeError</code> will be thrown.</p> <p>On an error, <code>err</code> is an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is the error code.</p> <pre><code class="language-js">const dns = require('dns'); dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { console.log(hostname, service); // Prints: localhost ssh }); </code></pre> <p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns a <code>Promise</code> for an <code>Object</code> with <code>hostname</code> and <code>service</code> properties.</p> <h2><code>dns.resolve(hostname[, rrtype], callback)</code><span><a class="mark" href="#dns_dns_resolve_hostname_rrtype_callback" id="dns_dns_resolve_hostname_rrtype_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.27</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Hostname to resolve.</li> <li><code>rrtype</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Resource record type. <strong>Default:</strong> <code>'A'</code>.</li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>records</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve a hostname (e.g. <code>'nodejs.org'</code>) into an array of the resource records. The <code>callback</code> function has arguments <code>(err, records)</code>. When successful, <code>records</code> will be an array of resource records. The type and structure of individual results varies based on <code>rrtype</code>:</p> <table><thead><tr><th><code>rrtype</code></th><th><code>records</code> contains</th><th>Result type</th><th>Shorthand method</th></tr></thead><tbody><tr><td><code>'A'</code></td><td>IPv4 addresses (default)</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#dns_dns_resolve4_hostname_options_callback"><code>dns.resolve4()</code></a></td></tr><tr><td><code>'AAAA'</code></td><td>IPv6 addresses</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#dns_dns_resolve6_hostname_options_callback"><code>dns.resolve6()</code></a></td></tr><tr><td><code>'ANY'</code></td><td>any records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#dns_dns_resolveany_hostname_callback"><code>dns.resolveAny()</code></a></td></tr><tr><td><code>'CNAME'</code></td><td>canonical name records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#dns_dns_resolvecname_hostname_callback"><code>dns.resolveCname()</code></a></td></tr><tr><td><code>'MX'</code></td><td>mail exchange records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#dns_dns_resolvemx_hostname_callback"><code>dns.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>name authority pointer records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#dns_dns_resolvenaptr_hostname_callback"><code>dns.resolveNaptr()</code></a></td></tr><tr><td><code>'NS'</code></td><td>name server records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#dns_dns_resolvens_hostname_callback"><code>dns.resolveNs()</code></a></td></tr><tr><td><code>'PTR'</code></td><td>pointer records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#dns_dns_resolveptr_hostname_callback"><code>dns.resolvePtr()</code></a></td></tr><tr><td><code>'SOA'</code></td><td>start of authority records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#dns_dns_resolvesoa_hostname_callback"><code>dns.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>service records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#dns_dns_resolvesrv_hostname_callback"><code>dns.resolveSrv()</code></a></td></tr><tr><td><code>'TXT'</code></td><td>text records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></td><td><a href="#dns_dns_resolvetxt_hostname_callback"><code>dns.resolveTxt()</code></a></td></tr></tbody></table> <p>On error, <code>err</code> is an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is one of the <a href="#dns_error_codes">DNS error codes</a>.</p> <h2><code>dns.resolve4(hostname[, options], callback)</code><span><a class="mark" href="#dns_dns_resolve4_hostname_options_callback" id="dns_dns_resolve4_hostname_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.2.0</td> <td><p>This method now supports passing <code>options</code>, specifically <code>options.ttl</code>.</p></td></tr> <tr><td>v0.1.16</td> <td><p><span>Added in: v0.1.16</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Hostname to resolve.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Retrieve the Time-To-Live value (TTL) of each record. When <code>true</code>, the callback receives an array of <code>{ address: '1.2.3.4', ttl: 60 }</code> objects rather than an array of strings, with the TTL expressed in seconds.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve a IPv4 addresses (<code>A</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will contain an array of IPv4 addresses (e.g. <code>['74.125.79.104', '74.125.79.105', '74.125.79.106']</code>).</p> <h2><code>dns.resolve6(hostname[, options], callback)</code><span><a class="mark" href="#dns_dns_resolve6_hostname_options_callback" id="dns_dns_resolve6_hostname_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.2.0</td> <td><p>This method now supports passing <code>options</code>, specifically <code>options.ttl</code>.</p></td></tr> <tr><td>v0.1.16</td> <td><p><span>Added in: v0.1.16</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Hostname to resolve.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Retrieve the Time-To-Live value (TTL) of each record. When <code>true</code>, the callback receives an array of <code>{ address: '0:1:2:3:4:5:6:7', ttl: 60 }</code> objects rather than an array of strings, with the TTL expressed in seconds.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve a IPv6 addresses (<code>AAAA</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will contain an array of IPv6 addresses.</p> <h2><code>dns.resolveAny(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolveany_hostname_callback" id="dns_dns_resolveany_hostname_callback">#</a></span></h2> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>ret</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve all records (also known as <code>ANY</code> or <code>*</code> query). The <code>ret</code> argument passed to the <code>callback</code> function will be an array containing various types of records. Each object has a property <code>type</code> that indicates the type of the current record. And depending on the <code>type</code>, additional properties will be present on the object:</p> <table><thead><tr><th>Type</th><th>Properties</th></tr></thead><tbody><tr><td><code>'A'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'AAAA'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'CNAME'</code></td><td><code>value</code></td></tr><tr><td><code>'MX'</code></td><td>Refer to <a href="#dns_dns_resolvemx_hostname_callback"><code>dns.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>Refer to <a href="#dns_dns_resolvenaptr_hostname_callback"><code>dns.resolveNaptr()</code></a></td></tr><tr><td><code>'NS'</code></td><td><code>value</code></td></tr><tr><td><code>'PTR'</code></td><td><code>value</code></td></tr><tr><td><code>'SOA'</code></td><td>Refer to <a href="#dns_dns_resolvesoa_hostname_callback"><code>dns.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>Refer to <a href="#dns_dns_resolvesrv_hostname_callback"><code>dns.resolveSrv()</code></a></td></tr><tr><td><code>'TXT'</code></td><td>This type of record contains an array property called <code>entries</code> which refers to <a href="#dns_dns_resolvetxt_hostname_callback"><code>dns.resolveTxt()</code></a>, e.g. <code>{ entries: ['...'], type: 'TXT' }</code></td></tr></tbody></table> <p>Here is an example of the <code>ret</code> object passed to the callback:</p> <!-- eslint-disable semi --> <pre><code class="language-js">[ { type: 'A', address: '127.0.0.1', ttl: 299 }, { type: 'CNAME', value: 'example.com' }, { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, { type: 'NS', value: 'ns1.example.com' }, { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, { type: 'SOA', nsname: 'ns1.example.com', hostmaster: 'admin.example.com', serial: 156696742, refresh: 900, retry: 900, expire: 1800, minttl: 60 } ] </code></pre> <p>DNS server operators may choose not to respond to <code>ANY</code> queries. It may be better to call individual methods like <a href="#dns_dns_resolve4_hostname_options_callback"><code>dns.resolve4()</code></a>, <a href="#dns_dns_resolvemx_hostname_callback"><code>dns.resolveMx()</code></a>, and so on. For more details, see <a href="https://tools.ietf.org/html/rfc8482">RFC 8482</a>.</p> <h2><code>dns.resolveCname(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvecname_hostname_callback" id="dns_dns_resolvecname_hostname_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.2</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve <code>CNAME</code> records for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will contain an array of canonical name records available for the <code>hostname</code> (e.g. <code>['bar.example.com']</code>).</p> <h2><code>dns.resolveMx(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvemx_hostname_callback" id="dns_dns_resolvemx_hostname_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.27</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve mail exchange records (<code>MX</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will contain an array of objects containing both a <code>priority</code> and <code>exchange</code> property (e.g. <code>[{priority: 10, exchange: 'mx.example.com'}, ...]</code>).</p> <h2><code>dns.resolveNaptr(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvenaptr_hostname_callback" id="dns_dns_resolvenaptr_hostname_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.9.12</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve regular expression based records (<code>NAPTR</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will contain an array of objects with the following properties:</p> <ul> <li><code>flags</code></li> <li><code>service</code></li> <li><code>regexp</code></li> <li><code>replacement</code></li> <li><code>order</code></li> <li><code>preference</code></li> </ul> <!-- eslint-skip --> <pre><code class="language-js">{ flags: 's', service: 'SIP+D2U', regexp: '', replacement: '_sip._udp.example.com', order: 30, preference: 100 } </code></pre> <h2><code>dns.resolveNs(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvens_hostname_callback" id="dns_dns_resolvens_hostname_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve name server records (<code>NS</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will contain an array of name server records available for <code>hostname</code> (e.g. <code>['ns1.example.com', 'ns2.example.com']</code>).</p> <h2><code>dns.resolvePtr(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolveptr_hostname_callback" id="dns_dns_resolveptr_hostname_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve pointer records (<code>PTR</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will be an array of strings containing the reply records.</p> <h2><code>dns.resolveSoa(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvesoa_hostname_callback" id="dns_dns_resolvesoa_hostname_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.10</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve a start of authority record (<code>SOA</code> record) for the <code>hostname</code>. The <code>address</code> argument passed to the <code>callback</code> function will be an object with the following properties:</p> <ul> <li><code>nsname</code></li> <li><code>hostmaster</code></li> <li><code>serial</code></li> <li><code>refresh</code></li> <li><code>retry</code></li> <li><code>expire</code></li> <li><code>minttl</code></li> </ul> <!-- eslint-skip --> <pre><code class="language-js">{ nsname: 'ns.example.com', hostmaster: 'root.example.com', serial: 2013101809, refresh: 10000, retry: 2400, expire: 604800, minttl: 3600 } </code></pre> <h2><code>dns.resolveSrv(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvesrv_hostname_callback" id="dns_dns_resolvesrv_hostname_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.27</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve service records (<code>SRV</code> records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will be an array of objects with the following properties:</p> <ul> <li><code>priority</code></li> <li><code>weight</code></li> <li><code>port</code></li> <li><code>name</code></li> </ul> <!-- eslint-skip --> <pre><code class="language-js">{ priority: 10, weight: 5, port: 21223, name: 'service.example.com' } </code></pre> <h2><code>dns.resolveTxt(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvetxt_hostname_callback" id="dns_dns_resolvetxt_hostname_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.27</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>records</code> {string[][]}</li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve text queries (<code>TXT</code> records) for the <code>hostname</code>. The <code>records</code> argument passed to the <code>callback</code> function is a two-dimensional array of the text records available for <code>hostname</code> (e.g. <code>[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]</code>). Each sub-array contains TXT chunks of one record. Depending on the use case, these could be either joined together or treated separately.</p> <h2><code>dns.reverse(ip, callback)</code><span><a class="mark" href="#dns_dns_reverse_ip_callback" id="dns_dns_reverse_ip_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <ul> <li><code>ip</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>hostnames</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> </li> </ul> <p>Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of hostnames.</p> <p>On error, <code>err</code> is an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is one of the <a href="#dns_error_codes">DNS error codes</a>.</p> <h2><code>dns.setServers(servers)</code><span><a class="mark" href="#dns_dns_setservers_servers" id="dns_dns_setservers_servers">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.3</span> </div> <ul> <li><code>servers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> array of <a href="https://tools.ietf.org/html/rfc5952#section-6">rfc5952</a> formatted addresses</li> </ul> <p>Sets the IP address and port of servers to be used when performing DNS resolution. The <code>servers</code> argument is an array of <a href="https://tools.ietf.org/html/rfc5952#section-6">rfc5952</a> formatted addresses. If the port is the IANA default DNS port (53) it can be omitted.</p> <pre><code class="language-js">dns.setServers([ '4.4.4.4', '[2001:4860:4860::8888]', '4.4.4.4:1053', '[2001:4860:4860::8888]:1053' ]); </code></pre> <p>An error will be thrown if an invalid address is provided.</p> <p>The <code>dns.setServers()</code> method must not be called while a DNS query is in progress.</p> <p>The <a href="#dns_dns_setservers_servers"><code>dns.setServers()</code></a> method affects only <a href="#dns_dns_resolve_hostname_rrtype_callback"><code>dns.resolve()</code></a>, [<code>dns.resolve*()</code>][] and <a href="#dns_dns_reverse_ip_callback"><code>dns.reverse()</code></a> (and specifically <em>not</em> <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>).</p> <p>Note that this method works much like <a href="http://man7.org/linux/man-pages/man5/resolv.conf.5.html">resolve.conf</a>. That is, if attempting to resolve with the first server provided results in a <code>NOTFOUND</code> error, the <code>resolve()</code> method will <em>not</em> attempt to resolve with subsequent servers provided. Fallback DNS servers will only be used if the earlier ones time out or result in some other error.</p> <h2>DNS Promises API<span><a class="mark" href="#dns_dns_promises_api" id="dns_dns_promises_api">#</a></span></h2> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>dns.promises</code> API provides an alternative set of asynchronous DNS methods that return <code>Promise</code> objects rather than using callbacks. The API is accessible via <code>require('dns').promises</code>.</p> <h3>Class: <code>dnsPromises.Resolver</code><span><a class="mark" href="#dns_class_dnspromises_resolver" id="dns_class_dnspromises_resolver">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <p>An independent resolver for DNS requests.</p> <p>Note that creating a new resolver uses the default server settings. Setting the servers used for a resolver using <a href="#dns_dnspromises_setservers_servers"><code>resolver.setServers()</code></a> does not affect other resolvers:</p> <pre><code class="language-js">const { Resolver } = require('dns').promises; const resolver = new Resolver(); resolver.setServers(['4.4.4.4']); // This request will use the server at 4.4.4.4, independent of global settings. resolver.resolve4('example.org').then((addresses) => { // ... }); // Alternatively, the same code can be written using async-await style. (async function() { const addresses = await resolver.resolve4('example.org'); })(); </code></pre> <p>The following methods from the <code>dnsPromises</code> API are available:</p> <ul> <li><a href="#dns_dnspromises_getservers"><code>resolver.getServers()</code></a></li> <li><a href="#dns_dnspromises_resolve_hostname_rrtype"><code>resolver.resolve()</code></a></li> <li><a href="#dns_dnspromises_resolve4_hostname_options"><code>resolver.resolve4()</code></a></li> <li><a href="#dns_dnspromises_resolve6_hostname_options"><code>resolver.resolve6()</code></a></li> <li><a href="#dns_dnspromises_resolveany_hostname"><code>resolver.resolveAny()</code></a></li> <li><a href="#dns_dnspromises_resolvecname_hostname"><code>resolver.resolveCname()</code></a></li> <li><a href="#dns_dnspromises_resolvemx_hostname"><code>resolver.resolveMx()</code></a></li> <li><a href="#dns_dnspromises_resolvenaptr_hostname"><code>resolver.resolveNaptr()</code></a></li> <li><a href="#dns_dnspromises_resolvens_hostname"><code>resolver.resolveNs()</code></a></li> <li><a href="#dns_dnspromises_resolveptr_hostname"><code>resolver.resolvePtr()</code></a></li> <li><a href="#dns_dnspromises_resolvesoa_hostname"><code>resolver.resolveSoa()</code></a></li> <li><a href="#dns_dnspromises_resolvesrv_hostname"><code>resolver.resolveSrv()</code></a></li> <li><a href="#dns_dnspromises_resolvetxt_hostname"><code>resolver.resolveTxt()</code></a></li> <li><a href="#dns_dnspromises_reverse_ip"><code>resolver.reverse()</code></a></li> <li><a href="#dns_dnspromises_setservers_servers"><code>resolver.setServers()</code></a></li> </ul> <h3><code>dnsPromises.getServers()</code><span><a class="mark" href="#dns_dnspromises_getservers" id="dns_dnspromises_getservers">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Returns an array of IP address strings, formatted according to <a href="https://tools.ietf.org/html/rfc5952#section-6">rfc5952</a>, that are currently configured for DNS resolution. A string will include a port section if a custom port is used.</p> <!-- eslint-disable semi--> <pre><code class="language-js">[ '4.4.4.4', '2001:4860:4860::8888', '4.4.4.4:1053', '[2001:4860:4860::8888]:1053' ] </code></pre> <h3><code>dnsPromises.lookup(hostname[, options])</code><span><a class="mark" href="#dns_dnspromises_lookup_hostname_options" id="dns_dnspromises_lookup_hostname_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The record family. Must be <code>4</code> or <code>6</code>. IPv4 and IPv6 addresses are both returned by default.</li> <li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> One or more <a href="#dns_supported_getaddrinfo_flags">supported <code>getaddrinfo</code> flags</a>. Multiple flags may be passed by bitwise <code>OR</code>ing their values.</li> <li><code>all</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Promise</code> is resolved with all addresses in an array. Otherwise, returns a single address. <strong>Default:</strong> <code>false</code>.</li> <li><code>verbatim</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Promise</code> is resolved with IPv4 and IPv6 addresses in the order the DNS resolver returned them. When <code>false</code>, IPv4 addresses are placed before IPv6 addresses. <strong>Default:</strong> currently <code>false</code> (addresses are reordered) but this is expected to change in the not too distant future. New code should use <code>{ verbatim: true }</code>.</li> </ul> </li> </ul> <p>Resolves a hostname (e.g. <code>'nodejs.org'</code>) into the first found A (IPv4) or AAAA (IPv6) record. All <code>option</code> properties are optional. If <code>options</code> is an integer, then it must be <code>4</code> or <code>6</code> – if <code>options</code> is not provided, then IPv4 and IPv6 addresses are both returned if found.</p> <p>With the <code>all</code> option set to <code>true</code>, the <code>Promise</code> is resolved with <code>addresses</code> being an array of objects with the properties <code>address</code> and <code>family</code>.</p> <p>On error, the <code>Promise</code> is rejected with an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is the error code. Keep in mind that <code>err.code</code> will be set to <code>'ENOENT'</code> not only when the hostname does not exist but also when the lookup fails in other ways such as no available file descriptors.</p> <p><a href="#dns_dnspromises_lookup_hostname_options"><code>dnsPromises.lookup()</code></a> does not necessarily have anything to do with the DNS protocol. The implementation uses an operating system facility that can associate names with addresses, and vice versa. This implementation can have subtle but important consequences on the behavior of any Node.js program. Please take some time to consult the <a href="#dns_implementation_considerations">Implementation considerations section</a> before using <code>dnsPromises.lookup()</code>.</p> <p>Example usage:</p> <pre><code class="language-js">const dns = require('dns'); const dnsPromises = dns.promises; const options = { family: 6, hints: dns.ADDRCONFIG | dns.V4MAPPED, }; dnsPromises.lookup('example.com', options).then((result) => { console.log('address: %j family: IPv%s', result.address, result.family); // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 }); // When options.all is true, the result will be an Array. options.all = true; dnsPromises.lookup('example.com', options).then((result) => { console.log('addresses: %j', result); // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] }); </code></pre> <h3><code>dnsPromises.lookupService(address, port)</code><span><a class="mark" href="#dns_dnspromises_lookupservice_address_port" id="dns_dnspromises_lookupservice_address_port">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Resolves the given <code>address</code> and <code>port</code> into a hostname and service using the operating system's underlying <code>getnameinfo</code> implementation.</p> <p>If <code>address</code> is not a valid IP address, a <code>TypeError</code> will be thrown. The <code>port</code> will be coerced to a number. If it is not a legal port, a <code>TypeError</code> will be thrown.</p> <p>On error, the <code>Promise</code> is rejected with an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is the error code.</p> <pre><code class="language-js">const dnsPromises = require('dns').promises; dnsPromises.lookupService('127.0.0.1', 22).then((result) => { console.log(result.hostname, result.service); // Prints: localhost ssh }); </code></pre> <h3><code>dnsPromises.resolve(hostname[, rrtype])</code><span><a class="mark" href="#dns_dnspromises_resolve_hostname_rrtype" id="dns_dnspromises_resolve_hostname_rrtype">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Hostname to resolve.</li> <li><code>rrtype</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Resource record type. <strong>Default:</strong> <code>'A'</code>.</li> </ul> <p>Uses the DNS protocol to resolve a hostname (e.g. <code>'nodejs.org'</code>) into an array of the resource records. When successful, the <code>Promise</code> is resolved with an array of resource records. The type and structure of individual results vary based on <code>rrtype</code>:</p> <table><thead><tr><th><code>rrtype</code></th><th><code>records</code> contains</th><th>Result type</th><th>Shorthand method</th></tr></thead><tbody><tr><td><code>'A'</code></td><td>IPv4 addresses (default)</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#dns_dnspromises_resolve4_hostname_options"><code>dnsPromises.resolve4()</code></a></td></tr><tr><td><code>'AAAA'</code></td><td>IPv6 addresses</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#dns_dnspromises_resolve6_hostname_options"><code>dnsPromises.resolve6()</code></a></td></tr><tr><td><code>'ANY'</code></td><td>any records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#dns_dnspromises_resolveany_hostname"><code>dnsPromises.resolveAny()</code></a></td></tr><tr><td><code>'CNAME'</code></td><td>canonical name records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#dns_dnspromises_resolvecname_hostname"><code>dnsPromises.resolveCname()</code></a></td></tr><tr><td><code>'MX'</code></td><td>mail exchange records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#dns_dnspromises_resolvemx_hostname"><code>dnsPromises.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>name authority pointer records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#dns_dnspromises_resolvenaptr_hostname"><code>dnsPromises.resolveNaptr()</code></a></td></tr><tr><td><code>'NS'</code></td><td>name server records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#dns_dnspromises_resolvens_hostname"><code>dnsPromises.resolveNs()</code></a></td></tr><tr><td><code>'PTR'</code></td><td>pointer records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></td><td><a href="#dns_dnspromises_resolveptr_hostname"><code>dnsPromises.resolvePtr()</code></a></td></tr><tr><td><code>'SOA'</code></td><td>start of authority records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#dns_dnspromises_resolvesoa_hostname"><code>dnsPromises.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>service records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></td><td><a href="#dns_dnspromises_resolvesrv_hostname"><code>dnsPromises.resolveSrv()</code></a></td></tr><tr><td><code>'TXT'</code></td><td>text records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></td><td><a href="#dns_dnspromises_resolvetxt_hostname"><code>dnsPromises.resolveTxt()</code></a></td></tr></tbody></table> <p>On error, the <code>Promise</code> is rejected with an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is one of the <a href="#dns_error_codes">DNS error codes</a>.</p> <h3><code>dnsPromises.resolve4(hostname[, options])</code><span><a class="mark" href="#dns_dnspromises_resolve4_hostname_options" id="dns_dnspromises_resolve4_hostname_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Hostname to resolve.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Retrieve the Time-To-Live value (TTL) of each record. When <code>true</code>, the <code>Promise</code> is resolved with an array of <code>{ address: '1.2.3.4', ttl: 60 }</code> objects rather than an array of strings, with the TTL expressed in seconds.</li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve IPv4 addresses (<code>A</code> records) for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of IPv4 addresses (e.g. <code>['74.125.79.104', '74.125.79.105', '74.125.79.106']</code>).</p> <h3><code>dnsPromises.resolve6(hostname[, options])</code><span><a class="mark" href="#dns_dnspromises_resolve6_hostname_options" id="dns_dnspromises_resolve6_hostname_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Hostname to resolve.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Retrieve the Time-To-Live value (TTL) of each record. When <code>true</code>, the <code>Promise</code> is resolved with an array of <code>{ address: '0:1:2:3:4:5:6:7', ttl: 60 }</code> objects rather than an array of strings, with the TTL expressed in seconds.</li> </ul> </li> </ul> <p>Uses the DNS protocol to resolve IPv6 addresses (<code>AAAA</code> records) for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of IPv6 addresses.</p> <h3><code>dnsPromises.resolveAny(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolveany_hostname" id="dns_dnspromises_resolveany_hostname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Uses the DNS protocol to resolve all records (also known as <code>ANY</code> or <code>*</code> query). On success, the <code>Promise</code> is resolved with an array containing various types of records. Each object has a property <code>type</code> that indicates the type of the current record. And depending on the <code>type</code>, additional properties will be present on the object:</p> <table><thead><tr><th>Type</th><th>Properties</th></tr></thead><tbody><tr><td><code>'A'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'AAAA'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'CNAME'</code></td><td><code>value</code></td></tr><tr><td><code>'MX'</code></td><td>Refer to <a href="#dns_dnspromises_resolvemx_hostname"><code>dnsPromises.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>Refer to <a href="#dns_dnspromises_resolvenaptr_hostname"><code>dnsPromises.resolveNaptr()</code></a></td></tr><tr><td><code>'NS'</code></td><td><code>value</code></td></tr><tr><td><code>'PTR'</code></td><td><code>value</code></td></tr><tr><td><code>'SOA'</code></td><td>Refer to <a href="#dns_dnspromises_resolvesoa_hostname"><code>dnsPromises.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>Refer to <a href="#dns_dnspromises_resolvesrv_hostname"><code>dnsPromises.resolveSrv()</code></a></td></tr><tr><td><code>'TXT'</code></td><td>This type of record contains an array property called <code>entries</code> which refers to <a href="#dns_dnspromises_resolvetxt_hostname"><code>dnsPromises.resolveTxt()</code></a>, e.g. <code>{ entries: ['...'], type: 'TXT' }</code></td></tr></tbody></table> <p>Here is an example of the result object:</p> <!-- eslint-disable semi --> <pre><code class="language-js">[ { type: 'A', address: '127.0.0.1', ttl: 299 }, { type: 'CNAME', value: 'example.com' }, { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, { type: 'NS', value: 'ns1.example.com' }, { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, { type: 'SOA', nsname: 'ns1.example.com', hostmaster: 'admin.example.com', serial: 156696742, refresh: 900, retry: 900, expire: 1800, minttl: 60 } ] </code></pre> <h3><code>dnsPromises.resolveCname(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvecname_hostname" id="dns_dnspromises_resolvecname_hostname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Uses the DNS protocol to resolve <code>CNAME</code> records for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of canonical name records available for the <code>hostname</code> (e.g. <code>['bar.example.com']</code>).</p> <h3><code>dnsPromises.resolveMx(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvemx_hostname" id="dns_dnspromises_resolvemx_hostname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Uses the DNS protocol to resolve mail exchange records (<code>MX</code> records) for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of objects containing both a <code>priority</code> and <code>exchange</code> property (e.g. <code>[{priority: 10, exchange: 'mx.example.com'}, ...]</code>).</p> <h3><code>dnsPromises.resolveNaptr(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvenaptr_hostname" id="dns_dnspromises_resolvenaptr_hostname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Uses the DNS protocol to resolve regular expression based records (<code>NAPTR</code> records) for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of objects with the following properties:</p> <ul> <li><code>flags</code></li> <li><code>service</code></li> <li><code>regexp</code></li> <li><code>replacement</code></li> <li><code>order</code></li> <li><code>preference</code></li> </ul> <!-- eslint-skip --> <pre><code class="language-js">{ flags: 's', service: 'SIP+D2U', regexp: '', replacement: '_sip._udp.example.com', order: 30, preference: 100 } </code></pre> <h3><code>dnsPromises.resolveNs(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvens_hostname" id="dns_dnspromises_resolvens_hostname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Uses the DNS protocol to resolve name server records (<code>NS</code> records) for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of name server records available for <code>hostname</code> (e.g. <code>['ns1.example.com', 'ns2.example.com']</code>).</p> <h3><code>dnsPromises.resolvePtr(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolveptr_hostname" id="dns_dnspromises_resolveptr_hostname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Uses the DNS protocol to resolve pointer records (<code>PTR</code> records) for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of strings containing the reply records.</p> <h3><code>dnsPromises.resolveSoa(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvesoa_hostname" id="dns_dnspromises_resolvesoa_hostname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Uses the DNS protocol to resolve a start of authority record (<code>SOA</code> record) for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an object with the following properties:</p> <ul> <li><code>nsname</code></li> <li><code>hostmaster</code></li> <li><code>serial</code></li> <li><code>refresh</code></li> <li><code>retry</code></li> <li><code>expire</code></li> <li><code>minttl</code></li> </ul> <!-- eslint-skip --> <pre><code class="language-js">{ nsname: 'ns.example.com', hostmaster: 'root.example.com', serial: 2013101809, refresh: 10000, retry: 2400, expire: 604800, minttl: 3600 } </code></pre> <h3><code>dnsPromises.resolveSrv(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvesrv_hostname" id="dns_dnspromises_resolvesrv_hostname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Uses the DNS protocol to resolve service records (<code>SRV</code> records) for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of objects with the following properties:</p> <ul> <li><code>priority</code></li> <li><code>weight</code></li> <li><code>port</code></li> <li><code>name</code></li> </ul> <!-- eslint-skip --> <pre><code class="language-js">{ priority: 10, weight: 5, port: 21223, name: 'service.example.com' } </code></pre> <h3><code>dnsPromises.resolveTxt(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvetxt_hostname" id="dns_dnspromises_resolvetxt_hostname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Uses the DNS protocol to resolve text queries (<code>TXT</code> records) for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with a two-dimensional array of the text records available for <code>hostname</code> (e.g. <code>[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]</code>). Each sub-array contains TXT chunks of one record. Depending on the use case, these could be either joined together or treated separately.</p> <h3><code>dnsPromises.reverse(ip)</code><span><a class="mark" href="#dns_dnspromises_reverse_ip" id="dns_dnspromises_reverse_ip">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>ip</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an array of hostnames.</p> <p>On error, the <code>Promise</code> is rejected with an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is one of the <a href="#dns_error_codes">DNS error codes</a>.</p> <h3><code>dnsPromises.setServers(servers)</code><span><a class="mark" href="#dns_dnspromises_setservers_servers" id="dns_dnspromises_setservers_servers">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><code>servers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> array of <a href="https://tools.ietf.org/html/rfc5952#section-6">rfc5952</a> formatted addresses</li> </ul> <p>Sets the IP address and port of servers to be used when performing DNS resolution. The <code>servers</code> argument is an array of <a href="https://tools.ietf.org/html/rfc5952#section-6">rfc5952</a> formatted addresses. If the port is the IANA default DNS port (53) it can be omitted.</p> <pre><code class="language-js">dnsPromises.setServers([ '4.4.4.4', '[2001:4860:4860::8888]', '4.4.4.4:1053', '[2001:4860:4860::8888]:1053' ]); </code></pre> <p>An error will be thrown if an invalid address is provided.</p> <p>The <code>dnsPromises.setServers()</code> method must not be called while a DNS query is in progress.</p> <p>Note that this method works much like <a href="http://man7.org/linux/man-pages/man5/resolv.conf.5.html">resolve.conf</a>. That is, if attempting to resolve with the first server provided results in a <code>NOTFOUND</code> error, the <code>resolve()</code> method will <em>not</em> attempt to resolve with subsequent servers provided. Fallback DNS servers will only be used if the earlier ones time out or result in some other error.</p> <h2>Error codes<span><a class="mark" href="#dns_error_codes" id="dns_error_codes">#</a></span></h2> <p>Each DNS query can return one of the following error codes:</p> <ul> <li><code>dns.NODATA</code>: DNS server returned answer with no data.</li> <li><code>dns.FORMERR</code>: DNS server claims query was misformatted.</li> <li><code>dns.SERVFAIL</code>: DNS server returned general failure.</li> <li><code>dns.NOTFOUND</code>: Domain name not found.</li> <li><code>dns.NOTIMP</code>: DNS server does not implement requested operation.</li> <li><code>dns.REFUSED</code>: DNS server refused query.</li> <li><code>dns.BADQUERY</code>: Misformatted DNS query.</li> <li><code>dns.BADNAME</code>: Misformatted hostname.</li> <li><code>dns.BADFAMILY</code>: Unsupported address family.</li> <li><code>dns.BADRESP</code>: Misformatted DNS reply.</li> <li><code>dns.CONNREFUSED</code>: Could not contact DNS servers.</li> <li><code>dns.TIMEOUT</code>: Timeout while contacting DNS servers.</li> <li><code>dns.EOF</code>: End of file.</li> <li><code>dns.FILE</code>: Error reading file.</li> <li><code>dns.NOMEM</code>: Out of memory.</li> <li><code>dns.DESTRUCTION</code>: Channel is being destroyed.</li> <li><code>dns.BADSTR</code>: Misformatted string.</li> <li><code>dns.BADFLAGS</code>: Illegal flags specified.</li> <li><code>dns.NONAME</code>: Given hostname is not numeric.</li> <li><code>dns.BADHINTS</code>: Illegal hints flags specified.</li> <li><code>dns.NOTINITIALIZED</code>: c-ares library initialization not yet performed.</li> <li><code>dns.LOADIPHLPAPI</code>: Error loading <code>iphlpapi.dll</code>.</li> <li><code>dns.ADDRGETNETWORKPARAMS</code>: Could not find <code>GetNetworkParams</code> function.</li> <li><code>dns.CANCELLED</code>: DNS query cancelled.</li> </ul> <h2>Implementation considerations<span><a class="mark" href="#dns_implementation_considerations" id="dns_implementation_considerations">#</a></span></h2> <p>Although <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> and the various <code>dns.resolve*()/dns.reverse()</code> functions have the same goal of associating a network name with a network address (or vice versa), their behavior is quite different. These differences can have subtle but significant consequences on the behavior of Node.js programs.</p> <h3><code>dns.lookup()</code><span><a class="mark" href="#dns_dns_lookup" id="dns_dns_lookup">#</a></span></h3> <p>Under the hood, <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> uses the same operating system facilities as most other programs. For instance, <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> will almost always resolve a given name the same way as the <code>ping</code> command. On most POSIX-like operating systems, the behavior of the <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> function can be modified by changing settings in <a href="http://man7.org/linux/man-pages/man5/nsswitch.conf.5.html"><code>nsswitch.conf(5)</code></a> and/or <a href="http://man7.org/linux/man-pages/man5/resolv.conf.5.html"><code>resolv.conf(5)</code></a>, but note that changing these files will change the behavior of <em>all other programs running on the same operating system</em>.</p> <p>Though the call to <code>dns.lookup()</code> will be asynchronous from JavaScript's perspective, it is implemented as a synchronous call to <a href="http://man7.org/linux/man-pages/man3/getaddrinfo.3.html"><code>getaddrinfo(3)</code></a> that runs on libuv's threadpool. This can have surprising negative performance implications for some applications, see the <a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p> <p>Note that various networking APIs will call <code>dns.lookup()</code> internally to resolve host names. If that is an issue, consider resolving the hostname to an address using <code>dns.resolve()</code> and using the address instead of a host name. Also, some networking APIs (such as <a href="#net_socket_connect_options_connectlistener"><code>socket.connect()</code></a> and <a href="#dgram_dgram_createsocket_options_callback"><code>dgram.createSocket()</code></a>) allow the default resolver, <code>dns.lookup()</code>, to be replaced.</p> <h3><code>dns.resolve()</code>, <code>dns.resolve*()</code> and <code>dns.reverse()</code><span><a class="mark" href="#dns_dns_resolve_dns_resolve_and_dns_reverse" id="dns_dns_resolve_dns_resolve_and_dns_reverse">#</a></span></h3> <p>These functions are implemented quite differently than <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>. They do not use <a href="http://man7.org/linux/man-pages/man3/getaddrinfo.3.html"><code>getaddrinfo(3)</code></a> and they <em>always</em> perform a DNS query on the network. This network communication is always done asynchronously, and does not use libuv's threadpool.</p> <p>As a result, these functions cannot have the same negative impact on other processing that happens on libuv's threadpool that <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> can have.</p> <p>They do not use the same set of configuration files than what <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> uses. For instance, <em>they do not use the configuration from <code>/etc/hosts</code></em>.</p> <h1>Domain<span><a class="mark" href="#domain_domain" id="domain_domain">#</a></span></h1> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.8.0</td> <td><p>Any <code>Promise</code>s created in VM contexts no longer have a <code>.domain</code> property. Their handlers are still executed in the proper domain, however, and <code>Promise</code>s created in the main context still possess a <code>.domain</code> property.</p></td></tr> <tr><td>v8.0.0</td> <td><p>Handlers for <code>Promise</code>s are now invoked in the domain in which the first promise of a chain was created.</p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p> <p><strong>This module is pending deprecation</strong>. Once a replacement API has been finalized, this module will be fully deprecated. Most end users should <strong>not</strong> have cause to use this module. Users who absolutely must have the functionality that domains provide may rely on it for the time being but should expect to have to migrate to a different solution in the future.</p> <p>Domains provide a way to handle multiple different IO operations as a single group. If any of the event emitters or callbacks registered to a domain emit an <code>'error'</code> event, or throw an error, then the domain object will be notified, rather than losing the context of the error in the <code>process.on('uncaughtException')</code> handler, or causing the program to exit immediately with an error code.</p> <h2>Warning: Don't Ignore Errors!<span><a class="mark" href="#domain_warning_don_t_ignore_errors" id="domain_warning_don_t_ignore_errors">#</a></span></h2> <p>Domain error handlers are not a substitute for closing down a process when an error occurs.</p> <p>By the very nature of how <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw"><code>throw</code></a> works in JavaScript, there is almost never any way to safely "pick up where it left off", without leaking references, or creating some other sort of undefined brittle state.</p> <p>The safest way to respond to a thrown error is to shut down the process. Of course, in a normal web server, there may be many open connections, and it is not reasonable to abruptly shut those down because an error was triggered by someone else.</p> <p>The better approach is to send an error response to the request that triggered the error, while letting the others finish in their normal time, and stop listening for new requests in that worker.</p> <p>In this way, <code>domain</code> usage goes hand-in-hand with the cluster module, since the master process can fork a new worker when a worker encounters an error. For Node.js programs that scale to multiple machines, the terminating proxy or service registry can take note of the failure, and react accordingly.</p> <p>For example, this is not a good idea:</p> <pre><code class="language-js">// XXX WARNING! BAD IDEA! const d = require('domain').create(); d.on('error', (er) => { // The error won't crash the process, but what it does is worse! // Though we've prevented abrupt process restarting, we are leaking // resources like crazy if this ever happens. // This is no better than process.on('uncaughtException')! console.log(`error, but oh well ${er.message}`); }); d.run(() => { require('http').createServer((req, res) => { handleRequest(req, res); }).listen(PORT); }); </code></pre> <p>By using the context of a domain, and the resilience of separating our program into multiple worker processes, we can react more appropriately, and handle errors with much greater safety.</p> <pre><code class="language-js">// Much better! const cluster = require('cluster'); const PORT = +process.env.PORT || 1337; if (cluster.isMaster) { // A more realistic scenario would have more than 2 workers, // and perhaps not put the master and worker in the same file. // // It is also possible to get a bit fancier about logging, and // implement whatever custom logic is needed to prevent DoS // attacks and other bad behavior. // // See the options in the cluster documentation. // // The important thing is that the master does very little, // increasing our resilience to unexpected errors. cluster.fork(); cluster.fork(); cluster.on('disconnect', (worker) => { console.error('disconnect!'); cluster.fork(); }); } else { // the worker // // This is where we put our bugs! const domain = require('domain'); // See the cluster documentation for more details about using // worker processes to serve requests. How it works, caveats, etc. const server = require('http').createServer((req, res) => { const d = domain.create(); d.on('error', (er) => { console.error(`error ${er.stack}`); // We're in dangerous territory! // By definition, something unexpected occurred, // which we probably didn't want. // Anything can happen now! Be very careful! try { // make sure we close down within 30 seconds const killtimer = setTimeout(() => { process.exit(1); }, 30000); // But don't keep the process open just for that! killtimer.unref(); // stop taking new requests. server.close(); // Let the master know we're dead. This will trigger a // 'disconnect' in the cluster master, and then it will fork // a new worker. cluster.worker.disconnect(); // try to send an error to the request that triggered the problem res.statusCode = 500; res.setHeader('content-type', 'text/plain'); res.end('Oops, there was a problem!\n'); } catch (er2) { // oh well, not much we can do at this point. console.error(`Error sending 500! ${er2.stack}`); } }); // Because req and res were created before this domain existed, // we need to explicitly add them. // See the explanation of implicit vs explicit binding below. d.add(req); d.add(res); // Now run the handler function in the domain. d.run(() => { handleRequest(req, res); }); }); server.listen(PORT); } // This part is not important. Just an example routing thing. // Put fancy application logic here. function handleRequest(req, res) { switch (req.url) { case '/error': // We do some async stuff, and then... setTimeout(() => { // Whoops! flerb.bark(); }, timeout); break; default: res.end('ok'); } } </code></pre> <h2>Additions to Error objects<span><a class="mark" href="#domain_additions_to_error_objects" id="domain_additions_to_error_objects">#</a></span></h2> <p>Any time an <code>Error</code> object is routed through a domain, a few extra fields are added to it.</p> <ul> <li><code>error.domain</code> The domain that first handled the error.</li> <li><code>error.domainEmitter</code> The event emitter that emitted an <code>'error'</code> event with the error object.</li> <li><code>error.domainBound</code> The callback function which was bound to the domain, and passed an error as its first argument.</li> <li><code>error.domainThrown</code> A boolean indicating whether the error was thrown, emitted, or passed to a bound callback function.</li> </ul> <h2>Implicit Binding<span><a class="mark" href="#domain_implicit_binding" id="domain_implicit_binding">#</a></span></h2> <p>If domains are in use, then all <strong>new</strong> <code>EventEmitter</code> objects (including Stream objects, requests, responses, etc.) will be implicitly bound to the active domain at the time of their creation.</p> <p>Additionally, callbacks passed to lowlevel event loop requests (such as to <code>fs.open()</code>, or other callback-taking methods) will automatically be bound to the active domain. If they throw, then the domain will catch the error.</p> <p>In order to prevent excessive memory usage, <code>Domain</code> objects themselves are not implicitly added as children of the active domain. If they were, then it would be too easy to prevent request and response objects from being properly garbage collected.</p> <p>To nest <code>Domain</code> objects as children of a parent <code>Domain</code> they must be explicitly added.</p> <p>Implicit binding routes thrown errors and <code>'error'</code> events to the <code>Domain</code>'s <code>'error'</code> event, but does not register the <code>EventEmitter</code> on the <code>Domain</code>. Implicit binding only takes care of thrown errors and <code>'error'</code> events.</p> <h2>Explicit Binding<span><a class="mark" href="#domain_explicit_binding" id="domain_explicit_binding">#</a></span></h2> <p>Sometimes, the domain in use is not the one that ought to be used for a specific event emitter. Or, the event emitter could have been created in the context of one domain, but ought to instead be bound to some other domain.</p> <p>For example, there could be one domain in use for an HTTP server, but perhaps we would like to have a separate domain to use for each request.</p> <p>That is possible via explicit binding.</p> <pre><code class="language-js">// create a top-level domain for the server const domain = require('domain'); const http = require('http'); const serverDomain = domain.create(); serverDomain.run(() => { // server is created in the scope of serverDomain http.createServer((req, res) => { // req and res are also created in the scope of serverDomain // however, we'd prefer to have a separate domain for each request. // create it first thing, and add req and res to it. const reqd = domain.create(); reqd.add(req); reqd.add(res); reqd.on('error', (er) => { console.error('Error', er, req.url); try { res.writeHead(500); res.end('Error occurred, sorry.'); } catch (er2) { console.error('Error sending 500', er2, req.url); } }); }).listen(1337); }); </code></pre> <h2>domain.create()<span><a class="mark" href="#domain_domain_create" id="domain_domain_create">#</a></span></h2> <ul> <li>Returns: <a href="#domain_class_domain" class="type"><Domain></a></li> </ul> <h2>Class: Domain<span><a class="mark" href="#domain_class_domain" id="domain_class_domain">#</a></span></h2> <p>The <code>Domain</code> class encapsulates the functionality of routing errors and uncaught exceptions to the active <code>Domain</code> object.</p> <p><code>Domain</code> is a child class of <a href="#events_class_eventemitter"><code>EventEmitter</code></a>. To handle the errors that it catches, listen to its <code>'error'</code> event.</p> <h3>domain.members<span><a class="mark" href="#domain_domain_members" id="domain_domain_members">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li> </ul> <p>An array of timers and event emitters that have been explicitly added to the domain.</p> <h3>domain.add(emitter)<span><a class="mark" href="#domain_domain_add_emitter" id="domain_domain_add_emitter">#</a></span></h3> <ul> <li><code>emitter</code> <a href="#events_class_eventemitter" class="type"><EventEmitter></a> | <a href="#timers_timers" class="type"><Timer></a> emitter or timer to be added to the domain</li> </ul> <p>Explicitly adds an emitter to the domain. If any event handlers called by the emitter throw an error, or if the emitter emits an <code>'error'</code> event, it will be routed to the domain's <code>'error'</code> event, just like with implicit binding.</p> <p>This also works with timers that are returned from <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a> and <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a>. If their callback function throws, it will be caught by the domain <code>'error'</code> handler.</p> <p>If the Timer or <code>EventEmitter</code> was already bound to a domain, it is removed from that one, and bound to this one instead.</p> <h3>domain.bind(callback)<span><a class="mark" href="#domain_domain_bind_callback" id="domain_domain_bind_callback">#</a></span></h3> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The bound function</li> </ul> <p>The returned function will be a wrapper around the supplied callback function. When the returned function is called, any errors that are thrown will be routed to the domain's <code>'error'</code> event.</p> <pre><code class="language-js">const d = domain.create(); function readSomeFile(filename, cb) { fs.readFile(filename, 'utf8', d.bind((er, data) => { // if this throws, it will also be passed to the domain return cb(er, data ? JSON.parse(data) : null); })); } d.on('error', (er) => { // an error occurred somewhere. // if we throw it now, it will crash the program // with the normal line number and stack message. }); </code></pre> <h3>domain.enter()<span><a class="mark" href="#domain_domain_enter" id="domain_domain_enter">#</a></span></h3> <p>The <code>enter()</code> method is plumbing used by the <code>run()</code>, <code>bind()</code>, and <code>intercept()</code> methods to set the active domain. It sets <code>domain.active</code> and <code>process.domain</code> to the domain, and implicitly pushes the domain onto the domain stack managed by the domain module (see <a href="#domain_domain_exit"><code>domain.exit()</code></a> for details on the domain stack). The call to <code>enter()</code> delimits the beginning of a chain of asynchronous calls and I/O operations bound to a domain.</p> <p>Calling <code>enter()</code> changes only the active domain, and does not alter the domain itself. <code>enter()</code> and <code>exit()</code> can be called an arbitrary number of times on a single domain.</p> <h3>domain.exit()<span><a class="mark" href="#domain_domain_exit" id="domain_domain_exit">#</a></span></h3> <p>The <code>exit()</code> method exits the current domain, popping it off the domain stack. Any time execution is going to switch to the context of a different chain of asynchronous calls, it's important to ensure that the current domain is exited. The call to <code>exit()</code> delimits either the end of or an interruption to the chain of asynchronous calls and I/O operations bound to a domain.</p> <p>If there are multiple, nested domains bound to the current execution context, <code>exit()</code> will exit any domains nested within this domain.</p> <p>Calling <code>exit()</code> changes only the active domain, and does not alter the domain itself. <code>enter()</code> and <code>exit()</code> can be called an arbitrary number of times on a single domain.</p> <h3>domain.intercept(callback)<span><a class="mark" href="#domain_domain_intercept_callback" id="domain_domain_intercept_callback">#</a></span></h3> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The intercepted function</li> </ul> <p>This method is almost identical to <a href="#domain_domain_bind_callback"><code>domain.bind(callback)</code></a>. However, in addition to catching thrown errors, it will also intercept <a href="#errors_class_error"><code>Error</code></a> objects sent as the first argument to the function.</p> <p>In this way, the common <code>if (err) return callback(err);</code> pattern can be replaced with a single error handler in a single place.</p> <pre><code class="language-js">const d = domain.create(); function readSomeFile(filename, cb) { fs.readFile(filename, 'utf8', d.intercept((data) => { // note, the first argument is never passed to the // callback since it is assumed to be the 'Error' argument // and thus intercepted by the domain. // if this throws, it will also be passed to the domain // so the error-handling logic can be moved to the 'error' // event on the domain instead of being repeated throughout // the program. return cb(null, JSON.parse(data)); })); } d.on('error', (er) => { // an error occurred somewhere. // if we throw it now, it will crash the program // with the normal line number and stack message. }); </code></pre> <h3>domain.remove(emitter)<span><a class="mark" href="#domain_domain_remove_emitter" id="domain_domain_remove_emitter">#</a></span></h3> <ul> <li><code>emitter</code> <a href="#events_class_eventemitter" class="type"><EventEmitter></a> | <a href="#timers_timers" class="type"><Timer></a> emitter or timer to be removed from the domain</li> </ul> <p>The opposite of <a href="#domain_domain_add_emitter"><code>domain.add(emitter)</code></a>. Removes domain handling from the specified emitter.</p> <h3>domain.run(fn[, ...args])<span><a class="mark" href="#domain_domain_run_fn_args" id="domain_domain_run_fn_args">#</a></span></h3> <ul> <li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Run the supplied function in the context of the domain, implicitly binding all event emitters, timers, and lowlevel requests that are created in that context. Optionally, arguments can be passed to the function.</p> <p>This is the most basic way to use a domain.</p> <pre><code class="language-js">const domain = require('domain'); const fs = require('fs'); const d = domain.create(); d.on('error', (er) => { console.error('Caught error!', er); }); d.run(() => { process.nextTick(() => { setTimeout(() => { // simulating some various async stuff fs.open('non-existent file', 'r', (er, fd) => { if (er) throw er; // proceed... }); }, 100); }); }); </code></pre> <p>In this example, the <code>d.on('error')</code> handler will be triggered, rather than crashing the program.</p> <h2>Domains and Promises<span><a class="mark" href="#domain_domains_and_promises" id="domain_domains_and_promises">#</a></span></h2> <p>As of Node.js 8.0.0, the handlers of Promises are run inside the domain in which the call to <code>.then()</code> or <code>.catch()</code> itself was made:</p> <pre><code class="language-js">const d1 = domain.create(); const d2 = domain.create(); let p; d1.run(() => { p = Promise.resolve(42); }); d2.run(() => { p.then((v) => { // running in d2 }); }); </code></pre> <p>A callback may be bound to a specific domain using <a href="#domain_domain_bind_callback"><code>domain.bind(callback)</code></a>:</p> <pre><code class="language-js">const d1 = domain.create(); const d2 = domain.create(); let p; d1.run(() => { p = Promise.resolve(42); }); d2.run(() => { p.then(p.domain.bind((v) => { // running in d1 })); }); </code></pre> <p>Note that domains will not interfere with the error handling mechanisms for Promises, i.e. no <code>'error'</code> event will be emitted for unhandled <code>Promise</code> rejections.</p> <h1>ECMAScript Modules<span><a class="mark" href="#esm_ecmascript_modules" id="esm_ecmascript_modules">#</a></span></h1> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>Node.js contains support for ES Modules based upon the <a href="https://github.com/nodejs/node-eps/blob/master/002-es-modules.md">Node.js EP for ES Modules</a>.</p> <p>Not all features of the EP are complete and will be landing as both VM support and implementation is ready. Error messages are still being polished.</p> <h2>Enabling<span><a class="mark" href="#esm_enabling" id="esm_enabling">#</a></span></h2> <p>The <code>--experimental-modules</code> flag can be used to enable features for loading ESM modules.</p> <p>Once this has been set, files ending with <code>.mjs</code> will be able to be loaded as ES Modules.</p> <pre><code class="language-sh">node --experimental-modules my-app.mjs </code></pre> <h2>Features<span><a class="mark" href="#esm_features" id="esm_features">#</a></span></h2> <h3>Supported<span><a class="mark" href="#esm_supported" id="esm_supported">#</a></span></h3> <p>Only the CLI argument for the main entry point to the program can be an entry point into an ESM graph. Dynamic import can also be used to create entry points into ESM graphs at runtime.</p> <h4>import.meta<span><a class="mark" href="#esm_import_meta" id="esm_import_meta">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>import.meta</code> metaproperty is an <code>Object</code> that contains the following property:</p> <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute <code>file:</code> URL of the module.</li> </ul> <h3>Unsupported<span><a class="mark" href="#esm_unsupported" id="esm_unsupported">#</a></span></h3> <table><thead><tr><th>Feature</th><th>Reason</th></tr></thead><tbody><tr><td><code>require('./foo.mjs')</code></td><td>ES Modules have differing resolution and timing, use dynamic import</td></tr></tbody></table> <h2>Notable differences between <code>import</code> and <code>require</code><span><a class="mark" href="#esm_notable_differences_between_import_and_require" id="esm_notable_differences_between_import_and_require">#</a></span></h2> <h3>No NODE_PATH<span><a class="mark" href="#esm_no_node_path" id="esm_no_node_path">#</a></span></h3> <p><code>NODE_PATH</code> is not part of resolving <code>import</code> specifiers. Please use symlinks if this behavior is desired.</p> <h3>No <code>require.extensions</code><span><a class="mark" href="#esm_no_require_extensions" id="esm_no_require_extensions">#</a></span></h3> <p><code>require.extensions</code> is not used by <code>import</code>. The expectation is that loader hooks can provide this workflow in the future.</p> <h3>No <code>require.cache</code><span><a class="mark" href="#esm_no_require_cache" id="esm_no_require_cache">#</a></span></h3> <p><code>require.cache</code> is not used by <code>import</code>. It has a separate cache.</p> <h3>URL based paths<span><a class="mark" href="#esm_url_based_paths" id="esm_url_based_paths">#</a></span></h3> <p>ESM are resolved and cached based upon <a href="https://url.spec.whatwg.org/">URL</a> semantics. This means that files containing special characters such as <code>#</code> and <code>?</code> need to be escaped.</p> <p>Modules will be loaded multiple times if the <code>import</code> specifier used to resolve them have a different query or fragment.</p> <pre><code class="language-js">import './foo?query=1'; // loads ./foo with query of "?query=1" import './foo?query=2'; // loads ./foo with query of "?query=2" </code></pre> <p>For now, only modules using the <code>file:</code> protocol can be loaded.</p> <h2>Interop with existing modules<span><a class="mark" href="#esm_interop_with_existing_modules" id="esm_interop_with_existing_modules">#</a></span></h2> <p>All CommonJS, JSON, and C++ modules can be used with <code>import</code>.</p> <p>Modules loaded this way will only be loaded once, even if their query or fragment string differs between <code>import</code> statements.</p> <p>When loaded via <code>import</code> these modules will provide a single <code>default</code> export representing the value of <code>module.exports</code> at the time they finished evaluating.</p> <pre><code class="language-js">// foo.js module.exports = { one: 1 }; // bar.mjs import foo from './foo.js'; foo.one === 1; // true </code></pre> <p>Builtin modules will provide named exports of their public API, as well as a default export which can be used for, among other things, modifying the named exports. Named exports of builtin modules are updated when the corresponding exports property is accessed, redefined, or deleted.</p> <pre><code class="language-js">import EventEmitter from 'events'; const e = new EventEmitter(); </code></pre> <pre><code class="language-js">import { readFile } from 'fs'; readFile('./foo.txt', (err, source) => { if (err) { console.error(err); } else { console.log(source); } }); </code></pre> <pre><code class="language-js">import fs, { readFileSync } from 'fs'; fs.readFileSync = () => Buffer.from('Hello, ESM'); fs.readFileSync === readFileSync; </code></pre> <h2>Loader hooks<span><a class="mark" href="#esm_loader_hooks" id="esm_loader_hooks">#</a></span></h2> <p>To customize the default module resolution, loader hooks can optionally be provided via a <code>--loader ./loader-name.mjs</code> argument to Node.js.</p> <p>When hooks are used they only apply to ES module loading and not to any CommonJS modules loaded.</p> <h3>Resolve hook<span><a class="mark" href="#esm_resolve_hook" id="esm_resolve_hook">#</a></span></h3> <p>The resolve hook returns the resolved file URL and module format for a given module specifier and parent file URL:</p> <pre><code class="language-js">const baseURL = new URL('file://'); baseURL.pathname = `${process.cwd()}/`; export async function resolve(specifier, parentModuleURL = baseURL, defaultResolver) { return { url: new URL(specifier, parentModuleURL).href, format: 'esm' }; } </code></pre> <p>The <code>parentModuleURL</code> is provided as <code>undefined</code> when performing main Node.js load itself.</p> <p>The default Node.js ES module resolution function is provided as a third argument to the resolver for easy compatibility workflows.</p> <p>In addition to returning the resolved file URL value, the resolve hook also returns a <code>format</code> property specifying the module format of the resolved module. This can be one of the following:</p> <table><thead><tr><th><code>format</code></th><th>Description</th></tr></thead><tbody><tr><td><code>'esm'</code></td><td>Load a standard JavaScript module</td></tr><tr><td><code>'cjs'</code></td><td>Load a node-style CommonJS module</td></tr><tr><td><code>'builtin'</code></td><td>Load a node builtin CommonJS module</td></tr><tr><td><code>'json'</code></td><td>Load a JSON file</td></tr><tr><td><code>'addon'</code></td><td>Load a <a href="addons.html">C++ Addon</a></td></tr><tr><td><code>'dynamic'</code></td><td>Use a <a href="#esm_dynamic_instantiate_hook">dynamic instantiate hook</a></td></tr></tbody></table> <p>For example, a dummy loader to load JavaScript restricted to browser resolution rules with only JS file extension and Node.js builtin modules support could be written:</p> <pre><code class="language-js">import path from 'path'; import process from 'process'; import Module from 'module'; const builtins = Module.builtinModules; const JS_EXTENSIONS = new Set(['.js', '.mjs']); const baseURL = new URL('file://'); baseURL.pathname = `${process.cwd()}/`; export function resolve(specifier, parentModuleURL = baseURL, defaultResolve) { if (builtins.includes(specifier)) { return { url: specifier, format: 'builtin' }; } if (/^\.{0,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) { // For node_modules support: // return defaultResolve(specifier, parentModuleURL); throw new Error( `imports must begin with '/', './', or '../'; '${specifier}' does not`); } const resolved = new URL(specifier, parentModuleURL); const ext = path.extname(resolved.pathname); if (!JS_EXTENSIONS.has(ext)) { throw new Error( `Cannot load file with non-JavaScript file extension ${ext}.`); } return { url: resolved.href, format: 'esm' }; } </code></pre> <p>With this loader, running:</p> <pre><code class="language-console">NODE_OPTIONS='--experimental-modules --loader ./custom-loader.mjs' node x.js </code></pre> <p>would load the module <code>x.js</code> as an ES module with relative resolution support (with <code>node_modules</code> loading skipped in this example).</p> <h3>Dynamic instantiate hook<span><a class="mark" href="#esm_dynamic_instantiate_hook" id="esm_dynamic_instantiate_hook">#</a></span></h3> <p>To create a custom dynamic module that doesn't correspond to one of the existing <code>format</code> interpretations, the <code>dynamicInstantiate</code> hook can be used. This hook is called only for modules that return <code>format: 'dynamic'</code> from the <code>resolve</code> hook.</p> <pre><code class="language-js">export async function dynamicInstantiate(url) { return { exports: ['customExportName'], execute: (exports) => { // get and set functions provided for pre-allocated export names exports.customExportName.set('value'); } }; } </code></pre> <p>With the list of module exports provided upfront, the <code>execute</code> function will then be called at the exact point of module evaluation order for that module in the import tree.</p> <h1>Errors<span><a class="mark" href="#errors_errors" id="errors_errors">#</a></span></h1> <p>Applications running in Node.js will generally experience four categories of errors:</p> <ul> <li>Standard JavaScript errors such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError" class="type"><EvalError></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError" class="type"><SyntaxError></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError" class="type"><RangeError></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError" class="type"><ReferenceError></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError" class="type"><TypeError></a>, and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError" class="type"><URIError></a>.</li> <li>System errors triggered by underlying operating system constraints such as attempting to open a file that does not exist or attempting to send data over a closed socket.</li> <li>User-specified errors triggered by application code.</li> <li><code>AssertionError</code>s are a special class of error that can be triggered when Node.js detects an exceptional logic violation that should never occur. These are raised typically by the <code>assert</code> module.</li> </ul> <p>All JavaScript and System errors raised by Node.js inherit from, or are instances of, the standard JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> class and are guaranteed to provide <em>at least</em> the properties available on that class.</p> <h2>Error Propagation and Interception<span><a class="mark" href="#errors_error_propagation_and_interception" id="errors_error_propagation_and_interception">#</a></span></h2> <p>Node.js supports several mechanisms for propagating and handling errors that occur while an application is running. How these errors are reported and handled depends entirely on the type of <code>Error</code> and the style of the API that is called.</p> <p>All JavaScript errors are handled as exceptions that <em>immediately</em> generate and throw an error using the standard JavaScript <code>throw</code> mechanism. These are handled using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>try…catch</code> construct</a> provided by the JavaScript language.</p> <pre><code class="language-js">// Throws with a ReferenceError because z is not defined. try { const m = 1; const n = m + z; } catch (err) { // Handle the error here. } </code></pre> <p>Any use of the JavaScript <code>throw</code> mechanism will raise an exception that <em>must</em> be handled using <code>try…catch</code> or the Node.js process will exit immediately.</p> <p>With few exceptions, <em>Synchronous</em> APIs (any blocking method that does not accept a <code>callback</code> function, such as <a href="#fs_fs_readfilesync_path_options"><code>fs.readFileSync</code></a>), will use <code>throw</code> to report errors.</p> <p>Errors that occur within <em>Asynchronous APIs</em> may be reported in multiple ways:</p> <ul> <li>Most asynchronous methods that accept a <code>callback</code> function will accept an <code>Error</code> object passed as the first argument to that function. If that first argument is not <code>null</code> and is an instance of <code>Error</code>, then an error occurred that should be handled.</li> </ul> <!-- eslint-disable no-useless-return --> <pre><code class="language-js">const fs = require('fs'); fs.readFile('a file that does not exist', (err, data) => { if (err) { console.error('There was an error reading the file!', err); return; } // Otherwise handle the data }); </code></pre> <ul> <li> <p>When an asynchronous method is called on an object that is an <a href="#events_class_eventemitter"><code>EventEmitter</code></a>, errors can be routed to that object's <code>'error'</code> event.</p> <pre><code class="language-js">const net = require('net'); const connection = net.connect('localhost'); // Adding an 'error' event handler to a stream: connection.on('error', (err) => { // If the connection is reset by the server, or if it can't // connect at all, or on any sort of error encountered by // the connection, the error will be sent here. console.error(err); }); connection.pipe(process.stdout); </code></pre> </li> <li> <p>A handful of typically asynchronous methods in the Node.js API may still use the <code>throw</code> mechanism to raise exceptions that must be handled using <code>try…catch</code>. There is no comprehensive list of such methods; please refer to the documentation of each method to determine the appropriate error handling mechanism required.</p> </li> </ul> <p>The use of the <code>'error'</code> event mechanism is most common for <a href="stream.html">stream-based</a> and <a href="#events_class_eventemitter">event emitter-based</a> APIs, which themselves represent a series of asynchronous operations over time (as opposed to a single operation that may pass or fail).</p> <p>For <em>all</em> <a href="#events_class_eventemitter"><code>EventEmitter</code></a> objects, if an <code>'error'</code> event handler is not provided, the error will be thrown, causing the Node.js process to report an uncaught exception and crash unless either: The <a href="domain.html"><code>domain</code></a> module is used appropriately or a handler has been registered for the <a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a> event.</p> <pre><code class="language-js">const EventEmitter = require('events'); const ee = new EventEmitter(); setImmediate(() => { // This will crash the process because no 'error' event // handler has been added. ee.emit('error', new Error('This will crash')); }); </code></pre> <p>Errors generated in this way <em>cannot</em> be intercepted using <code>try…catch</code> as they are thrown <em>after</em> the calling code has already exited.</p> <p>Developers must refer to the documentation for each method to determine exactly how errors raised by those methods are propagated.</p> <h3>Error-first callbacks<span><a class="mark" href="#errors_error_first_callbacks" id="errors_error_first_callbacks">#</a></span></h3> <p>Most asynchronous methods exposed by the Node.js core API follow an idiomatic pattern referred to as an <em>error-first callback</em>. With this pattern, a callback function is passed to the method as an argument. When the operation either completes or an error is raised, the callback function is called with the <code>Error</code> object (if any) passed as the first argument. If no error was raised, the first argument will be passed as <code>null</code>.</p> <pre><code class="language-js">const fs = require('fs'); function errorFirstCallback(err, data) { if (err) { console.error('There was an error', err); return; } console.log(data); } fs.readFile('/some/file/that/does-not-exist', errorFirstCallback); fs.readFile('/some/file/that/does-exist', errorFirstCallback); </code></pre> <p>The JavaScript <code>try…catch</code> mechanism <strong>cannot</strong> be used to intercept errors generated by asynchronous APIs. A common mistake for beginners is to try to use <code>throw</code> inside an error-first callback:</p> <pre><code class="language-js">// THIS WILL NOT WORK: const fs = require('fs'); try { fs.readFile('/some/file/that/does-not-exist', (err, data) => { // mistaken assumption: throwing here... if (err) { throw err; } }); } catch (err) { // This will not catch the throw! console.error(err); } </code></pre> <p>This will not work because the callback function passed to <code>fs.readFile()</code> is called asynchronously. By the time the callback has been called, the surrounding code (including the <code>try { } catch (err) { }</code> block will have already exited. Throwing an error inside the callback <strong>can crash the Node.js process</strong> in most cases. If <a href="domain.html">domains</a> are enabled, or a handler has been registered with <code>process.on('uncaughtException')</code>, such errors can be intercepted.</p> <h2>Class: Error<span><a class="mark" href="#errors_class_error" id="errors_class_error">#</a></span></h2> <p>A generic JavaScript <code>Error</code> object that does not denote any specific circumstance of why the error occurred. <code>Error</code> objects capture a "stack trace" detailing the point in the code at which the <code>Error</code> was instantiated, and may provide a text description of the error.</p> <p>For crypto only, <code>Error</code> objects will include the OpenSSL error stack in a separate property called <code>opensslErrorStack</code> if it is available when the error is thrown.</p> <p>All errors generated by Node.js, including all System and JavaScript errors, will either be instances of, or inherit from, the <code>Error</code> class.</p> <h3>new Error(message)<span><a class="mark" href="#errors_new_error_message" id="errors_new_error_message">#</a></span></h3> <ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Creates a new <code>Error</code> object and sets the <code>error.message</code> property to the provided text message. If an object is passed as <code>message</code>, the text message is generated by calling <code>message.toString()</code>. The <code>error.stack</code> property will represent the point in the code at which <code>new Error()</code> was called. Stack traces are dependent on <a href="https://github.com/v8/v8/wiki/Stack-Trace-API">V8's stack trace API</a>. Stack traces extend only to either (a) the beginning of <em>synchronous code execution</em>, or (b) the number of frames given by the property <code>Error.stackTraceLimit</code>, whichever is smaller.</p> <h3>Error.captureStackTrace(targetObject[, constructorOpt])<span><a class="mark" href="#errors_error_capturestacktrace_targetobject_constructoropt" id="errors_error_capturestacktrace_targetobject_constructoropt">#</a></span></h3> <ul> <li><code>targetObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>constructorOpt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Creates a <code>.stack</code> property on <code>targetObject</code>, which when accessed returns a string representing the location in the code at which <code>Error.captureStackTrace()</code> was called.</p> <pre><code class="language-js">const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // similar to `new Error().stack` </code></pre> <p>The first line of the trace will be prefixed with <code>${myObject.name}: ${myObject.message}</code>.</p> <p>The optional <code>constructorOpt</code> argument accepts a function. If given, all frames above <code>constructorOpt</code>, including <code>constructorOpt</code>, will be omitted from the generated stack trace.</p> <p>The <code>constructorOpt</code> argument is useful for hiding implementation details of error generation from an end user. For instance:</p> <pre><code class="language-js">function MyError() { Error.captureStackTrace(this, MyError); } // Without passing MyError to captureStackTrace, the MyError // frame would show up in the .stack property. By passing // the constructor, we omit that frame, and retain all frames below it. new MyError().stack; </code></pre> <h3>Error.stackTraceLimit<span><a class="mark" href="#errors_error_stacktracelimit" id="errors_error_stacktracelimit">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <code>Error.stackTraceLimit</code> property specifies the number of stack frames collected by a stack trace (whether generated by <code>new Error().stack</code> or <code>Error.captureStackTrace(obj)</code>).</p> <p>The default value is <code>10</code> but may be set to any valid JavaScript number. Changes will affect any stack trace captured <em>after</em> the value has been changed.</p> <p>If set to a non-number value, or set to a negative number, stack traces will not capture any frames.</p> <h3>error.code<span><a class="mark" href="#errors_error_code" id="errors_error_code">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>error.code</code> property is a string label that identifies the kind of error. <code>error.code</code> is the most stable way to identify an error. It will only change between major versions of Node.js. In contrast, <code>error.message</code> strings may change between any versions of Node.js. See <a href="#nodejs-error-codes">Node.js Error Codes</a> for details about specific codes.</p> <h3>error.message<span><a class="mark" href="#errors_error_message" id="errors_error_message">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>error.message</code> property is the string description of the error as set by calling <code>new Error(message)</code>. The <code>message</code> passed to the constructor will also appear in the first line of the stack trace of the <code>Error</code>, however changing this property after the <code>Error</code> object is created <em>may not</em> change the first line of the stack trace (for example, when <code>error.stack</code> is read before this property is changed).</p> <pre><code class="language-js">const err = new Error('The message'); console.error(err.message); // Prints: The message </code></pre> <h3>error.stack<span><a class="mark" href="#errors_error_stack" id="errors_error_stack">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>error.stack</code> property is a string describing the point in the code at which the <code>Error</code> was instantiated.</p> <pre><code class="language-txt">Error: Things keep happening! at /home/gbusey/file.js:525:2 at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21) at Actor.<anonymous> (/home/gbusey/actors.js:400:8) at increaseSynergy (/home/gbusey/actors.js:701:6) </code></pre> <p>The first line is formatted as <code><error class name>: <error message></code>, and is followed by a series of stack frames (each line beginning with "at "). Each frame describes a call site within the code that lead to the error being generated. V8 attempts to display a name for each function (by variable name, function name, or object method name), but occasionally it will not be able to find a suitable name. If V8 cannot determine a name for the function, only location information will be displayed for that frame. Otherwise, the determined function name will be displayed with location information appended in parentheses.</p> <p>Frames are only generated for JavaScript functions. If, for example, execution synchronously passes through a C++ addon function called <code>cheetahify</code> which itself calls a JavaScript function, the frame representing the <code>cheetahify</code> call will not be present in the stack traces:</p> <pre><code class="language-js">const cheetahify = require('./native-binding.node'); function makeFaster() { // cheetahify *synchronously* calls speedy. cheetahify(function speedy() { throw new Error('oh no!'); }); } makeFaster(); // will throw: // /home/gbusey/file.js:6 // throw new Error('oh no!'); // ^ // Error: oh no! // at speedy (/home/gbusey/file.js:6:11) // at makeFaster (/home/gbusey/file.js:5:3) // at Object.<anonymous> (/home/gbusey/file.js:10:1) // at Module._compile (module.js:456:26) // at Object.Module._extensions..js (module.js:474:10) // at Module.load (module.js:356:32) // at Function.Module._load (module.js:312:12) // at Function.Module.runMain (module.js:497:10) // at startup (node.js:119:16) // at node.js:906:3 </code></pre> <p>The location information will be one of:</p> <ul> <li><code>native</code>, if the frame represents a call internal to V8 (as in <code>[].forEach</code>).</li> <li><code>plain-filename.js:line:column</code>, if the frame represents a call internal to Node.js.</li> <li><code>/absolute/path/to/file.js:line:column</code>, if the frame represents a call in a user program, or its dependencies.</li> </ul> <p>The string representing the stack trace is lazily generated when the <code>error.stack</code> property is <strong>accessed</strong>.</p> <p>The number of frames captured by the stack trace is bounded by the smaller of <code>Error.stackTraceLimit</code> or the number of available frames on the current event loop tick.</p> <p>System-level errors are generated as augmented <code>Error</code> instances, which are detailed <a href="#errors_system_errors">here</a>.</p> <h2>Class: AssertionError<span><a class="mark" href="#errors_class_assertionerror" id="errors_class_assertionerror">#</a></span></h2> <p>A subclass of <code>Error</code> that indicates the failure of an assertion. For details, see <a href="#assert_class_assert_assertionerror"><code>Class: assert.AssertionError</code></a>.</p> <h2>Class: RangeError<span><a class="mark" href="#errors_class_rangeerror" id="errors_class_rangeerror">#</a></span></h2> <p>A subclass of <code>Error</code> that indicates that a provided argument was not within the set or range of acceptable values for a function; whether that is a numeric range, or outside the set of options for a given function parameter.</p> <pre><code class="language-js">require('net').connect(-1); // throws "RangeError: "port" option should be >= 0 and < 65536: -1" </code></pre> <p>Node.js will generate and throw <code>RangeError</code> instances <em>immediately</em> as a form of argument validation.</p> <h2>Class: ReferenceError<span><a class="mark" href="#errors_class_referenceerror" id="errors_class_referenceerror">#</a></span></h2> <p>A subclass of <code>Error</code> that indicates that an attempt is being made to access a variable that is not defined. Such errors commonly indicate typos in code, or an otherwise broken program.</p> <p>While client code may generate and propagate these errors, in practice, only V8 will do so.</p> <pre><code class="language-js">doesNotExist; // throws ReferenceError, doesNotExist is not a variable in this program. </code></pre> <p>Unless an application is dynamically generating and running code, <code>ReferenceError</code> instances should always be considered a bug in the code or its dependencies.</p> <h2>Class: SyntaxError<span><a class="mark" href="#errors_class_syntaxerror" id="errors_class_syntaxerror">#</a></span></h2> <p>A subclass of <code>Error</code> that indicates that a program is not valid JavaScript. These errors may only be generated and propagated as a result of code evaluation. Code evaluation may happen as a result of <code>eval</code>, <code>Function</code>, <code>require</code>, or <a href="vm.html">vm</a>. These errors are almost always indicative of a broken program.</p> <pre><code class="language-js">try { require('vm').runInThisContext('binary ! isNotOk'); } catch (err) { // err will be a SyntaxError } </code></pre> <p><code>SyntaxError</code> instances are unrecoverable in the context that created them – they may only be caught by other contexts.</p> <h2>Class: TypeError<span><a class="mark" href="#errors_class_typeerror" id="errors_class_typeerror">#</a></span></h2> <p>A subclass of <code>Error</code> that indicates that a provided argument is not an allowable type. For example, passing a function to a parameter which expects a string would be considered a <code>TypeError</code>.</p> <pre><code class="language-js">require('url').parse(() => { }); // throws TypeError, since it expected a string </code></pre> <p>Node.js will generate and throw <code>TypeError</code> instances <em>immediately</em> as a form of argument validation.</p> <h2>Exceptions vs. Errors<span><a class="mark" href="#errors_exceptions_vs_errors" id="errors_exceptions_vs_errors">#</a></span></h2> <p>A JavaScript exception is a value that is thrown as a result of an invalid operation or as the target of a <code>throw</code> statement. While it is not required that these values are instances of <code>Error</code> or classes which inherit from <code>Error</code>, all exceptions thrown by Node.js or the JavaScript runtime <em>will</em> be instances of <code>Error</code>.</p> <p>Some exceptions are <em>unrecoverable</em> at the JavaScript layer. Such exceptions will <em>always</em> cause the Node.js process to crash. Examples include <code>assert()</code> checks or <code>abort()</code> calls in the C++ layer.</p> <h2>System Errors<span><a class="mark" href="#errors_system_errors" id="errors_system_errors">#</a></span></h2> <p>Node.js generates system errors when exceptions occur within its runtime environment. These usually occur when an application violates an operating system constraint. For example, a system error will occur if an application attempts to read a file that does not exist.</p> <p>System errors are usually generated at the syscall level. For a comprehensive list, see the <a href="http://man7.org/linux/man-pages/man3/errno.3.html"><code>errno</code>(3) man page</a>.</p> <p>In Node.js, system errors are <code>Error</code> objects with extra properties.</p> <h3>Class: SystemError<span><a class="mark" href="#errors_class_systemerror" id="errors_class_systemerror">#</a></span></h3> <ul> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If present, the address to which a network connection failed</li> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The string error code</li> <li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If present, the file path destination when reporting a file system error</li> <li><code>errno</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The system-provided error number</li> <li><code>info</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> If present, extra details about the error condition</li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A system-provided human-readable description of the error</li> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If present, the file path when reporting a file system error</li> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If present, the network connection port that is not available</li> <li><code>syscall</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the system call that triggered the error</li> </ul> <h4>error.address<span><a class="mark" href="#errors_error_address" id="errors_error_address">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>If present, <code>error.address</code> is a string describing the address to which a network connection failed.</p> <h4>error.code<span><a class="mark" href="#errors_error_code_1" id="errors_error_code_1">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>error.code</code> property is a string representing the error code.</p> <h4>error.dest<span><a class="mark" href="#errors_error_dest" id="errors_error_dest">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>If present, <code>error.dest</code> is the file path destination when reporting a file system error.</p> <h4>error.errno<span><a class="mark" href="#errors_error_errno" id="errors_error_errno">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <code>error.errno</code> property is a number or a string. If it is a number, it is a negative value which corresponds to the error code defined in <a href="http://docs.libuv.org/en/v1.x/errors.html"><code>libuv Error handling</code></a>. See the libuv <code>errno.h</code> header file (<code>deps/uv/include/uv/errno.h</code> in the Node.js source tree) for details. In case of a string, it is the same as <code>error.code</code>.</p> <h4>error.info<span><a class="mark" href="#errors_error_info" id="errors_error_info">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>If present, <code>error.info</code> is an object with details about the error condition.</p> <h4>error.message<span><a class="mark" href="#errors_error_message_1" id="errors_error_message_1">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p><code>error.message</code> is a system-provided human-readable description of the error.</p> <h4>error.path<span><a class="mark" href="#errors_error_path" id="errors_error_path">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>If present, <code>error.path</code> is a string containing a relevant invalid pathname.</p> <h4>error.port<span><a class="mark" href="#errors_error_port" id="errors_error_port">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>If present, <code>error.port</code> is the network connection port that is not available.</p> <h4>error.syscall<span><a class="mark" href="#errors_error_syscall" id="errors_error_syscall">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>error.syscall</code> property is a string describing the <a href="http://man7.org/linux/man-pages/man2/syscalls.2.html">syscall</a> that failed.</p> <h3>Common System Errors<span><a class="mark" href="#errors_common_system_errors" id="errors_common_system_errors">#</a></span></h3> <p>This is a list of system errors commonly-encountered when writing a Node.js program. For a comprehensive list, see the <a href="http://man7.org/linux/man-pages/man3/errno.3.html"><code>errno</code>(3) man page</a>.</p> <ul> <li> <p><code>EACCES</code> (Permission denied): An attempt was made to access a file in a way forbidden by its file access permissions.</p> </li> <li> <p><code>EADDRINUSE</code> (Address already in use): An attempt to bind a server (<a href="net.html"><code>net</code></a>, <a href="http.html"><code>http</code></a>, or <a href="https.html"><code>https</code></a>) to a local address failed due to another server on the local system already occupying that address.</p> </li> <li> <p><code>ECONNREFUSED</code> (Connection refused): No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host.</p> </li> <li> <p><code>ECONNRESET</code> (Connection reset by peer): A connection was forcibly closed by a peer. This normally results from a loss of the connection on the remote socket due to a timeout or reboot. Commonly encountered via the <a href="http.html"><code>http</code></a> and <a href="net.html"><code>net</code></a> modules.</p> </li> <li> <p><code>EEXIST</code> (File exists): An existing file was the target of an operation that required that the target not exist.</p> </li> <li> <p><code>EISDIR</code> (Is a directory): An operation expected a file, but the given pathname was a directory.</p> </li> <li> <p><code>EMFILE</code> (Too many open files in system): Maximum number of <a href="https://en.wikipedia.org/wiki/File_descriptor">file descriptors</a> allowable on the system has been reached, and requests for another descriptor cannot be fulfilled until at least one has been closed. This is encountered when opening many files at once in parallel, especially on systems (in particular, macOS) where there is a low file descriptor limit for processes. To remedy a low limit, run <code>ulimit -n 2048</code> in the same shell that will run the Node.js process.</p> </li> <li> <p><code>ENOENT</code> (No such file or directory): Commonly raised by <a href="fs.html"><code>fs</code></a> operations to indicate that a component of the specified pathname does not exist. No entity (file or directory) could be found by the given path.</p> </li> <li> <p><code>ENOTDIR</code> (Not a directory): A component of the given pathname existed, but was not a directory as expected. Commonly raised by <a href="#fs_fs_readdir_path_options_callback"><code>fs.readdir</code></a>.</p> </li> <li> <p><code>ENOTEMPTY</code> (Directory not empty): A directory with entries was the target of an operation that requires an empty directory, usually <a href="#fs_fs_unlink_path_callback"><code>fs.unlink</code></a>.</p> </li> <li> <p><code>EPERM</code> (Operation not permitted): An attempt was made to perform an operation that requires elevated privileges.</p> </li> <li> <p><code>EPIPE</code> (Broken pipe): A write on a pipe, socket, or FIFO for which there is no process to read the data. Commonly encountered at the <a href="net.html"><code>net</code></a> and <a href="http.html"><code>http</code></a> layers, indicative that the remote side of the stream being written to has been closed.</p> </li> <li> <p><code>ETIMEDOUT</code> (Operation timed out): A connect or send request failed because the connected party did not properly respond after a period of time. Usually encountered by <a href="http.html"><code>http</code></a> or <a href="net.html"><code>net</code></a>. Often a sign that a <code>socket.end()</code> was not properly called.</p> </li> </ul> <p><a id="nodejs-error-codes"></a></p> <h2>Node.js Error Codes<span><a class="mark" href="#errors_node_js_error_codes" id="errors_node_js_error_codes">#</a></span></h2> <p><a id="ERR_AMBIGUOUS_ARGUMENT"></a></p> <h3>ERR_AMBIGUOUS_ARGUMENT<span><a class="mark" href="#errors_err_ambiguous_argument" id="errors_err_ambiguous_argument">#</a></span><span><a class="mark" href="#ERR_AMBIGUOUS_ARGUMENT" id="ERR_AMBIGUOUS_ARGUMENT">#</a></span></h3> <p>A function argument is being used in a way that suggests that the function signature may be misunderstood. This is thrown by the <code>assert</code> module when the <code>message</code> parameter in <code>assert.throws(block, message)</code> matches the error message thrown by <code>block</code> because that usage suggests that the user believes <code>message</code> is the expected message rather than the message the <code>AssertionError</code> will display if <code>block</code> does not throw.</p> <p><a id="ERR_ARG_NOT_ITERABLE"></a></p> <h3>ERR_ARG_NOT_ITERABLE<span><a class="mark" href="#errors_err_arg_not_iterable" id="errors_err_arg_not_iterable">#</a></span><span><a class="mark" href="#ERR_ARG_NOT_ITERABLE" id="ERR_ARG_NOT_ITERABLE">#</a></span></h3> <p>An iterable argument (i.e. a value that works with <code>for...of</code> loops) was required, but not provided to a Node.js API.</p> <p><a id="ERR_ASSERTION"></a></p> <h3>ERR_ASSERTION<span><a class="mark" href="#errors_err_assertion" id="errors_err_assertion">#</a></span><span><a class="mark" href="#ERR_ASSERTION" id="ERR_ASSERTION">#</a></span></h3> <p>A special type of error that can be triggered whenever Node.js detects an exceptional logic violation that should never occur. These are raised typically by the <code>assert</code> module.</p> <p><a id="ERR_ASYNC_CALLBACK"></a></p> <h3>ERR_ASYNC_CALLBACK<span><a class="mark" href="#errors_err_async_callback" id="errors_err_async_callback">#</a></span><span><a class="mark" href="#ERR_ASYNC_CALLBACK" id="ERR_ASYNC_CALLBACK">#</a></span></h3> <p>An attempt was made to register something that is not a function as an <code>AsyncHooks</code> callback.</p> <p><a id="ERR_ASYNC_TYPE"></a></p> <h3>ERR_ASYNC_TYPE<span><a class="mark" href="#errors_err_async_type" id="errors_err_async_type">#</a></span><span><a class="mark" href="#ERR_ASYNC_TYPE" id="ERR_ASYNC_TYPE">#</a></span></h3> <p>The type of an asynchronous resource was invalid. Note that users are also able to define their own types if using the public embedder API.</p> <p><a id="ERR_BROTLI_COMPRESSION_FAILED"></a></p> <h3>ERR_BROTLI_COMPRESSION_FAILED<span><a class="mark" href="#errors_err_brotli_compression_failed" id="errors_err_brotli_compression_failed">#</a></span><span><a class="mark" href="#ERR_BROTLI_COMPRESSION_FAILED" id="ERR_BROTLI_COMPRESSION_FAILED">#</a></span></h3> <p>Data passed to a Brotli stream was not successfully compressed.</p> <p><a id="ERR_BROTLI_INVALID_PARAM"></a></p> <h3>ERR_BROTLI_INVALID_PARAM<span><a class="mark" href="#errors_err_brotli_invalid_param" id="errors_err_brotli_invalid_param">#</a></span><span><a class="mark" href="#ERR_BROTLI_INVALID_PARAM" id="ERR_BROTLI_INVALID_PARAM">#</a></span></h3> <p>An invalid parameter key was passed during construction of a Brotli stream.</p> <p><a id="ERR_BUFFER_OUT_OF_BOUNDS"></a></p> <h3>ERR_BUFFER_OUT_OF_BOUNDS<span><a class="mark" href="#errors_err_buffer_out_of_bounds" id="errors_err_buffer_out_of_bounds">#</a></span><span><a class="mark" href="#ERR_BUFFER_OUT_OF_BOUNDS" id="ERR_BUFFER_OUT_OF_BOUNDS">#</a></span></h3> <p>An operation outside the bounds of a <code>Buffer</code> was attempted.</p> <p><a id="ERR_BUFFER_TOO_LARGE"></a></p> <h3>ERR_BUFFER_TOO_LARGE<span><a class="mark" href="#errors_err_buffer_too_large" id="errors_err_buffer_too_large">#</a></span><span><a class="mark" href="#ERR_BUFFER_TOO_LARGE" id="ERR_BUFFER_TOO_LARGE">#</a></span></h3> <p>An attempt has been made to create a <code>Buffer</code> larger than the maximum allowed size.</p> <p><a id="ERR_CANNOT_TRANSFER_OBJECT"></a></p> <h3>ERR_CANNOT_TRANSFER_OBJECT<span><a class="mark" href="#errors_err_cannot_transfer_object" id="errors_err_cannot_transfer_object">#</a></span><span><a class="mark" href="#ERR_CANNOT_TRANSFER_OBJECT" id="ERR_CANNOT_TRANSFER_OBJECT">#</a></span></h3> <p>The value passed to <code>postMessage()</code> contained an object that is not supported for transferring.</p> <p><a id="ERR_CANNOT_WATCH_SIGINT"></a></p> <h3>ERR_CANNOT_WATCH_SIGINT<span><a class="mark" href="#errors_err_cannot_watch_sigint" id="errors_err_cannot_watch_sigint">#</a></span><span><a class="mark" href="#ERR_CANNOT_WATCH_SIGINT" id="ERR_CANNOT_WATCH_SIGINT">#</a></span></h3> <p>Node.js was unable to watch for the <code>SIGINT</code> signal.</p> <p><a id="ERR_CHILD_CLOSED_BEFORE_REPLY"></a></p> <h3>ERR_CHILD_CLOSED_BEFORE_REPLY<span><a class="mark" href="#errors_err_child_closed_before_reply" id="errors_err_child_closed_before_reply">#</a></span><span><a class="mark" href="#ERR_CHILD_CLOSED_BEFORE_REPLY" id="ERR_CHILD_CLOSED_BEFORE_REPLY">#</a></span></h3> <p>A child process was closed before the parent received a reply.</p> <p><a id="ERR_CHILD_PROCESS_IPC_REQUIRED"></a></p> <h3>ERR_CHILD_PROCESS_IPC_REQUIRED<span><a class="mark" href="#errors_err_child_process_ipc_required" id="errors_err_child_process_ipc_required">#</a></span><span><a class="mark" href="#ERR_CHILD_PROCESS_IPC_REQUIRED" id="ERR_CHILD_PROCESS_IPC_REQUIRED">#</a></span></h3> <p>Used when a child process is being forked without specifying an IPC channel.</p> <p><a id="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"></a></p> <h3>ERR_CHILD_PROCESS_STDIO_MAXBUFFER<span><a class="mark" href="#errors_err_child_process_stdio_maxbuffer" id="errors_err_child_process_stdio_maxbuffer">#</a></span><span><a class="mark" href="#ERR_CHILD_PROCESS_STDIO_MAXBUFFER" id="ERR_CHILD_PROCESS_STDIO_MAXBUFFER">#</a></span></h3> <p>Used when the main process is trying to read data from the child process's STDERR/STDOUT, and the data's length is longer than the <code>maxBuffer</code> option.</p> <p><a id="ERR_CLOSED_MESSAGE_PORT"></a></p> <h3>ERR_CLOSED_MESSAGE_PORT<span><a class="mark" href="#errors_err_closed_message_port" id="errors_err_closed_message_port">#</a></span><span><a class="mark" href="#ERR_CLOSED_MESSAGE_PORT" id="ERR_CLOSED_MESSAGE_PORT">#</a></span></h3> <p>There was an attempt to use a <code>MessagePort</code> instance in a closed state, usually after <code>.close()</code> has been called.</p> <p><a id="ERR_CONSOLE_WRITABLE_STREAM"></a></p> <h3>ERR_CONSOLE_WRITABLE_STREAM<span><a class="mark" href="#errors_err_console_writable_stream" id="errors_err_console_writable_stream">#</a></span><span><a class="mark" href="#ERR_CONSOLE_WRITABLE_STREAM" id="ERR_CONSOLE_WRITABLE_STREAM">#</a></span></h3> <p><code>Console</code> was instantiated without <code>stdout</code> stream, or <code>Console</code> has a non-writable <code>stdout</code> or <code>stderr</code> stream.</p> <p><a id="ERR_CONSTRUCT_CALL_REQUIRED"></a></p> <h3>ERR_CONSTRUCT_CALL_REQUIRED<span><a class="mark" href="#errors_err_construct_call_required" id="errors_err_construct_call_required">#</a></span><span><a class="mark" href="#ERR_CONSTRUCT_CALL_REQUIRED" id="ERR_CONSTRUCT_CALL_REQUIRED">#</a></span></h3> <p>A constructor for a class was called without <code>new</code>.</p> <p><a id="ERR_CPU_USAGE"></a></p> <h3>ERR_CPU_USAGE<span><a class="mark" href="#errors_err_cpu_usage" id="errors_err_cpu_usage">#</a></span><span><a class="mark" href="#ERR_CPU_USAGE" id="ERR_CPU_USAGE">#</a></span></h3> <p>The native call from <code>process.cpuUsage</code> could not be processed.</p> <p><a id="ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED"></a></p> <h3>ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED<span><a class="mark" href="#errors_err_crypto_custom_engine_not_supported" id="errors_err_crypto_custom_engine_not_supported">#</a></span><span><a class="mark" href="#ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED" id="ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED">#</a></span></h3> <p>A client certificate engine was requested that is not supported by the version of OpenSSL being used.</p> <p><a id="ERR_CRYPTO_ECDH_INVALID_FORMAT"></a></p> <h3>ERR_CRYPTO_ECDH_INVALID_FORMAT<span><a class="mark" href="#errors_err_crypto_ecdh_invalid_format" id="errors_err_crypto_ecdh_invalid_format">#</a></span><span><a class="mark" href="#ERR_CRYPTO_ECDH_INVALID_FORMAT" id="ERR_CRYPTO_ECDH_INVALID_FORMAT">#</a></span></h3> <p>An invalid value for the <code>format</code> argument was passed to the <code>crypto.ECDH()</code> class <code>getPublicKey()</code> method.</p> <p><a id="ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY"></a></p> <h3>ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY<span><a class="mark" href="#errors_err_crypto_ecdh_invalid_public_key" id="errors_err_crypto_ecdh_invalid_public_key">#</a></span><span><a class="mark" href="#ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY" id="ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY">#</a></span></h3> <p>An invalid value for the <code>key</code> argument has been passed to the <code>crypto.ECDH()</code> class <code>computeSecret()</code> method. It means that the public key lies outside of the elliptic curve.</p> <p><a id="ERR_CRYPTO_ENGINE_UNKNOWN"></a></p> <h3>ERR_CRYPTO_ENGINE_UNKNOWN<span><a class="mark" href="#errors_err_crypto_engine_unknown" id="errors_err_crypto_engine_unknown">#</a></span><span><a class="mark" href="#ERR_CRYPTO_ENGINE_UNKNOWN" id="ERR_CRYPTO_ENGINE_UNKNOWN">#</a></span></h3> <p>An invalid crypto engine identifier was passed to <a href="#crypto_crypto_setengine_engine_flags"><code>require('crypto').setEngine()</code></a>.</p> <p><a id="ERR_CRYPTO_FIPS_FORCED"></a></p> <h3>ERR_CRYPTO_FIPS_FORCED<span><a class="mark" href="#errors_err_crypto_fips_forced" id="errors_err_crypto_fips_forced">#</a></span><span><a class="mark" href="#ERR_CRYPTO_FIPS_FORCED" id="ERR_CRYPTO_FIPS_FORCED">#</a></span></h3> <p>The <a href="#cli_force_fips"><code>--force-fips</code></a> command-line argument was used but there was an attempt to enable or disable FIPS mode in the <code>crypto</code> module.</p> <p><a id="ERR_CRYPTO_FIPS_UNAVAILABLE"></a></p> <h3>ERR_CRYPTO_FIPS_UNAVAILABLE<span><a class="mark" href="#errors_err_crypto_fips_unavailable" id="errors_err_crypto_fips_unavailable">#</a></span><span><a class="mark" href="#ERR_CRYPTO_FIPS_UNAVAILABLE" id="ERR_CRYPTO_FIPS_UNAVAILABLE">#</a></span></h3> <p>An attempt was made to enable or disable FIPS mode, but FIPS mode was not available.</p> <p><a id="ERR_CRYPTO_HASH_DIGEST_NO_UTF16"></a></p> <h3>ERR_CRYPTO_HASH_DIGEST_NO_UTF16<span><a class="mark" href="#errors_err_crypto_hash_digest_no_utf16" id="errors_err_crypto_hash_digest_no_utf16">#</a></span><span><a class="mark" href="#ERR_CRYPTO_HASH_DIGEST_NO_UTF16" id="ERR_CRYPTO_HASH_DIGEST_NO_UTF16">#</a></span></h3> <p>The UTF-16 encoding was used with <a href="#crypto_hash_digest_encoding"><code>hash.digest()</code></a>. While the <code>hash.digest()</code> method does allow an <code>encoding</code> argument to be passed in, causing the method to return a string rather than a <code>Buffer</code>, the UTF-16 encoding (e.g. <code>ucs</code> or <code>utf16le</code>) is not supported.</p> <p><a id="ERR_CRYPTO_HASH_FINALIZED"></a></p> <h3>ERR_CRYPTO_HASH_FINALIZED<span><a class="mark" href="#errors_err_crypto_hash_finalized" id="errors_err_crypto_hash_finalized">#</a></span><span><a class="mark" href="#ERR_CRYPTO_HASH_FINALIZED" id="ERR_CRYPTO_HASH_FINALIZED">#</a></span></h3> <p><a href="#crypto_hash_digest_encoding"><code>hash.digest()</code></a> was called multiple times. The <code>hash.digest()</code> method must be called no more than one time per instance of a <code>Hash</code> object.</p> <p><a id="ERR_CRYPTO_HASH_UPDATE_FAILED"></a></p> <h3>ERR_CRYPTO_HASH_UPDATE_FAILED<span><a class="mark" href="#errors_err_crypto_hash_update_failed" id="errors_err_crypto_hash_update_failed">#</a></span><span><a class="mark" href="#ERR_CRYPTO_HASH_UPDATE_FAILED" id="ERR_CRYPTO_HASH_UPDATE_FAILED">#</a></span></h3> <p><a href="#crypto_hash_update_data_inputencoding"><code>hash.update()</code></a> failed for any reason. This should rarely, if ever, happen.</p> <p><a id="ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS"></a></p> <h3>ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS<span><a class="mark" href="#errors_err_crypto_incompatible_key_options" id="errors_err_crypto_incompatible_key_options">#</a></span><span><a class="mark" href="#ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS" id="ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS">#</a></span></h3> <p>The selected public or private key encoding is incompatible with other options.</p> <p><a id="ERR_CRYPTO_INVALID_DIGEST"></a></p> <h3>ERR_CRYPTO_INVALID_DIGEST<span><a class="mark" href="#errors_err_crypto_invalid_digest" id="errors_err_crypto_invalid_digest">#</a></span><span><a class="mark" href="#ERR_CRYPTO_INVALID_DIGEST" id="ERR_CRYPTO_INVALID_DIGEST">#</a></span></h3> <p>An invalid <a href="#crypto_crypto_gethashes">crypto digest algorithm</a> was specified.</p> <p><a id="ERR_CRYPTO_INVALID_STATE"></a></p> <h3>ERR_CRYPTO_INVALID_STATE<span><a class="mark" href="#errors_err_crypto_invalid_state" id="errors_err_crypto_invalid_state">#</a></span><span><a class="mark" href="#ERR_CRYPTO_INVALID_STATE" id="ERR_CRYPTO_INVALID_STATE">#</a></span></h3> <p>A crypto method was used on an object that was in an invalid state. For instance, calling <a href="#crypto_cipher_getauthtag"><code>cipher.getAuthTag()</code></a> before calling <code>cipher.final()</code>.</p> <p><a id="ERR_CRYPTO_PBKDF2_ERROR"></a></p> <h3>ERR_CRYPTO_PBKDF2_ERROR<span><a class="mark" href="#errors_err_crypto_pbkdf2_error" id="errors_err_crypto_pbkdf2_error">#</a></span><span><a class="mark" href="#ERR_CRYPTO_PBKDF2_ERROR" id="ERR_CRYPTO_PBKDF2_ERROR">#</a></span></h3> <p>The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide more details and therefore neither does Node.js.</p> <p><a id="ERR_CRYPTO_SCRYPT_INVALID_PARAMETER"></a></p> <h3>ERR_CRYPTO_SCRYPT_INVALID_PARAMETER<span><a class="mark" href="#errors_err_crypto_scrypt_invalid_parameter" id="errors_err_crypto_scrypt_invalid_parameter">#</a></span><span><a class="mark" href="#ERR_CRYPTO_SCRYPT_INVALID_PARAMETER" id="ERR_CRYPTO_SCRYPT_INVALID_PARAMETER">#</a></span></h3> <p>One or more <a href="#crypto_crypto_scrypt_password_salt_keylen_options_callback"><code>crypto.scrypt()</code></a> or <a href="#crypto_crypto_scryptsync_password_salt_keylen_options"><code>crypto.scryptSync()</code></a> parameters are outside their legal range.</p> <p><a id="ERR_CRYPTO_SCRYPT_NOT_SUPPORTED"></a></p> <h3>ERR_CRYPTO_SCRYPT_NOT_SUPPORTED<span><a class="mark" href="#errors_err_crypto_scrypt_not_supported" id="errors_err_crypto_scrypt_not_supported">#</a></span><span><a class="mark" href="#ERR_CRYPTO_SCRYPT_NOT_SUPPORTED" id="ERR_CRYPTO_SCRYPT_NOT_SUPPORTED">#</a></span></h3> <p>Node.js was compiled without <code>scrypt</code> support. Not possible with the official release binaries but can happen with custom builds, including distro builds.</p> <p><a id="ERR_CRYPTO_SIGN_KEY_REQUIRED"></a></p> <h3>ERR_CRYPTO_SIGN_KEY_REQUIRED<span><a class="mark" href="#errors_err_crypto_sign_key_required" id="errors_err_crypto_sign_key_required">#</a></span><span><a class="mark" href="#ERR_CRYPTO_SIGN_KEY_REQUIRED" id="ERR_CRYPTO_SIGN_KEY_REQUIRED">#</a></span></h3> <p>A signing <code>key</code> was not provided to the <a href="#crypto_sign_sign_privatekey_outputencoding"><code>sign.sign()</code></a> method.</p> <p><a id="ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH"></a></p> <h3>ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH<span><a class="mark" href="#errors_err_crypto_timing_safe_equal_length" id="errors_err_crypto_timing_safe_equal_length">#</a></span><span><a class="mark" href="#ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH" id="ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH">#</a></span></h3> <p><a href="#crypto_crypto_timingsafeequal_a_b"><code>crypto.timingSafeEqual()</code></a> was called with <code>Buffer</code>, <code>TypedArray</code>, or <code>DataView</code> arguments of different lengths.</p> <p><a id="ERR_DNS_SET_SERVERS_FAILED"></a></p> <h3>ERR_DNS_SET_SERVERS_FAILED<span><a class="mark" href="#errors_err_dns_set_servers_failed" id="errors_err_dns_set_servers_failed">#</a></span><span><a class="mark" href="#ERR_DNS_SET_SERVERS_FAILED" id="ERR_DNS_SET_SERVERS_FAILED">#</a></span></h3> <p><code>c-ares</code> failed to set the DNS server.</p> <p><a id="ERR_DOMAIN_CALLBACK_NOT_AVAILABLE"></a></p> <h3>ERR_DOMAIN_CALLBACK_NOT_AVAILABLE<span><a class="mark" href="#errors_err_domain_callback_not_available" id="errors_err_domain_callback_not_available">#</a></span><span><a class="mark" href="#ERR_DOMAIN_CALLBACK_NOT_AVAILABLE" id="ERR_DOMAIN_CALLBACK_NOT_AVAILABLE">#</a></span></h3> <p>The <code>domain</code> module was not usable since it could not establish the required error handling hooks, because <a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> had been called at an earlier point in time.</p> <p><a id="ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE"></a></p> <h3>ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE<span><a class="mark" href="#errors_err_domain_cannot_set_uncaught_exception_capture" id="errors_err_domain_cannot_set_uncaught_exception_capture">#</a></span><span><a class="mark" href="#ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE" id="ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE">#</a></span></h3> <p><a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> could not be called because the <code>domain</code> module has been loaded at an earlier point in time.</p> <p>The stack trace is extended to include the point in time at which the <code>domain</code> module had been loaded.</p> <p><a id="ERR_ENCODING_INVALID_ENCODED_DATA"></a></p> <h3>ERR_ENCODING_INVALID_ENCODED_DATA<span><a class="mark" href="#errors_err_encoding_invalid_encoded_data" id="errors_err_encoding_invalid_encoded_data">#</a></span><span><a class="mark" href="#ERR_ENCODING_INVALID_ENCODED_DATA" id="ERR_ENCODING_INVALID_ENCODED_DATA">#</a></span></h3> <p>Data provided to <code>util.TextDecoder()</code> API was invalid according to the encoding provided.</p> <p><a id="ERR_ENCODING_NOT_SUPPORTED"></a></p> <h3>ERR_ENCODING_NOT_SUPPORTED<span><a class="mark" href="#errors_err_encoding_not_supported" id="errors_err_encoding_not_supported">#</a></span><span><a class="mark" href="#ERR_ENCODING_NOT_SUPPORTED" id="ERR_ENCODING_NOT_SUPPORTED">#</a></span></h3> <p>Encoding provided to <code>util.TextDecoder()</code> API was not one of the <a href="#util_whatwg_supported_encodings">WHATWG Supported Encodings</a>.</p> <p><a id="ERR_FALSY_VALUE_REJECTION"></a></p> <h3>ERR_FALSY_VALUE_REJECTION<span><a class="mark" href="#errors_err_falsy_value_rejection" id="errors_err_falsy_value_rejection">#</a></span><span><a class="mark" href="#ERR_FALSY_VALUE_REJECTION" id="ERR_FALSY_VALUE_REJECTION">#</a></span></h3> <p>A <code>Promise</code> that was callbackified via <code>util.callbackify()</code> was rejected with a falsy value.</p> <p><a id="ERR_FS_FILE_TOO_LARGE"></a></p> <h3>ERR_FS_FILE_TOO_LARGE<span><a class="mark" href="#errors_err_fs_file_too_large" id="errors_err_fs_file_too_large">#</a></span><span><a class="mark" href="#ERR_FS_FILE_TOO_LARGE" id="ERR_FS_FILE_TOO_LARGE">#</a></span></h3> <p>An attempt has been made to read a file whose size is larger than the maximum allowed size for a <code>Buffer</code>.</p> <p><a id="ERR_FS_INVALID_SYMLINK_TYPE"></a></p> <h3>ERR_FS_INVALID_SYMLINK_TYPE<span><a class="mark" href="#errors_err_fs_invalid_symlink_type" id="errors_err_fs_invalid_symlink_type">#</a></span><span><a class="mark" href="#ERR_FS_INVALID_SYMLINK_TYPE" id="ERR_FS_INVALID_SYMLINK_TYPE">#</a></span></h3> <p>An invalid symlink type was passed to the <a href="#fs_fs_symlink_target_path_type_callback"><code>fs.symlink()</code></a> or <a href="#fs_fs_symlinksync_target_path_type"><code>fs.symlinkSync()</code></a> methods.</p> <p><a id="ERR_HTTP_HEADERS_SENT"></a></p> <h3>ERR_HTTP_HEADERS_SENT<span><a class="mark" href="#errors_err_http_headers_sent" id="errors_err_http_headers_sent">#</a></span><span><a class="mark" href="#ERR_HTTP_HEADERS_SENT" id="ERR_HTTP_HEADERS_SENT">#</a></span></h3> <p>An attempt was made to add more headers after the headers had already been sent.</p> <p><a id="ERR_HTTP_INVALID_HEADER_VALUE"></a></p> <h3>ERR_HTTP_INVALID_HEADER_VALUE<span><a class="mark" href="#errors_err_http_invalid_header_value" id="errors_err_http_invalid_header_value">#</a></span><span><a class="mark" href="#ERR_HTTP_INVALID_HEADER_VALUE" id="ERR_HTTP_INVALID_HEADER_VALUE">#</a></span></h3> <p>An invalid HTTP header value was specified.</p> <p><a id="ERR_HTTP_INVALID_STATUS_CODE"></a></p> <h3>ERR_HTTP_INVALID_STATUS_CODE<span><a class="mark" href="#errors_err_http_invalid_status_code" id="errors_err_http_invalid_status_code">#</a></span><span><a class="mark" href="#ERR_HTTP_INVALID_STATUS_CODE" id="ERR_HTTP_INVALID_STATUS_CODE">#</a></span></h3> <p>Status code was outside the regular status code range (100-999).</p> <p><a id="ERR_HTTP_TRAILER_INVALID"></a></p> <h3>ERR_HTTP_TRAILER_INVALID<span><a class="mark" href="#errors_err_http_trailer_invalid" id="errors_err_http_trailer_invalid">#</a></span><span><a class="mark" href="#ERR_HTTP_TRAILER_INVALID" id="ERR_HTTP_TRAILER_INVALID">#</a></span></h3> <p>The <code>Trailer</code> header was set even though the transfer encoding does not support that.</p> <p><a id="ERR_HTTP2_ALTSVC_INVALID_ORIGIN"></a></p> <h3>ERR_HTTP2_ALTSVC_INVALID_ORIGIN<span><a class="mark" href="#errors_err_http2_altsvc_invalid_origin" id="errors_err_http2_altsvc_invalid_origin">#</a></span><span><a class="mark" href="#ERR_HTTP2_ALTSVC_INVALID_ORIGIN" id="ERR_HTTP2_ALTSVC_INVALID_ORIGIN">#</a></span></h3> <p>HTTP/2 ALTSVC frames require a valid origin.</p> <p><a id="ERR_HTTP2_ALTSVC_LENGTH"></a></p> <h3>ERR_HTTP2_ALTSVC_LENGTH<span><a class="mark" href="#errors_err_http2_altsvc_length" id="errors_err_http2_altsvc_length">#</a></span><span><a class="mark" href="#ERR_HTTP2_ALTSVC_LENGTH" id="ERR_HTTP2_ALTSVC_LENGTH">#</a></span></h3> <p>HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.</p> <p><a id="ERR_HTTP2_CONNECT_AUTHORITY"></a></p> <h3>ERR_HTTP2_CONNECT_AUTHORITY<span><a class="mark" href="#errors_err_http2_connect_authority" id="errors_err_http2_connect_authority">#</a></span><span><a class="mark" href="#ERR_HTTP2_CONNECT_AUTHORITY" id="ERR_HTTP2_CONNECT_AUTHORITY">#</a></span></h3> <p>For HTTP/2 requests using the <code>CONNECT</code> method, the <code>:authority</code> pseudo-header is required.</p> <p><a id="ERR_HTTP2_CONNECT_PATH"></a></p> <h3>ERR_HTTP2_CONNECT_PATH<span><a class="mark" href="#errors_err_http2_connect_path" id="errors_err_http2_connect_path">#</a></span><span><a class="mark" href="#ERR_HTTP2_CONNECT_PATH" id="ERR_HTTP2_CONNECT_PATH">#</a></span></h3> <p>For HTTP/2 requests using the <code>CONNECT</code> method, the <code>:path</code> pseudo-header is forbidden.</p> <p><a id="ERR_HTTP2_CONNECT_SCHEME"></a></p> <h3>ERR_HTTP2_CONNECT_SCHEME<span><a class="mark" href="#errors_err_http2_connect_scheme" id="errors_err_http2_connect_scheme">#</a></span><span><a class="mark" href="#ERR_HTTP2_CONNECT_SCHEME" id="ERR_HTTP2_CONNECT_SCHEME">#</a></span></h3> <p>For HTTP/2 requests using the <code>CONNECT</code> method, the <code>:scheme</code> pseudo-header is forbidden.</p> <p><a id="ERR_HTTP2_ERROR"></a></p> <h3>ERR_HTTP2_ERROR<span><a class="mark" href="#errors_err_http2_error" id="errors_err_http2_error">#</a></span><span><a class="mark" href="#ERR_HTTP2_ERROR" id="ERR_HTTP2_ERROR">#</a></span></h3> <p>A non-specific HTTP/2 error has occurred.</p> <p><a id="ERR_HTTP2_GOAWAY_SESSION"></a></p> <h3>ERR_HTTP2_GOAWAY_SESSION<span><a class="mark" href="#errors_err_http2_goaway_session" id="errors_err_http2_goaway_session">#</a></span><span><a class="mark" href="#ERR_HTTP2_GOAWAY_SESSION" id="ERR_HTTP2_GOAWAY_SESSION">#</a></span></h3> <p>New HTTP/2 Streams may not be opened after the <code>Http2Session</code> has received a <code>GOAWAY</code> frame from the connected peer.</p> <p><a id="ERR_HTTP2_HEADERS_AFTER_RESPOND"></a></p> <h3>ERR_HTTP2_HEADERS_AFTER_RESPOND<span><a class="mark" href="#errors_err_http2_headers_after_respond" id="errors_err_http2_headers_after_respond">#</a></span><span><a class="mark" href="#ERR_HTTP2_HEADERS_AFTER_RESPOND" id="ERR_HTTP2_HEADERS_AFTER_RESPOND">#</a></span></h3> <p>An additional headers was specified after an HTTP/2 response was initiated.</p> <p><a id="ERR_HTTP2_HEADERS_SENT"></a></p> <h3>ERR_HTTP2_HEADERS_SENT<span><a class="mark" href="#errors_err_http2_headers_sent" id="errors_err_http2_headers_sent">#</a></span><span><a class="mark" href="#ERR_HTTP2_HEADERS_SENT" id="ERR_HTTP2_HEADERS_SENT">#</a></span></h3> <p>An attempt was made to send multiple response headers.</p> <p><a id="ERR_HTTP2_HEADER_SINGLE_VALUE"></a></p> <h3>ERR_HTTP2_HEADER_SINGLE_VALUE<span><a class="mark" href="#errors_err_http2_header_single_value" id="errors_err_http2_header_single_value">#</a></span><span><a class="mark" href="#ERR_HTTP2_HEADER_SINGLE_VALUE" id="ERR_HTTP2_HEADER_SINGLE_VALUE">#</a></span></h3> <p>Multiple values were provided for an HTTP/2 header field that was required to have only a single value.</p> <p><a id="ERR_HTTP2_INFO_STATUS_NOT_ALLOWED"></a></p> <h3>ERR_HTTP2_INFO_STATUS_NOT_ALLOWED<span><a class="mark" href="#errors_err_http2_info_status_not_allowed" id="errors_err_http2_info_status_not_allowed">#</a></span><span><a class="mark" href="#ERR_HTTP2_INFO_STATUS_NOT_ALLOWED" id="ERR_HTTP2_INFO_STATUS_NOT_ALLOWED">#</a></span></h3> <p>Informational HTTP status codes (<code>1xx</code>) may not be set as the response status code on HTTP/2 responses.</p> <p><a id="ERR_HTTP2_INVALID_CONNECTION_HEADERS"></a></p> <h3>ERR_HTTP2_INVALID_CONNECTION_HEADERS<span><a class="mark" href="#errors_err_http2_invalid_connection_headers" id="errors_err_http2_invalid_connection_headers">#</a></span><span><a class="mark" href="#ERR_HTTP2_INVALID_CONNECTION_HEADERS" id="ERR_HTTP2_INVALID_CONNECTION_HEADERS">#</a></span></h3> <p>HTTP/1 connection specific headers are forbidden to be used in HTTP/2 requests and responses.</p> <p><a id="ERR_HTTP2_INVALID_HEADER_VALUE"></a></p> <h3>ERR_HTTP2_INVALID_HEADER_VALUE<span><a class="mark" href="#errors_err_http2_invalid_header_value" id="errors_err_http2_invalid_header_value">#</a></span><span><a class="mark" href="#ERR_HTTP2_INVALID_HEADER_VALUE" id="ERR_HTTP2_INVALID_HEADER_VALUE">#</a></span></h3> <p>An invalid HTTP/2 header value was specified.</p> <p><a id="ERR_HTTP2_INVALID_INFO_STATUS"></a></p> <h3>ERR_HTTP2_INVALID_INFO_STATUS<span><a class="mark" href="#errors_err_http2_invalid_info_status" id="errors_err_http2_invalid_info_status">#</a></span><span><a class="mark" href="#ERR_HTTP2_INVALID_INFO_STATUS" id="ERR_HTTP2_INVALID_INFO_STATUS">#</a></span></h3> <p>An invalid HTTP informational status code has been specified. Informational status codes must be an integer between <code>100</code> and <code>199</code> (inclusive).</p> <p><a id="ERR_HTTP2_INVALID_ORIGIN"></a></p> <h3>ERR_HTTP2_INVALID_ORIGIN<span><a class="mark" href="#errors_err_http2_invalid_origin" id="errors_err_http2_invalid_origin">#</a></span><span><a class="mark" href="#ERR_HTTP2_INVALID_ORIGIN" id="ERR_HTTP2_INVALID_ORIGIN">#</a></span></h3> <p>HTTP/2 <code>ORIGIN</code> frames require a valid origin.</p> <p><a id="ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH"></a></p> <h3>ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH<span><a class="mark" href="#errors_err_http2_invalid_packed_settings_length" id="errors_err_http2_invalid_packed_settings_length">#</a></span><span><a class="mark" href="#ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH" id="ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH">#</a></span></h3> <p>Input <code>Buffer</code> and <code>Uint8Array</code> instances passed to the <code>http2.getUnpackedSettings()</code> API must have a length that is a multiple of six.</p> <p><a id="ERR_HTTP2_INVALID_PSEUDOHEADER"></a></p> <h3>ERR_HTTP2_INVALID_PSEUDOHEADER<span><a class="mark" href="#errors_err_http2_invalid_pseudoheader" id="errors_err_http2_invalid_pseudoheader">#</a></span><span><a class="mark" href="#ERR_HTTP2_INVALID_PSEUDOHEADER" id="ERR_HTTP2_INVALID_PSEUDOHEADER">#</a></span></h3> <p>Only valid HTTP/2 pseudoheaders (<code>:status</code>, <code>:path</code>, <code>:authority</code>, <code>:scheme</code>, and <code>:method</code>) may be used.</p> <p><a id="ERR_HTTP2_INVALID_SESSION"></a></p> <h3>ERR_HTTP2_INVALID_SESSION<span><a class="mark" href="#errors_err_http2_invalid_session" id="errors_err_http2_invalid_session">#</a></span><span><a class="mark" href="#ERR_HTTP2_INVALID_SESSION" id="ERR_HTTP2_INVALID_SESSION">#</a></span></h3> <p>An action was performed on an <code>Http2Session</code> object that had already been destroyed.</p> <p><a id="ERR_HTTP2_INVALID_SETTING_VALUE"></a></p> <h3>ERR_HTTP2_INVALID_SETTING_VALUE<span><a class="mark" href="#errors_err_http2_invalid_setting_value" id="errors_err_http2_invalid_setting_value">#</a></span><span><a class="mark" href="#ERR_HTTP2_INVALID_SETTING_VALUE" id="ERR_HTTP2_INVALID_SETTING_VALUE">#</a></span></h3> <p>An invalid value has been specified for an HTTP/2 setting.</p> <p><a id="ERR_HTTP2_INVALID_STREAM"></a></p> <h3>ERR_HTTP2_INVALID_STREAM<span><a class="mark" href="#errors_err_http2_invalid_stream" id="errors_err_http2_invalid_stream">#</a></span><span><a class="mark" href="#ERR_HTTP2_INVALID_STREAM" id="ERR_HTTP2_INVALID_STREAM">#</a></span></h3> <p>An operation was performed on a stream that had already been destroyed.</p> <p><a id="ERR_HTTP2_MAX_PENDING_SETTINGS_ACK"></a></p> <h3>ERR_HTTP2_MAX_PENDING_SETTINGS_ACK<span><a class="mark" href="#errors_err_http2_max_pending_settings_ack" id="errors_err_http2_max_pending_settings_ack">#</a></span><span><a class="mark" href="#ERR_HTTP2_MAX_PENDING_SETTINGS_ACK" id="ERR_HTTP2_MAX_PENDING_SETTINGS_ACK">#</a></span></h3> <p>Whenever an HTTP/2 <code>SETTINGS</code> frame is sent to a connected peer, the peer is required to send an acknowledgment that it has received and applied the new <code>SETTINGS</code>. By default, a maximum number of unacknowledged <code>SETTINGS</code> frames may be sent at any given time. This error code is used when that limit has been reached.</p> <p><a id="ERR_HTTP2_NESTED_PUSH"></a></p> <h3>ERR_HTTP2_NESTED_PUSH<span><a class="mark" href="#errors_err_http2_nested_push" id="errors_err_http2_nested_push">#</a></span><span><a class="mark" href="#ERR_HTTP2_NESTED_PUSH" id="ERR_HTTP2_NESTED_PUSH">#</a></span></h3> <p>An attempt was made to initiate a new push stream from within a push stream. Nested push streams are not permitted.</p> <p><a id="ERR_HTTP2_NO_SOCKET_MANIPULATION"></a></p> <h3>ERR_HTTP2_NO_SOCKET_MANIPULATION<span><a class="mark" href="#errors_err_http2_no_socket_manipulation" id="errors_err_http2_no_socket_manipulation">#</a></span><span><a class="mark" href="#ERR_HTTP2_NO_SOCKET_MANIPULATION" id="ERR_HTTP2_NO_SOCKET_MANIPULATION">#</a></span></h3> <p>An attempt was made to directly manipulate (read, write, pause, resume, etc.) a socket attached to an <code>Http2Session</code>.</p> <p><a id="ERR_HTTP2_ORIGIN_LENGTH"></a></p> <h3>ERR_HTTP2_ORIGIN_LENGTH<span><a class="mark" href="#errors_err_http2_origin_length" id="errors_err_http2_origin_length">#</a></span><span><a class="mark" href="#ERR_HTTP2_ORIGIN_LENGTH" id="ERR_HTTP2_ORIGIN_LENGTH">#</a></span></h3> <p>HTTP/2 <code>ORIGIN</code> frames are limited to a length of 16382 bytes.</p> <p><a id="ERR_HTTP2_OUT_OF_STREAMS"></a></p> <h3>ERR_HTTP2_OUT_OF_STREAMS<span><a class="mark" href="#errors_err_http2_out_of_streams" id="errors_err_http2_out_of_streams">#</a></span><span><a class="mark" href="#ERR_HTTP2_OUT_OF_STREAMS" id="ERR_HTTP2_OUT_OF_STREAMS">#</a></span></h3> <p>The number of streams created on a single HTTP/2 session reached the maximum limit.</p> <p><a id="ERR_HTTP2_PAYLOAD_FORBIDDEN"></a></p> <h3>ERR_HTTP2_PAYLOAD_FORBIDDEN<span><a class="mark" href="#errors_err_http2_payload_forbidden" id="errors_err_http2_payload_forbidden">#</a></span><span><a class="mark" href="#ERR_HTTP2_PAYLOAD_FORBIDDEN" id="ERR_HTTP2_PAYLOAD_FORBIDDEN">#</a></span></h3> <p>A message payload was specified for an HTTP response code for which a payload is forbidden.</p> <p><a id="ERR_HTTP2_PING_CANCEL"></a></p> <h3>ERR_HTTP2_PING_CANCEL<span><a class="mark" href="#errors_err_http2_ping_cancel" id="errors_err_http2_ping_cancel">#</a></span><span><a class="mark" href="#ERR_HTTP2_PING_CANCEL" id="ERR_HTTP2_PING_CANCEL">#</a></span></h3> <p>An HTTP/2 ping was canceled.</p> <p><a id="ERR_HTTP2_PING_LENGTH"></a></p> <h3>ERR_HTTP2_PING_LENGTH<span><a class="mark" href="#errors_err_http2_ping_length" id="errors_err_http2_ping_length">#</a></span><span><a class="mark" href="#ERR_HTTP2_PING_LENGTH" id="ERR_HTTP2_PING_LENGTH">#</a></span></h3> <p>HTTP/2 ping payloads must be exactly 8 bytes in length.</p> <p><a id="ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED"></a></p> <h3>ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED<span><a class="mark" href="#errors_err_http2_pseudoheader_not_allowed" id="errors_err_http2_pseudoheader_not_allowed">#</a></span><span><a class="mark" href="#ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED" id="ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED">#</a></span></h3> <p>An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header key names that begin with the <code>:</code> prefix.</p> <p><a id="ERR_HTTP2_PUSH_DISABLED"></a></p> <h3>ERR_HTTP2_PUSH_DISABLED<span><a class="mark" href="#errors_err_http2_push_disabled" id="errors_err_http2_push_disabled">#</a></span><span><a class="mark" href="#ERR_HTTP2_PUSH_DISABLED" id="ERR_HTTP2_PUSH_DISABLED">#</a></span></h3> <p>An attempt was made to create a push stream, which had been disabled by the client.</p> <p><a id="ERR_HTTP2_SEND_FILE"></a></p> <h3>ERR_HTTP2_SEND_FILE<span><a class="mark" href="#errors_err_http2_send_file" id="errors_err_http2_send_file">#</a></span><span><a class="mark" href="#ERR_HTTP2_SEND_FILE" id="ERR_HTTP2_SEND_FILE">#</a></span></h3> <p>An attempt was made to use the <code>Http2Stream.prototype.responseWithFile()</code> API to send a directory.</p> <p><a id="ERR_HTTP2_SEND_FILE_NOSEEK"></a></p> <h3>ERR_HTTP2_SEND_FILE_NOSEEK<span><a class="mark" href="#errors_err_http2_send_file_noseek" id="errors_err_http2_send_file_noseek">#</a></span><span><a class="mark" href="#ERR_HTTP2_SEND_FILE_NOSEEK" id="ERR_HTTP2_SEND_FILE_NOSEEK">#</a></span></h3> <p>An attempt was made to use the <code>Http2Stream.prototype.responseWithFile()</code> API to send something other than a regular file, but <code>offset</code> or <code>length</code> options were provided.</p> <p><a id="ERR_HTTP2_SESSION_ERROR"></a></p> <h3>ERR_HTTP2_SESSION_ERROR<span><a class="mark" href="#errors_err_http2_session_error" id="errors_err_http2_session_error">#</a></span><span><a class="mark" href="#ERR_HTTP2_SESSION_ERROR" id="ERR_HTTP2_SESSION_ERROR">#</a></span></h3> <p>The <code>Http2Session</code> closed with a non-zero error code.</p> <p><a id="ERR_HTTP2_SETTINGS_CANCEL"></a></p> <h3>ERR_HTTP2_SETTINGS_CANCEL<span><a class="mark" href="#errors_err_http2_settings_cancel" id="errors_err_http2_settings_cancel">#</a></span><span><a class="mark" href="#ERR_HTTP2_SETTINGS_CANCEL" id="ERR_HTTP2_SETTINGS_CANCEL">#</a></span></h3> <p>The <code>Http2Session</code> settings canceled.</p> <p><a id="ERR_HTTP2_SOCKET_BOUND"></a></p> <h3>ERR_HTTP2_SOCKET_BOUND<span><a class="mark" href="#errors_err_http2_socket_bound" id="errors_err_http2_socket_bound">#</a></span><span><a class="mark" href="#ERR_HTTP2_SOCKET_BOUND" id="ERR_HTTP2_SOCKET_BOUND">#</a></span></h3> <p>An attempt was made to connect a <code>Http2Session</code> object to a <code>net.Socket</code> or <code>tls.TLSSocket</code> that had already been bound to another <code>Http2Session</code> object.</p> <p><a id="ERR_HTTP2_SOCKET_UNBOUND"></a></p> <h3>ERR_HTTP2_SOCKET_UNBOUND<span><a class="mark" href="#errors_err_http2_socket_unbound" id="errors_err_http2_socket_unbound">#</a></span><span><a class="mark" href="#ERR_HTTP2_SOCKET_UNBOUND" id="ERR_HTTP2_SOCKET_UNBOUND">#</a></span></h3> <p>An attempt was made to use the <code>socket</code> property of an <code>Http2Session</code> that has already been closed.</p> <p><a id="ERR_HTTP2_STATUS_101"></a></p> <h3>ERR_HTTP2_STATUS_101<span><a class="mark" href="#errors_err_http2_status_101" id="errors_err_http2_status_101">#</a></span><span><a class="mark" href="#ERR_HTTP2_STATUS_101" id="ERR_HTTP2_STATUS_101">#</a></span></h3> <p>Use of the <code>101</code> Informational status code is forbidden in HTTP/2.</p> <p><a id="ERR_HTTP2_STATUS_INVALID"></a></p> <h3>ERR_HTTP2_STATUS_INVALID<span><a class="mark" href="#errors_err_http2_status_invalid" id="errors_err_http2_status_invalid">#</a></span><span><a class="mark" href="#ERR_HTTP2_STATUS_INVALID" id="ERR_HTTP2_STATUS_INVALID">#</a></span></h3> <p>An invalid HTTP status code has been specified. Status codes must be an integer between <code>100</code> and <code>599</code> (inclusive).</p> <p><a id="ERR_HTTP2_STREAM_CANCEL"></a></p> <h3>ERR_HTTP2_STREAM_CANCEL<span><a class="mark" href="#errors_err_http2_stream_cancel" id="errors_err_http2_stream_cancel">#</a></span><span><a class="mark" href="#ERR_HTTP2_STREAM_CANCEL" id="ERR_HTTP2_STREAM_CANCEL">#</a></span></h3> <p>An <code>Http2Stream</code> was destroyed before any data was transmitted to the connected peer.</p> <p><a id="ERR_HTTP2_STREAM_ERROR"></a></p> <h3>ERR_HTTP2_STREAM_ERROR<span><a class="mark" href="#errors_err_http2_stream_error" id="errors_err_http2_stream_error">#</a></span><span><a class="mark" href="#ERR_HTTP2_STREAM_ERROR" id="ERR_HTTP2_STREAM_ERROR">#</a></span></h3> <p>A non-zero error code was been specified in an <code>RST_STREAM</code> frame.</p> <p><a id="ERR_HTTP2_STREAM_SELF_DEPENDENCY"></a></p> <h3>ERR_HTTP2_STREAM_SELF_DEPENDENCY<span><a class="mark" href="#errors_err_http2_stream_self_dependency" id="errors_err_http2_stream_self_dependency">#</a></span><span><a class="mark" href="#ERR_HTTP2_STREAM_SELF_DEPENDENCY" id="ERR_HTTP2_STREAM_SELF_DEPENDENCY">#</a></span></h3> <p>When setting the priority for an HTTP/2 stream, the stream may be marked as a dependency for a parent stream. This error code is used when an attempt is made to mark a stream and dependent of itself.</p> <p><a id="ERR_HTTP2_TRAILERS_ALREADY_SENT"></a></p> <h3>ERR_HTTP2_TRAILERS_ALREADY_SENT<span><a class="mark" href="#errors_err_http2_trailers_already_sent" id="errors_err_http2_trailers_already_sent">#</a></span><span><a class="mark" href="#ERR_HTTP2_TRAILERS_ALREADY_SENT" id="ERR_HTTP2_TRAILERS_ALREADY_SENT">#</a></span></h3> <p>Trailing headers have already been sent on the <code>Http2Stream</code>.</p> <p><a id="ERR_HTTP2_TRAILERS_NOT_READY"></a></p> <h3>ERR_HTTP2_TRAILERS_NOT_READY<span><a class="mark" href="#errors_err_http2_trailers_not_ready" id="errors_err_http2_trailers_not_ready">#</a></span><span><a class="mark" href="#ERR_HTTP2_TRAILERS_NOT_READY" id="ERR_HTTP2_TRAILERS_NOT_READY">#</a></span></h3> <p>The <code>http2stream.sendTrailers()</code> method cannot be called until after the <code>'wantTrailers'</code> event is emitted on an <code>Http2Stream</code> object. The <code>'wantTrailers'</code> event will only be emitted if the <code>waitForTrailers</code> option is set for the <code>Http2Stream</code>.</p> <p><a id="ERR_HTTP2_UNSUPPORTED_PROTOCOL"></a></p> <h3>ERR_HTTP2_UNSUPPORTED_PROTOCOL<span><a class="mark" href="#errors_err_http2_unsupported_protocol" id="errors_err_http2_unsupported_protocol">#</a></span><span><a class="mark" href="#ERR_HTTP2_UNSUPPORTED_PROTOCOL" id="ERR_HTTP2_UNSUPPORTED_PROTOCOL">#</a></span></h3> <p><code>http2.connect()</code> was passed a URL that uses any protocol other than <code>http:</code> or <code>https:</code>.</p> <p><a id="ERR_INDEX_OUT_OF_RANGE"></a></p> <h3>ERR_INDEX_OUT_OF_RANGE<span><a class="mark" href="#errors_err_index_out_of_range" id="errors_err_index_out_of_range">#</a></span><span><a class="mark" href="#ERR_INDEX_OUT_OF_RANGE" id="ERR_INDEX_OUT_OF_RANGE">#</a></span></h3> <p>A given index was out of the accepted range (e.g. negative offsets).</p> <p><a id="ERR_INSPECTOR_ALREADY_CONNECTED"></a></p> <h3>ERR_INSPECTOR_ALREADY_CONNECTED<span><a class="mark" href="#errors_err_inspector_already_connected" id="errors_err_inspector_already_connected">#</a></span><span><a class="mark" href="#ERR_INSPECTOR_ALREADY_CONNECTED" id="ERR_INSPECTOR_ALREADY_CONNECTED">#</a></span></h3> <p>While using the <code>inspector</code> module, an attempt was made to connect when the inspector was already connected.</p> <p><a id="ERR_INSPECTOR_CLOSED"></a></p> <h3>ERR_INSPECTOR_CLOSED<span><a class="mark" href="#errors_err_inspector_closed" id="errors_err_inspector_closed">#</a></span><span><a class="mark" href="#ERR_INSPECTOR_CLOSED" id="ERR_INSPECTOR_CLOSED">#</a></span></h3> <p>While using the <code>inspector</code> module, an attempt was made to use the inspector after the session had already closed.</p> <p><a id="ERR_INSPECTOR_NOT_AVAILABLE"></a></p> <h3>ERR_INSPECTOR_NOT_AVAILABLE<span><a class="mark" href="#errors_err_inspector_not_available" id="errors_err_inspector_not_available">#</a></span><span><a class="mark" href="#ERR_INSPECTOR_NOT_AVAILABLE" id="ERR_INSPECTOR_NOT_AVAILABLE">#</a></span></h3> <p>The <code>inspector</code> module is not available for use.</p> <p><a id="ERR_INSPECTOR_NOT_CONNECTED"></a></p> <h3>ERR_INSPECTOR_NOT_CONNECTED<span><a class="mark" href="#errors_err_inspector_not_connected" id="errors_err_inspector_not_connected">#</a></span><span><a class="mark" href="#ERR_INSPECTOR_NOT_CONNECTED" id="ERR_INSPECTOR_NOT_CONNECTED">#</a></span></h3> <p>While using the <code>inspector</code> module, an attempt was made to use the inspector before it was connected.</p> <p><a id="ERR_INVALID_ADDRESS_FAMILY"></a></p> <h3>ERR_INVALID_ADDRESS_FAMILY<span><a class="mark" href="#errors_err_invalid_address_family" id="errors_err_invalid_address_family">#</a></span><span><a class="mark" href="#ERR_INVALID_ADDRESS_FAMILY" id="ERR_INVALID_ADDRESS_FAMILY">#</a></span></h3> <p>The provided address family is not understood by the Node.js API.</p> <p><a id="ERR_INVALID_ARG_TYPE"></a></p> <h3>ERR_INVALID_ARG_TYPE<span><a class="mark" href="#errors_err_invalid_arg_type" id="errors_err_invalid_arg_type">#</a></span><span><a class="mark" href="#ERR_INVALID_ARG_TYPE" id="ERR_INVALID_ARG_TYPE">#</a></span></h3> <p>An argument of the wrong type was passed to a Node.js API.</p> <p><a id="ERR_INVALID_ARG_VALUE"></a></p> <h3>ERR_INVALID_ARG_VALUE<span><a class="mark" href="#errors_err_invalid_arg_value" id="errors_err_invalid_arg_value">#</a></span><span><a class="mark" href="#ERR_INVALID_ARG_VALUE" id="ERR_INVALID_ARG_VALUE">#</a></span></h3> <p>An invalid or unsupported value was passed for a given argument.</p> <p><a id="ERR_INVALID_ARRAY_LENGTH"></a></p> <h3>ERR_INVALID_ARRAY_LENGTH<span><a class="mark" href="#errors_err_invalid_array_length" id="errors_err_invalid_array_length">#</a></span><span><a class="mark" href="#ERR_INVALID_ARRAY_LENGTH" id="ERR_INVALID_ARRAY_LENGTH">#</a></span></h3> <p>An array was not of the expected length or in a valid range.</p> <p><a id="ERR_INVALID_ASYNC_ID"></a></p> <h3>ERR_INVALID_ASYNC_ID<span><a class="mark" href="#errors_err_invalid_async_id" id="errors_err_invalid_async_id">#</a></span><span><a class="mark" href="#ERR_INVALID_ASYNC_ID" id="ERR_INVALID_ASYNC_ID">#</a></span></h3> <p>An invalid <code>asyncId</code> or <code>triggerAsyncId</code> was passed using <code>AsyncHooks</code>. An id less than -1 should never happen.</p> <p><a id="ERR_INVALID_BUFFER_SIZE"></a></p> <h3>ERR_INVALID_BUFFER_SIZE<span><a class="mark" href="#errors_err_invalid_buffer_size" id="errors_err_invalid_buffer_size">#</a></span><span><a class="mark" href="#ERR_INVALID_BUFFER_SIZE" id="ERR_INVALID_BUFFER_SIZE">#</a></span></h3> <p>A swap was performed on a <code>Buffer</code> but its size was not compatible with the operation.</p> <p><a id="ERR_INVALID_CALLBACK"></a></p> <h3>ERR_INVALID_CALLBACK<span><a class="mark" href="#errors_err_invalid_callback" id="errors_err_invalid_callback">#</a></span><span><a class="mark" href="#ERR_INVALID_CALLBACK" id="ERR_INVALID_CALLBACK">#</a></span></h3> <p>A callback function was required but was not been provided to a Node.js API.</p> <p><a id="ERR_INVALID_CHAR"></a></p> <h3>ERR_INVALID_CHAR<span><a class="mark" href="#errors_err_invalid_char" id="errors_err_invalid_char">#</a></span><span><a class="mark" href="#ERR_INVALID_CHAR" id="ERR_INVALID_CHAR">#</a></span></h3> <p>Invalid characters were detected in headers.</p> <p><a id="ERR_INVALID_CURSOR_POS"></a></p> <h3>ERR_INVALID_CURSOR_POS<span><a class="mark" href="#errors_err_invalid_cursor_pos" id="errors_err_invalid_cursor_pos">#</a></span><span><a class="mark" href="#ERR_INVALID_CURSOR_POS" id="ERR_INVALID_CURSOR_POS">#</a></span></h3> <p>A cursor on a given stream cannot be moved to a specified row without a specified column.</p> <p><a id="ERR_INVALID_DOMAIN_NAME"></a></p> <h3>ERR_INVALID_DOMAIN_NAME<span><a class="mark" href="#errors_err_invalid_domain_name" id="errors_err_invalid_domain_name">#</a></span><span><a class="mark" href="#ERR_INVALID_DOMAIN_NAME" id="ERR_INVALID_DOMAIN_NAME">#</a></span></h3> <p><code>hostname</code> can not be parsed from a provided URL.</p> <p><a id="ERR_INVALID_FD"></a></p> <h3>ERR_INVALID_FD<span><a class="mark" href="#errors_err_invalid_fd" id="errors_err_invalid_fd">#</a></span><span><a class="mark" href="#ERR_INVALID_FD" id="ERR_INVALID_FD">#</a></span></h3> <p>A file descriptor ('fd') was not valid (e.g. it was a negative value).</p> <p><a id="ERR_INVALID_FD_TYPE"></a></p> <h3>ERR_INVALID_FD_TYPE<span><a class="mark" href="#errors_err_invalid_fd_type" id="errors_err_invalid_fd_type">#</a></span><span><a class="mark" href="#ERR_INVALID_FD_TYPE" id="ERR_INVALID_FD_TYPE">#</a></span></h3> <p>A file descriptor ('fd') type was not valid.</p> <p><a id="ERR_INVALID_FILE_URL_HOST"></a></p> <h3>ERR_INVALID_FILE_URL_HOST<span><a class="mark" href="#errors_err_invalid_file_url_host" id="errors_err_invalid_file_url_host">#</a></span><span><a class="mark" href="#ERR_INVALID_FILE_URL_HOST" id="ERR_INVALID_FILE_URL_HOST">#</a></span></h3> <p>A Node.js API that consumes <code>file:</code> URLs (such as certain functions in the <a href="fs.html"><code>fs</code></a> module) encountered a file URL with an incompatible host. This situation can only occur on Unix-like systems where only <code>localhost</code> or an empty host is supported.</p> <p><a id="ERR_INVALID_FILE_URL_PATH"></a></p> <h3>ERR_INVALID_FILE_URL_PATH<span><a class="mark" href="#errors_err_invalid_file_url_path" id="errors_err_invalid_file_url_path">#</a></span><span><a class="mark" href="#ERR_INVALID_FILE_URL_PATH" id="ERR_INVALID_FILE_URL_PATH">#</a></span></h3> <p>A Node.js API that consumes <code>file:</code> URLs (such as certain functions in the <a href="fs.html"><code>fs</code></a> module) encountered a file URL with an incompatible path. The exact semantics for determining whether a path can be used is platform-dependent.</p> <p><a id="ERR_INVALID_HANDLE_TYPE"></a></p> <h3>ERR_INVALID_HANDLE_TYPE<span><a class="mark" href="#errors_err_invalid_handle_type" id="errors_err_invalid_handle_type">#</a></span><span><a class="mark" href="#ERR_INVALID_HANDLE_TYPE" id="ERR_INVALID_HANDLE_TYPE">#</a></span></h3> <p>An attempt was made to send an unsupported "handle" over an IPC communication channel to a child process. See <a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>subprocess.send()</code></a> and <a href="#process_process_send_message_sendhandle_options_callback"><code>process.send()</code></a> for more information.</p> <p><a id="ERR_INVALID_HTTP_TOKEN"></a></p> <h3>ERR_INVALID_HTTP_TOKEN<span><a class="mark" href="#errors_err_invalid_http_token" id="errors_err_invalid_http_token">#</a></span><span><a class="mark" href="#ERR_INVALID_HTTP_TOKEN" id="ERR_INVALID_HTTP_TOKEN">#</a></span></h3> <p>An invalid HTTP token was supplied.</p> <p><a id="ERR_INVALID_IP_ADDRESS"></a></p> <h3>ERR_INVALID_IP_ADDRESS<span><a class="mark" href="#errors_err_invalid_ip_address" id="errors_err_invalid_ip_address">#</a></span><span><a class="mark" href="#ERR_INVALID_IP_ADDRESS" id="ERR_INVALID_IP_ADDRESS">#</a></span></h3> <p>An IP address is not valid.</p> <p><a id="ERR_INVALID_OPT_VALUE"></a></p> <h3>ERR_INVALID_OPT_VALUE<span><a class="mark" href="#errors_err_invalid_opt_value" id="errors_err_invalid_opt_value">#</a></span><span><a class="mark" href="#ERR_INVALID_OPT_VALUE" id="ERR_INVALID_OPT_VALUE">#</a></span></h3> <p>An invalid or unexpected value was passed in an options object.</p> <p><a id="ERR_INVALID_OPT_VALUE_ENCODING"></a></p> <h3>ERR_INVALID_OPT_VALUE_ENCODING<span><a class="mark" href="#errors_err_invalid_opt_value_encoding" id="errors_err_invalid_opt_value_encoding">#</a></span><span><a class="mark" href="#ERR_INVALID_OPT_VALUE_ENCODING" id="ERR_INVALID_OPT_VALUE_ENCODING">#</a></span></h3> <p>An invalid or unknown file encoding was passed.</p> <p><a id="ERR_INVALID_PERFORMANCE_MARK"></a></p> <h3>ERR_INVALID_PERFORMANCE_MARK<span><a class="mark" href="#errors_err_invalid_performance_mark" id="errors_err_invalid_performance_mark">#</a></span><span><a class="mark" href="#ERR_INVALID_PERFORMANCE_MARK" id="ERR_INVALID_PERFORMANCE_MARK">#</a></span></h3> <p>While using the Performance Timing API (<code>perf_hooks</code>), a performance mark is invalid.</p> <p><a id="ERR_INVALID_PROTOCOL"></a></p> <h3>ERR_INVALID_PROTOCOL<span><a class="mark" href="#errors_err_invalid_protocol" id="errors_err_invalid_protocol">#</a></span><span><a class="mark" href="#ERR_INVALID_PROTOCOL" id="ERR_INVALID_PROTOCOL">#</a></span></h3> <p>An invalid <code>options.protocol</code> was passed.</p> <p><a id="ERR_INVALID_REPL_EVAL_CONFIG"></a></p> <h3>ERR_INVALID_REPL_EVAL_CONFIG<span><a class="mark" href="#errors_err_invalid_repl_eval_config" id="errors_err_invalid_repl_eval_config">#</a></span><span><a class="mark" href="#ERR_INVALID_REPL_EVAL_CONFIG" id="ERR_INVALID_REPL_EVAL_CONFIG">#</a></span></h3> <p>Both <code>breakEvalOnSigint</code> and <code>eval</code> options were set in the REPL config, which is not supported.</p> <p><a id="ERR_INVALID_RETURN_PROPERTY"></a></p> <h3>ERR_INVALID_RETURN_PROPERTY<span><a class="mark" href="#errors_err_invalid_return_property" id="errors_err_invalid_return_property">#</a></span><span><a class="mark" href="#ERR_INVALID_RETURN_PROPERTY" id="ERR_INVALID_RETURN_PROPERTY">#</a></span></h3> <p>Thrown in case a function option does not provide a valid value for one of its returned object properties on execution.</p> <p><a id="ERR_INVALID_RETURN_PROPERTY_VALUE"></a></p> <h3>ERR_INVALID_RETURN_PROPERTY_VALUE<span><a class="mark" href="#errors_err_invalid_return_property_value" id="errors_err_invalid_return_property_value">#</a></span><span><a class="mark" href="#ERR_INVALID_RETURN_PROPERTY_VALUE" id="ERR_INVALID_RETURN_PROPERTY_VALUE">#</a></span></h3> <p>Thrown in case a function option does not provide an expected value type for one of its returned object properties on execution.</p> <p><a id="ERR_INVALID_RETURN_VALUE"></a></p> <h3>ERR_INVALID_RETURN_VALUE<span><a class="mark" href="#errors_err_invalid_return_value" id="errors_err_invalid_return_value">#</a></span><span><a class="mark" href="#ERR_INVALID_RETURN_VALUE" id="ERR_INVALID_RETURN_VALUE">#</a></span></h3> <p>Thrown in case a function option does not return an expected value type on execution, such as when a function is expected to return a promise.</p> <p><a id="ERR_INVALID_SYNC_FORK_INPUT"></a></p> <h3>ERR_INVALID_SYNC_FORK_INPUT<span><a class="mark" href="#errors_err_invalid_sync_fork_input" id="errors_err_invalid_sync_fork_input">#</a></span><span><a class="mark" href="#ERR_INVALID_SYNC_FORK_INPUT" id="ERR_INVALID_SYNC_FORK_INPUT">#</a></span></h3> <p>A <code>Buffer</code>, <code>TypedArray</code>, <code>DataView</code> or <code>string</code> was provided as stdio input to an asynchronous fork. See the documentation for the <a href="child_process.html"><code>child_process</code></a> module for more information.</p> <p><a id="ERR_INVALID_THIS"></a></p> <h3>ERR_INVALID_THIS<span><a class="mark" href="#errors_err_invalid_this" id="errors_err_invalid_this">#</a></span><span><a class="mark" href="#ERR_INVALID_THIS" id="ERR_INVALID_THIS">#</a></span></h3> <p>A Node.js API function was called with an incompatible <code>this</code> value.</p> <pre><code class="language-js">const urlSearchParams = new URLSearchParams('foo=bar&baz=new'); const buf = Buffer.alloc(1); urlSearchParams.has.call(buf, 'foo'); // Throws a TypeError with code 'ERR_INVALID_THIS' </code></pre> <p><a id="ERR_INVALID_TRANSFER_OBJECT"></a></p> <h3>ERR_INVALID_TRANSFER_OBJECT<span><a class="mark" href="#errors_err_invalid_transfer_object" id="errors_err_invalid_transfer_object">#</a></span><span><a class="mark" href="#ERR_INVALID_TRANSFER_OBJECT" id="ERR_INVALID_TRANSFER_OBJECT">#</a></span></h3> <p>An invalid transfer object was passed to <code>postMessage()</code>.</p> <p><a id="ERR_INVALID_TUPLE"></a></p> <h3>ERR_INVALID_TUPLE<span><a class="mark" href="#errors_err_invalid_tuple" id="errors_err_invalid_tuple">#</a></span><span><a class="mark" href="#ERR_INVALID_TUPLE" id="ERR_INVALID_TUPLE">#</a></span></h3> <p>An element in the <code>iterable</code> provided to the <a href="#url_the_whatwg_url_api">WHATWG</a> <a href="#url_constructor_new_urlsearchparams_iterable"><code>URLSearchParams</code> constructor</a> did not represent a <code>[name, value]</code> tuple – that is, if an element is not iterable, or does not consist of exactly two elements.</p> <p><a id="ERR_INVALID_URI"></a></p> <h3>ERR_INVALID_URI<span><a class="mark" href="#errors_err_invalid_uri" id="errors_err_invalid_uri">#</a></span><span><a class="mark" href="#ERR_INVALID_URI" id="ERR_INVALID_URI">#</a></span></h3> <p>An invalid URI was passed.</p> <p><a id="ERR_INVALID_URL"></a></p> <h3>ERR_INVALID_URL<span><a class="mark" href="#errors_err_invalid_url" id="errors_err_invalid_url">#</a></span><span><a class="mark" href="#ERR_INVALID_URL" id="ERR_INVALID_URL">#</a></span></h3> <p>An invalid URL was passed to the <a href="#url_the_whatwg_url_api">WHATWG</a> <a href="#url_constructor_new_url_input_base"><code>URL</code> constructor</a> to be parsed. The thrown error object typically has an additional property <code>'input'</code> that contains the URL that failed to parse.</p> <p><a id="ERR_INVALID_URL_SCHEME"></a></p> <h3>ERR_INVALID_URL_SCHEME<span><a class="mark" href="#errors_err_invalid_url_scheme" id="errors_err_invalid_url_scheme">#</a></span><span><a class="mark" href="#ERR_INVALID_URL_SCHEME" id="ERR_INVALID_URL_SCHEME">#</a></span></h3> <p>An attempt was made to use a URL of an incompatible scheme (protocol) for a specific purpose. It is only used in the <a href="#url_the_whatwg_url_api">WHATWG URL API</a> support in the <a href="fs.html"><code>fs</code></a> module (which only accepts URLs with <code>'file'</code> scheme), but may be used in other Node.js APIs as well in the future.</p> <p><a id="ERR_IPC_CHANNEL_CLOSED"></a></p> <h3>ERR_IPC_CHANNEL_CLOSED<span><a class="mark" href="#errors_err_ipc_channel_closed" id="errors_err_ipc_channel_closed">#</a></span><span><a class="mark" href="#ERR_IPC_CHANNEL_CLOSED" id="ERR_IPC_CHANNEL_CLOSED">#</a></span></h3> <p>An attempt was made to use an IPC communication channel that was already closed.</p> <p><a id="ERR_IPC_DISCONNECTED"></a></p> <h3>ERR_IPC_DISCONNECTED<span><a class="mark" href="#errors_err_ipc_disconnected" id="errors_err_ipc_disconnected">#</a></span><span><a class="mark" href="#ERR_IPC_DISCONNECTED" id="ERR_IPC_DISCONNECTED">#</a></span></h3> <p>An attempt was made to disconnect an IPC communication channel that was already disconnected. See the documentation for the <a href="child_process.html"><code>child_process</code></a> module for more information.</p> <p><a id="ERR_IPC_ONE_PIPE"></a></p> <h3>ERR_IPC_ONE_PIPE<span><a class="mark" href="#errors_err_ipc_one_pipe" id="errors_err_ipc_one_pipe">#</a></span><span><a class="mark" href="#ERR_IPC_ONE_PIPE" id="ERR_IPC_ONE_PIPE">#</a></span></h3> <p>An attempt was made to create a child Node.js process using more than one IPC communication channel. See the documentation for the <a href="child_process.html"><code>child_process</code></a> module for more information.</p> <p><a id="ERR_IPC_SYNC_FORK"></a></p> <h3>ERR_IPC_SYNC_FORK<span><a class="mark" href="#errors_err_ipc_sync_fork" id="errors_err_ipc_sync_fork">#</a></span><span><a class="mark" href="#ERR_IPC_SYNC_FORK" id="ERR_IPC_SYNC_FORK">#</a></span></h3> <p>An attempt was made to open an IPC communication channel with a synchronously forked Node.js process. See the documentation for the <a href="child_process.html"><code>child_process</code></a> module for more information.</p> <p><a id="ERR_MEMORY_ALLOCATION_FAILED"></a></p> <h3>ERR_MEMORY_ALLOCATION_FAILED<span><a class="mark" href="#errors_err_memory_allocation_failed" id="errors_err_memory_allocation_failed">#</a></span><span><a class="mark" href="#ERR_MEMORY_ALLOCATION_FAILED" id="ERR_MEMORY_ALLOCATION_FAILED">#</a></span></h3> <p>An attempt was made to allocate memory (usually in the C++ layer) but it failed.</p> <p><a id="ERR_METHOD_NOT_IMPLEMENTED"></a></p> <h3>ERR_METHOD_NOT_IMPLEMENTED<span><a class="mark" href="#errors_err_method_not_implemented" id="errors_err_method_not_implemented">#</a></span><span><a class="mark" href="#ERR_METHOD_NOT_IMPLEMENTED" id="ERR_METHOD_NOT_IMPLEMENTED">#</a></span></h3> <p>A method is required but not implemented.</p> <p><a id="ERR_MISSING_ARGS"></a></p> <h3>ERR_MISSING_ARGS<span><a class="mark" href="#errors_err_missing_args" id="errors_err_missing_args">#</a></span><span><a class="mark" href="#ERR_MISSING_ARGS" id="ERR_MISSING_ARGS">#</a></span></h3> <p>A required argument of a Node.js API was not passed. This is only used for strict compliance with the API specification (which in some cases may accept <code>func(undefined)</code> but not <code>func()</code>). In most native Node.js APIs, <code>func(undefined)</code> and <code>func()</code> are treated identically, and the <a href="#ERR_INVALID_ARG_TYPE"><code>ERR_INVALID_ARG_TYPE</code></a> error code may be used instead.</p> <p><a id="ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK"></a></p> <h3>ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK<span><a class="mark" href="#errors_err_missing_dynamic_instantiate_hook" id="errors_err_missing_dynamic_instantiate_hook">#</a></span><span><a class="mark" href="#ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK" id="ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK">#</a></span></h3> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>An <a href="esm.html">ES6 module</a> loader hook specified <code>format: 'dynamic'</code> but did not provide a <code>dynamicInstantiate</code> hook.</p> <p><a id="ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST"></a></p> <h3>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST<span><a class="mark" href="#errors_err_missing_message_port_in_transfer_list" id="errors_err_missing_message_port_in_transfer_list">#</a></span><span><a class="mark" href="#ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST" id="ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST">#</a></span></h3> <p>A <code>MessagePort</code> was found in the object passed to a <code>postMessage()</code> call, but not provided in the <code>transferList</code> for that call.</p> <p><a id="ERR_MISSING_MODULE"></a></p> <h3>ERR_MISSING_MODULE<span><a class="mark" href="#errors_err_missing_module" id="errors_err_missing_module">#</a></span><span><a class="mark" href="#ERR_MISSING_MODULE" id="ERR_MISSING_MODULE">#</a></span></h3> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>An <a href="esm.html">ES6 module</a> could not be resolved.</p> <p><a id="ERR_MISSING_PLATFORM_FOR_WORKER"></a></p> <h3>ERR_MISSING_PLATFORM_FOR_WORKER<span><a class="mark" href="#errors_err_missing_platform_for_worker" id="errors_err_missing_platform_for_worker">#</a></span><span><a class="mark" href="#ERR_MISSING_PLATFORM_FOR_WORKER" id="ERR_MISSING_PLATFORM_FOR_WORKER">#</a></span></h3> <p>The V8 platform used by this instance of Node.js does not support creating Workers. This is caused by lack of embedder support for Workers. In particular, this error will not occur with standard builds of Node.js.</p> <p><a id="ERR_MODULE_RESOLUTION_LEGACY"></a></p> <h3>ERR_MODULE_RESOLUTION_LEGACY<span><a class="mark" href="#errors_err_module_resolution_legacy" id="errors_err_module_resolution_legacy">#</a></span><span><a class="mark" href="#ERR_MODULE_RESOLUTION_LEGACY" id="ERR_MODULE_RESOLUTION_LEGACY">#</a></span></h3> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>A failure occurred resolving imports in an <a href="esm.html">ES6 module</a>.</p> <p><a id="ERR_MULTIPLE_CALLBACK"></a></p> <h3>ERR_MULTIPLE_CALLBACK<span><a class="mark" href="#errors_err_multiple_callback" id="errors_err_multiple_callback">#</a></span><span><a class="mark" href="#ERR_MULTIPLE_CALLBACK" id="ERR_MULTIPLE_CALLBACK">#</a></span></h3> <p>A callback was called more than once.</p> <p>A callback is almost always meant to only be called once as the query can either be fulfilled or rejected but not both at the same time. The latter would be possible by calling a callback more than once.</p> <p><a id="ERR_NAPI_CONS_FUNCTION"></a></p> <h3>ERR_NAPI_CONS_FUNCTION<span><a class="mark" href="#errors_err_napi_cons_function" id="errors_err_napi_cons_function">#</a></span><span><a class="mark" href="#ERR_NAPI_CONS_FUNCTION" id="ERR_NAPI_CONS_FUNCTION">#</a></span></h3> <p>While using <code>N-API</code>, a constructor passed was not a function.</p> <p><a id="ERR_NAPI_INVALID_DATAVIEW_ARGS"></a></p> <h3>ERR_NAPI_INVALID_DATAVIEW_ARGS<span><a class="mark" href="#errors_err_napi_invalid_dataview_args" id="errors_err_napi_invalid_dataview_args">#</a></span><span><a class="mark" href="#ERR_NAPI_INVALID_DATAVIEW_ARGS" id="ERR_NAPI_INVALID_DATAVIEW_ARGS">#</a></span></h3> <p>While calling <code>napi_create_dataview()</code>, a given <code>offset</code> was outside the bounds of the dataview or <code>offset + length</code> was larger than a length of given <code>buffer</code>.</p> <p><a id="ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT"></a></p> <h3>ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT<span><a class="mark" href="#errors_err_napi_invalid_typedarray_alignment" id="errors_err_napi_invalid_typedarray_alignment">#</a></span><span><a class="mark" href="#ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT" id="ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT">#</a></span></h3> <p>While calling <code>napi_create_typedarray()</code>, the provided <code>offset</code> was not a multiple of the element size.</p> <p><a id="ERR_NAPI_INVALID_TYPEDARRAY_LENGTH"></a></p> <h3>ERR_NAPI_INVALID_TYPEDARRAY_LENGTH<span><a class="mark" href="#errors_err_napi_invalid_typedarray_length" id="errors_err_napi_invalid_typedarray_length">#</a></span><span><a class="mark" href="#ERR_NAPI_INVALID_TYPEDARRAY_LENGTH" id="ERR_NAPI_INVALID_TYPEDARRAY_LENGTH">#</a></span></h3> <p>While calling <code>napi_create_typedarray()</code>, <code>(length * size_of_element) + byte_offset</code> was larger than the length of given <code>buffer</code>.</p> <p><a id="ERR_NAPI_TSFN_CALL_JS"></a></p> <h3>ERR_NAPI_TSFN_CALL_JS<span><a class="mark" href="#errors_err_napi_tsfn_call_js" id="errors_err_napi_tsfn_call_js">#</a></span><span><a class="mark" href="#ERR_NAPI_TSFN_CALL_JS" id="ERR_NAPI_TSFN_CALL_JS">#</a></span></h3> <p>An error occurred while invoking the JavaScript portion of the thread-safe function.</p> <p><a id="ERR_NAPI_TSFN_GET_UNDEFINED"></a></p> <h3>ERR_NAPI_TSFN_GET_UNDEFINED<span><a class="mark" href="#errors_err_napi_tsfn_get_undefined" id="errors_err_napi_tsfn_get_undefined">#</a></span><span><a class="mark" href="#ERR_NAPI_TSFN_GET_UNDEFINED" id="ERR_NAPI_TSFN_GET_UNDEFINED">#</a></span></h3> <p>An error occurred while attempting to retrieve the JavaScript <code>undefined</code> value.</p> <p><a id="ERR_NAPI_TSFN_START_IDLE_LOOP"></a></p> <h3>ERR_NAPI_TSFN_START_IDLE_LOOP<span><a class="mark" href="#errors_err_napi_tsfn_start_idle_loop" id="errors_err_napi_tsfn_start_idle_loop">#</a></span><span><a class="mark" href="#ERR_NAPI_TSFN_START_IDLE_LOOP" id="ERR_NAPI_TSFN_START_IDLE_LOOP">#</a></span></h3> <p>On the main thread, values are removed from the queue associated with the thread-safe function in an idle loop. This error indicates that an error has occurred when attempting to start the loop.</p> <p><a id="ERR_NAPI_TSFN_STOP_IDLE_LOOP"></a></p> <h3>ERR_NAPI_TSFN_STOP_IDLE_LOOP<span><a class="mark" href="#errors_err_napi_tsfn_stop_idle_loop" id="errors_err_napi_tsfn_stop_idle_loop">#</a></span><span><a class="mark" href="#ERR_NAPI_TSFN_STOP_IDLE_LOOP" id="ERR_NAPI_TSFN_STOP_IDLE_LOOP">#</a></span></h3> <p>Once no more items are left in the queue, the idle loop must be suspended. This error indicates that the idle loop has failed to stop.</p> <p><a id="ERR_NO_CRYPTO"></a></p> <h3>ERR_NO_CRYPTO<span><a class="mark" href="#errors_err_no_crypto" id="errors_err_no_crypto">#</a></span><span><a class="mark" href="#ERR_NO_CRYPTO" id="ERR_NO_CRYPTO">#</a></span></h3> <p>An attempt was made to use crypto features while Node.js was not compiled with OpenSSL crypto support.</p> <p><a id="ERR_NO_ICU"></a></p> <h3>ERR_NO_ICU<span><a class="mark" href="#errors_err_no_icu" id="errors_err_no_icu">#</a></span><span><a class="mark" href="#ERR_NO_ICU" id="ERR_NO_ICU">#</a></span></h3> <p>An attempt was made to use features that require <a href="#intl_internationalization_support">ICU</a>, but Node.js was not compiled with ICU support.</p> <p><a id="ERR_NO_LONGER_SUPPORTED"></a></p> <h3>ERR_NO_LONGER_SUPPORTED<span><a class="mark" href="#errors_err_no_longer_supported" id="errors_err_no_longer_supported">#</a></span><span><a class="mark" href="#ERR_NO_LONGER_SUPPORTED" id="ERR_NO_LONGER_SUPPORTED">#</a></span></h3> <p>A Node.js API was called in an unsupported manner, such as <code>Buffer.write(string, encoding, offset[, length])</code>.</p> <p><a id="ERR_OUT_OF_RANGE"></a></p> <h3>ERR_OUT_OF_RANGE<span><a class="mark" href="#errors_err_out_of_range" id="errors_err_out_of_range">#</a></span><span><a class="mark" href="#ERR_OUT_OF_RANGE" id="ERR_OUT_OF_RANGE">#</a></span></h3> <p>A given value is out of the accepted range.</p> <p><a id="ERR_REQUIRE_ESM"></a></p> <h3>ERR_REQUIRE_ESM<span><a class="mark" href="#errors_err_require_esm" id="errors_err_require_esm">#</a></span><span><a class="mark" href="#ERR_REQUIRE_ESM" id="ERR_REQUIRE_ESM">#</a></span></h3> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>An attempt was made to <code>require()</code> an <a href="esm.html">ES6 module</a>.</p> <p><a id="ERR_SCRIPT_EXECUTION_INTERRUPTED"></a></p> <h3>ERR_SCRIPT_EXECUTION_INTERRUPTED<span><a class="mark" href="#errors_err_script_execution_interrupted" id="errors_err_script_execution_interrupted">#</a></span><span><a class="mark" href="#ERR_SCRIPT_EXECUTION_INTERRUPTED" id="ERR_SCRIPT_EXECUTION_INTERRUPTED">#</a></span></h3> <p>Script execution was interrupted by <code>SIGINT</code> (For example, when Ctrl+C was pressed).</p> <p><a id="ERR_SERVER_ALREADY_LISTEN"></a></p> <h3>ERR_SERVER_ALREADY_LISTEN<span><a class="mark" href="#errors_err_server_already_listen" id="errors_err_server_already_listen">#</a></span><span><a class="mark" href="#ERR_SERVER_ALREADY_LISTEN" id="ERR_SERVER_ALREADY_LISTEN">#</a></span></h3> <p>The <a href="#net_server_listen"><code>server.listen()</code></a> method was called while a <code>net.Server</code> was already listening. This applies to all instances of <code>net.Server</code>, including HTTP, HTTPS, and HTTP/2 <code>Server</code> instances.</p> <p><a id="ERR_SERVER_NOT_RUNNING"></a></p> <h3>ERR_SERVER_NOT_RUNNING<span><a class="mark" href="#errors_err_server_not_running" id="errors_err_server_not_running">#</a></span><span><a class="mark" href="#ERR_SERVER_NOT_RUNNING" id="ERR_SERVER_NOT_RUNNING">#</a></span></h3> <p>The <a href="#net_server_close_callback"><code>server.close()</code></a> method was called when a <code>net.Server</code> was not running. This applies to all instances of <code>net.Server</code>, including HTTP, HTTPS, and HTTP/2 <code>Server</code> instances.</p> <p><a id="ERR_SOCKET_ALREADY_BOUND"></a></p> <h3>ERR_SOCKET_ALREADY_BOUND<span><a class="mark" href="#errors_err_socket_already_bound" id="errors_err_socket_already_bound">#</a></span><span><a class="mark" href="#ERR_SOCKET_ALREADY_BOUND" id="ERR_SOCKET_ALREADY_BOUND">#</a></span></h3> <p>An attempt was made to bind a socket that has already been bound.</p> <p><a id="ERR_SOCKET_BAD_BUFFER_SIZE"></a></p> <h3>ERR_SOCKET_BAD_BUFFER_SIZE<span><a class="mark" href="#errors_err_socket_bad_buffer_size" id="errors_err_socket_bad_buffer_size">#</a></span><span><a class="mark" href="#ERR_SOCKET_BAD_BUFFER_SIZE" id="ERR_SOCKET_BAD_BUFFER_SIZE">#</a></span></h3> <p>An invalid (negative) size was passed for either the <code>recvBufferSize</code> or <code>sendBufferSize</code> options in <a href="#dgram_dgram_createsocket_options_callback"><code>dgram.createSocket()</code></a>.</p> <p><a id="ERR_SOCKET_BAD_PORT"></a></p> <h3>ERR_SOCKET_BAD_PORT<span><a class="mark" href="#errors_err_socket_bad_port" id="errors_err_socket_bad_port">#</a></span><span><a class="mark" href="#ERR_SOCKET_BAD_PORT" id="ERR_SOCKET_BAD_PORT">#</a></span></h3> <p>An API function expecting a port >= 0 and < 65536 received an invalid value.</p> <p><a id="ERR_SOCKET_BAD_TYPE"></a></p> <h3>ERR_SOCKET_BAD_TYPE<span><a class="mark" href="#errors_err_socket_bad_type" id="errors_err_socket_bad_type">#</a></span><span><a class="mark" href="#ERR_SOCKET_BAD_TYPE" id="ERR_SOCKET_BAD_TYPE">#</a></span></h3> <p>An API function expecting a socket type (<code>udp4</code> or <code>udp6</code>) received an invalid value.</p> <p><a id="ERR_SOCKET_BUFFER_SIZE"></a></p> <h3>ERR_SOCKET_BUFFER_SIZE<span><a class="mark" href="#errors_err_socket_buffer_size" id="errors_err_socket_buffer_size">#</a></span><span><a class="mark" href="#ERR_SOCKET_BUFFER_SIZE" id="ERR_SOCKET_BUFFER_SIZE">#</a></span></h3> <p>While using <a href="#dgram_dgram_createsocket_options_callback"><code>dgram.createSocket()</code></a>, the size of the receive or send <code>Buffer</code> could not be determined.</p> <p><a id="ERR_SOCKET_CANNOT_SEND"></a></p> <h3>ERR_SOCKET_CANNOT_SEND<span><a class="mark" href="#errors_err_socket_cannot_send" id="errors_err_socket_cannot_send">#</a></span><span><a class="mark" href="#ERR_SOCKET_CANNOT_SEND" id="ERR_SOCKET_CANNOT_SEND">#</a></span></h3> <p>Data could be sent on a socket.</p> <p><a id="ERR_SOCKET_CLOSED"></a></p> <h3>ERR_SOCKET_CLOSED<span><a class="mark" href="#errors_err_socket_closed" id="errors_err_socket_closed">#</a></span><span><a class="mark" href="#ERR_SOCKET_CLOSED" id="ERR_SOCKET_CLOSED">#</a></span></h3> <p>An attempt was made to operate on an already closed socket.</p> <p><a id="ERR_SOCKET_DGRAM_NOT_RUNNING"></a></p> <h3>ERR_SOCKET_DGRAM_NOT_RUNNING<span><a class="mark" href="#errors_err_socket_dgram_not_running" id="errors_err_socket_dgram_not_running">#</a></span><span><a class="mark" href="#ERR_SOCKET_DGRAM_NOT_RUNNING" id="ERR_SOCKET_DGRAM_NOT_RUNNING">#</a></span></h3> <p>A call was made and the UDP subsystem was not running.</p> <p><a id="ERR_STREAM_CANNOT_PIPE"></a></p> <h3>ERR_STREAM_CANNOT_PIPE<span><a class="mark" href="#errors_err_stream_cannot_pipe" id="errors_err_stream_cannot_pipe">#</a></span><span><a class="mark" href="#ERR_STREAM_CANNOT_PIPE" id="ERR_STREAM_CANNOT_PIPE">#</a></span></h3> <p>An attempt was made to call <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> on a <a href="#stream_class_stream_writable"><code>Writable</code></a> stream.</p> <p><a id="ERR_STREAM_DESTROYED"></a></p> <h3>ERR_STREAM_DESTROYED<span><a class="mark" href="#errors_err_stream_destroyed" id="errors_err_stream_destroyed">#</a></span><span><a class="mark" href="#ERR_STREAM_DESTROYED" id="ERR_STREAM_DESTROYED">#</a></span></h3> <p>A stream method was called that cannot complete because the stream was destroyed using <code>stream.destroy()</code>.</p> <p><a id="ERR_STREAM_NULL_VALUES"></a></p> <h3>ERR_STREAM_NULL_VALUES<span><a class="mark" href="#errors_err_stream_null_values" id="errors_err_stream_null_values">#</a></span><span><a class="mark" href="#ERR_STREAM_NULL_VALUES" id="ERR_STREAM_NULL_VALUES">#</a></span></h3> <p>An attempt was made to call <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> with a <code>null</code> chunk.</p> <p><a id="ERR_STREAM_PREMATURE_CLOSE"></a></p> <h3>ERR_STREAM_PREMATURE_CLOSE<span><a class="mark" href="#errors_err_stream_premature_close" id="errors_err_stream_premature_close">#</a></span><span><a class="mark" href="#ERR_STREAM_PREMATURE_CLOSE" id="ERR_STREAM_PREMATURE_CLOSE">#</a></span></h3> <p>An error returned by <code>stream.finished()</code> and <code>stream.pipeline()</code>, when a stream or a pipeline ends non gracefully with no explicit error.</p> <p><a id="ERR_STREAM_PUSH_AFTER_EOF"></a></p> <h3>ERR_STREAM_PUSH_AFTER_EOF<span><a class="mark" href="#errors_err_stream_push_after_eof" id="errors_err_stream_push_after_eof">#</a></span><span><a class="mark" href="#ERR_STREAM_PUSH_AFTER_EOF" id="ERR_STREAM_PUSH_AFTER_EOF">#</a></span></h3> <p>An attempt was made to call <a href="#stream_readable_push_chunk_encoding"><code>stream.push()</code></a> after a <code>null</code>(EOF) had been pushed to the stream.</p> <p><a id="ERR_STREAM_UNSHIFT_AFTER_END_EVENT"></a></p> <h3>ERR_STREAM_UNSHIFT_AFTER_END_EVENT<span><a class="mark" href="#errors_err_stream_unshift_after_end_event" id="errors_err_stream_unshift_after_end_event">#</a></span><span><a class="mark" href="#ERR_STREAM_UNSHIFT_AFTER_END_EVENT" id="ERR_STREAM_UNSHIFT_AFTER_END_EVENT">#</a></span></h3> <p>An attempt was made to call <a href="#stream_readable_unshift_chunk"><code>stream.unshift()</code></a> after the <code>'end'</code> event was emitted.</p> <p><a id="ERR_STREAM_WRAP"></a></p> <h3>ERR_STREAM_WRAP<span><a class="mark" href="#errors_err_stream_wrap" id="errors_err_stream_wrap">#</a></span><span><a class="mark" href="#ERR_STREAM_WRAP" id="ERR_STREAM_WRAP">#</a></span></h3> <p>Prevents an abort if a string decoder was set on the Socket or if the decoder is in <code>objectMode</code>.</p> <pre><code class="language-js">const Socket = require('net').Socket; const instance = new Socket(); instance.setEncoding('utf8'); </code></pre> <p><a id="ERR_STREAM_WRITE_AFTER_END"></a></p> <h3>ERR_STREAM_WRITE_AFTER_END<span><a class="mark" href="#errors_err_stream_write_after_end" id="errors_err_stream_write_after_end">#</a></span><span><a class="mark" href="#ERR_STREAM_WRITE_AFTER_END" id="ERR_STREAM_WRITE_AFTER_END">#</a></span></h3> <p>An attempt was made to call <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> after <code>stream.end()</code> has been called.</p> <p><a id="ERR_STRING_TOO_LONG"></a></p> <h3>ERR_STRING_TOO_LONG<span><a class="mark" href="#errors_err_string_too_long" id="errors_err_string_too_long">#</a></span><span><a class="mark" href="#ERR_STRING_TOO_LONG" id="ERR_STRING_TOO_LONG">#</a></span></h3> <p>An attempt has been made to create a string longer than the maximum allowed length.</p> <p><a id="ERR_SYSTEM_ERROR"></a></p> <h3>ERR_SYSTEM_ERROR<span><a class="mark" href="#errors_err_system_error" id="errors_err_system_error">#</a></span><span><a class="mark" href="#ERR_SYSTEM_ERROR" id="ERR_SYSTEM_ERROR">#</a></span></h3> <p>An unspecified or non-specific system error has occurred within the Node.js process. The error object will have an <code>err.info</code> object property with additional details.</p> <p><a id="ERR_TLS_CERT_ALTNAME_INVALID"></a></p> <h3>ERR_TLS_CERT_ALTNAME_INVALID<span><a class="mark" href="#errors_err_tls_cert_altname_invalid" id="errors_err_tls_cert_altname_invalid">#</a></span><span><a class="mark" href="#ERR_TLS_CERT_ALTNAME_INVALID" id="ERR_TLS_CERT_ALTNAME_INVALID">#</a></span></h3> <p>While using TLS, the hostname/IP of the peer did not match any of the <code>subjectAltNames</code> in its certificate.</p> <p><a id="ERR_TLS_DH_PARAM_SIZE"></a></p> <h3>ERR_TLS_DH_PARAM_SIZE<span><a class="mark" href="#errors_err_tls_dh_param_size" id="errors_err_tls_dh_param_size">#</a></span><span><a class="mark" href="#ERR_TLS_DH_PARAM_SIZE" id="ERR_TLS_DH_PARAM_SIZE">#</a></span></h3> <p>While using TLS, the parameter offered for the Diffie-Hellman (<code>DH</code>) key-agreement protocol is too small. By default, the key length must be greater than or equal to 1024 bits to avoid vulnerabilities, even though it is strongly recommended to use 2048 bits or larger for stronger security.</p> <p><a id="ERR_TLS_HANDSHAKE_TIMEOUT"></a></p> <h3>ERR_TLS_HANDSHAKE_TIMEOUT<span><a class="mark" href="#errors_err_tls_handshake_timeout" id="errors_err_tls_handshake_timeout">#</a></span><span><a class="mark" href="#ERR_TLS_HANDSHAKE_TIMEOUT" id="ERR_TLS_HANDSHAKE_TIMEOUT">#</a></span></h3> <p>A TLS/SSL handshake timed out. In this case, the server must also abort the connection.</p> <p><a id="ERR_TLS_INVALID_PROTOCOL_VERSION"></a></p> <h3>ERR_TLS_INVALID_PROTOCOL_VERSION<span><a class="mark" href="#errors_err_tls_invalid_protocol_version" id="errors_err_tls_invalid_protocol_version">#</a></span><span><a class="mark" href="#ERR_TLS_INVALID_PROTOCOL_VERSION" id="ERR_TLS_INVALID_PROTOCOL_VERSION">#</a></span></h3> <p>Valid TLS protocol versions are <code>'TLSv1'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1.2'</code>.</p> <p><a id="ERR_TLS_PROTOCOL_VERSION_CONFLICT"></a></p> <h3>ERR_TLS_PROTOCOL_VERSION_CONFLICT<span><a class="mark" href="#errors_err_tls_protocol_version_conflict" id="errors_err_tls_protocol_version_conflict">#</a></span><span><a class="mark" href="#ERR_TLS_PROTOCOL_VERSION_CONFLICT" id="ERR_TLS_PROTOCOL_VERSION_CONFLICT">#</a></span></h3> <p>Attempting to set a TLS protocol <code>minVersion</code> or <code>maxVersion</code> conflicts with an attempt to set the <code>secureProtocol</code> explicitly. Use one mechanism or the other.</p> <p><a id="ERR_TLS_RENEGOTIATE"></a></p> <h3>ERR_TLS_RENEGOTIATE<span><a class="mark" href="#errors_err_tls_renegotiate" id="errors_err_tls_renegotiate">#</a></span><span><a class="mark" href="#ERR_TLS_RENEGOTIATE" id="ERR_TLS_RENEGOTIATE">#</a></span></h3> <p>An attempt to renegotiate the TLS session failed.</p> <p><a id="ERR_TLS_RENEGOTIATION_DISABLED"></a></p> <h3>ERR_TLS_RENEGOTIATION_DISABLED<span><a class="mark" href="#errors_err_tls_renegotiation_disabled" id="errors_err_tls_renegotiation_disabled">#</a></span><span><a class="mark" href="#ERR_TLS_RENEGOTIATION_DISABLED" id="ERR_TLS_RENEGOTIATION_DISABLED">#</a></span></h3> <p>An attempt was made to renegotiate TLS on a socket instance with TLS disabled.</p> <p><a id="ERR_TLS_REQUIRED_SERVER_NAME"></a></p> <h3>ERR_TLS_REQUIRED_SERVER_NAME<span><a class="mark" href="#errors_err_tls_required_server_name" id="errors_err_tls_required_server_name">#</a></span><span><a class="mark" href="#ERR_TLS_REQUIRED_SERVER_NAME" id="ERR_TLS_REQUIRED_SERVER_NAME">#</a></span></h3> <p>While using TLS, the <code>server.addContext()</code> method was called without providing a hostname in the first parameter.</p> <p><a id="ERR_TLS_SESSION_ATTACK"></a></p> <h3>ERR_TLS_SESSION_ATTACK<span><a class="mark" href="#errors_err_tls_session_attack" id="errors_err_tls_session_attack">#</a></span><span><a class="mark" href="#ERR_TLS_SESSION_ATTACK" id="ERR_TLS_SESSION_ATTACK">#</a></span></h3> <p>An excessive amount of TLS renegotiations is detected, which is a potential vector for denial-of-service attacks.</p> <p><a id="ERR_TLS_SNI_FROM_SERVER"></a></p> <h3>ERR_TLS_SNI_FROM_SERVER<span><a class="mark" href="#errors_err_tls_sni_from_server" id="errors_err_tls_sni_from_server">#</a></span><span><a class="mark" href="#ERR_TLS_SNI_FROM_SERVER" id="ERR_TLS_SNI_FROM_SERVER">#</a></span></h3> <p>An attempt was made to issue Server Name Indication from a TLS server-side socket, which is only valid from a client.</p> <p><a id="ERR_TRACE_EVENTS_CATEGORY_REQUIRED"></a></p> <h3>ERR_TRACE_EVENTS_CATEGORY_REQUIRED<span><a class="mark" href="#errors_err_trace_events_category_required" id="errors_err_trace_events_category_required">#</a></span><span><a class="mark" href="#ERR_TRACE_EVENTS_CATEGORY_REQUIRED" id="ERR_TRACE_EVENTS_CATEGORY_REQUIRED">#</a></span></h3> <p>The <code>trace_events.createTracing()</code> method requires at least one trace event category.</p> <p><a id="ERR_TRACE_EVENTS_UNAVAILABLE"></a></p> <h3>ERR_TRACE_EVENTS_UNAVAILABLE<span><a class="mark" href="#errors_err_trace_events_unavailable" id="errors_err_trace_events_unavailable">#</a></span><span><a class="mark" href="#ERR_TRACE_EVENTS_UNAVAILABLE" id="ERR_TRACE_EVENTS_UNAVAILABLE">#</a></span></h3> <p>The <code>trace_events</code> module could not be loaded because Node.js was compiled with the <code>--without-v8-platform</code> flag.</p> <p><a id="ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER"></a></p> <h3>ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER<span><a class="mark" href="#errors_err_transferring_externalized_sharedarraybuffer" id="errors_err_transferring_externalized_sharedarraybuffer">#</a></span><span><a class="mark" href="#ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER" id="ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER">#</a></span></h3> <p>A <code>SharedArrayBuffer</code> whose memory is not managed by the JavaScript engine or by Node.js was encountered during serialization. Such a <code>SharedArrayBuffer</code> cannot be serialized.</p> <p>This can only happen when native addons create <code>SharedArrayBuffer</code>s in "externalized" mode, or put existing <code>SharedArrayBuffer</code> into externalized mode.</p> <p><a id="ERR_TRANSFORM_ALREADY_TRANSFORMING"></a></p> <h3>ERR_TRANSFORM_ALREADY_TRANSFORMING<span><a class="mark" href="#errors_err_transform_already_transforming" id="errors_err_transform_already_transforming">#</a></span><span><a class="mark" href="#ERR_TRANSFORM_ALREADY_TRANSFORMING" id="ERR_TRANSFORM_ALREADY_TRANSFORMING">#</a></span></h3> <p>A <code>Transform</code> stream finished while it was still transforming.</p> <p><a id="ERR_TRANSFORM_WITH_LENGTH_0"></a></p> <h3>ERR_TRANSFORM_WITH_LENGTH_0<span><a class="mark" href="#errors_err_transform_with_length_0" id="errors_err_transform_with_length_0">#</a></span><span><a class="mark" href="#ERR_TRANSFORM_WITH_LENGTH_0" id="ERR_TRANSFORM_WITH_LENGTH_0">#</a></span></h3> <p>A <code>Transform</code> stream finished with data still in the write buffer.</p> <p><a id="ERR_TTY_INIT_FAILED"></a></p> <h3>ERR_TTY_INIT_FAILED<span><a class="mark" href="#errors_err_tty_init_failed" id="errors_err_tty_init_failed">#</a></span><span><a class="mark" href="#ERR_TTY_INIT_FAILED" id="ERR_TTY_INIT_FAILED">#</a></span></h3> <p>The initialization of a TTY failed due to a system error.</p> <p><a id="ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET"></a></p> <h3>ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET<span><a class="mark" href="#errors_err_uncaught_exception_capture_already_set" id="errors_err_uncaught_exception_capture_already_set">#</a></span><span><a class="mark" href="#ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET" id="ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET">#</a></span></h3> <p><a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> was called twice, without first resetting the callback to <code>null</code>.</p> <p>This error is designed to prevent accidentally overwriting a callback registered from another module.</p> <p><a id="ERR_UNESCAPED_CHARACTERS"></a></p> <h3>ERR_UNESCAPED_CHARACTERS<span><a class="mark" href="#errors_err_unescaped_characters" id="errors_err_unescaped_characters">#</a></span><span><a class="mark" href="#ERR_UNESCAPED_CHARACTERS" id="ERR_UNESCAPED_CHARACTERS">#</a></span></h3> <p>A string that contained unescaped characters was received.</p> <p><a id="ERR_UNHANDLED_ERROR"></a></p> <h3>ERR_UNHANDLED_ERROR<span><a class="mark" href="#errors_err_unhandled_error" id="errors_err_unhandled_error">#</a></span><span><a class="mark" href="#ERR_UNHANDLED_ERROR" id="ERR_UNHANDLED_ERROR">#</a></span></h3> <p>An unhandled error occurred (for instance, when an <code>'error'</code> event is emitted by an <a href="#events_class_eventemitter"><code>EventEmitter</code></a> but an <code>'error'</code> handler is not registered).</p> <p><a id="ERR_UNKNOWN_BUILTIN_MODULE"></a></p> <h3>ERR_UNKNOWN_BUILTIN_MODULE<span><a class="mark" href="#errors_err_unknown_builtin_module" id="errors_err_unknown_builtin_module">#</a></span><span><a class="mark" href="#ERR_UNKNOWN_BUILTIN_MODULE" id="ERR_UNKNOWN_BUILTIN_MODULE">#</a></span></h3> <p>Used to identify a specific kind of internal Node.js error that should not typically be triggered by user code. Instances of this error point to an internal bug within the Node.js binary itself.</p> <p><a id="ERR_UNKNOWN_ENCODING"></a></p> <h3>ERR_UNKNOWN_ENCODING<span><a class="mark" href="#errors_err_unknown_encoding" id="errors_err_unknown_encoding">#</a></span><span><a class="mark" href="#ERR_UNKNOWN_ENCODING" id="ERR_UNKNOWN_ENCODING">#</a></span></h3> <p>An invalid or unknown encoding option was passed to an API.</p> <p><a id="ERR_UNKNOWN_FILE_EXTENSION"></a></p> <h3>ERR_UNKNOWN_FILE_EXTENSION<span><a class="mark" href="#errors_err_unknown_file_extension" id="errors_err_unknown_file_extension">#</a></span><span><a class="mark" href="#ERR_UNKNOWN_FILE_EXTENSION" id="ERR_UNKNOWN_FILE_EXTENSION">#</a></span></h3> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>An attempt was made to load a module with an unknown or unsupported file extension.</p> <p><a id="ERR_UNKNOWN_MODULE_FORMAT"></a></p> <h3>ERR_UNKNOWN_MODULE_FORMAT<span><a class="mark" href="#errors_err_unknown_module_format" id="errors_err_unknown_module_format">#</a></span><span><a class="mark" href="#ERR_UNKNOWN_MODULE_FORMAT" id="ERR_UNKNOWN_MODULE_FORMAT">#</a></span></h3> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>An attempt was made to load a module with an unknown or unsupported format.</p> <p><a id="ERR_UNKNOWN_SIGNAL"></a></p> <h3>ERR_UNKNOWN_SIGNAL<span><a class="mark" href="#errors_err_unknown_signal" id="errors_err_unknown_signal">#</a></span><span><a class="mark" href="#ERR_UNKNOWN_SIGNAL" id="ERR_UNKNOWN_SIGNAL">#</a></span></h3> <p>An invalid or unknown process signal was passed to an API expecting a valid signal (such as <a href="#child_process_subprocess_kill_signal"><code>subprocess.kill()</code></a>).</p> <p><a id="ERR_UNKNOWN_STDIN_TYPE"></a></p> <h3>ERR_UNKNOWN_STDIN_TYPE<span><a class="mark" href="#errors_err_unknown_stdin_type" id="errors_err_unknown_stdin_type">#</a></span><span><a class="mark" href="#ERR_UNKNOWN_STDIN_TYPE" id="ERR_UNKNOWN_STDIN_TYPE">#</a></span></h3> <p>An attempt was made to launch a Node.js process with an unknown <code>stdin</code> file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it.</p> <p><a id="ERR_UNKNOWN_STREAM_TYPE"></a></p> <h3>ERR_UNKNOWN_STREAM_TYPE<span><a class="mark" href="#errors_err_unknown_stream_type" id="errors_err_unknown_stream_type">#</a></span><span><a class="mark" href="#ERR_UNKNOWN_STREAM_TYPE" id="ERR_UNKNOWN_STREAM_TYPE">#</a></span></h3> <p>An attempt was made to launch a Node.js process with an unknown <code>stdout</code> or <code>stderr</code> file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it.</p> <p><a id="ERR_V8BREAKITERATOR"></a></p> <h3>ERR_V8BREAKITERATOR<span><a class="mark" href="#errors_err_v8breakiterator" id="errors_err_v8breakiterator">#</a></span><span><a class="mark" href="#ERR_V8BREAKITERATOR" id="ERR_V8BREAKITERATOR">#</a></span></h3> <p>The V8 <code>BreakIterator</code> API was used but the full ICU data set is not installed.</p> <p><a id="ERR_VALID_PERFORMANCE_ENTRY_TYPE"></a></p> <h3>ERR_VALID_PERFORMANCE_ENTRY_TYPE<span><a class="mark" href="#errors_err_valid_performance_entry_type" id="errors_err_valid_performance_entry_type">#</a></span><span><a class="mark" href="#ERR_VALID_PERFORMANCE_ENTRY_TYPE" id="ERR_VALID_PERFORMANCE_ENTRY_TYPE">#</a></span></h3> <p>While using the Performance Timing API (<code>perf_hooks</code>), no valid performance entry types were found.</p> <p><a id="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"></a></p> <h3>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING<span><a class="mark" href="#errors_err_vm_dynamic_import_callback_missing" id="errors_err_vm_dynamic_import_callback_missing">#</a></span><span><a class="mark" href="#ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING" id="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING">#</a></span></h3> <p>A dynamic import callback was not specified.</p> <p><a id="ERR_VM_MODULE_ALREADY_LINKED"></a></p> <h3>ERR_VM_MODULE_ALREADY_LINKED<span><a class="mark" href="#errors_err_vm_module_already_linked" id="errors_err_vm_module_already_linked">#</a></span><span><a class="mark" href="#ERR_VM_MODULE_ALREADY_LINKED" id="ERR_VM_MODULE_ALREADY_LINKED">#</a></span></h3> <p>The module attempted to be linked is not eligible for linking, because of one of the following reasons:</p> <ul> <li>It has already been linked (<code>linkingStatus</code> is <code>'linked'</code>)</li> <li>It is being linked (<code>linkingStatus</code> is <code>'linking'</code>)</li> <li>Linking has failed for this module (<code>linkingStatus</code> is <code>'errored'</code>)</li> </ul> <p><a id="ERR_VM_MODULE_DIFFERENT_CONTEXT"></a></p> <h3>ERR_VM_MODULE_DIFFERENT_CONTEXT<span><a class="mark" href="#errors_err_vm_module_different_context" id="errors_err_vm_module_different_context">#</a></span><span><a class="mark" href="#ERR_VM_MODULE_DIFFERENT_CONTEXT" id="ERR_VM_MODULE_DIFFERENT_CONTEXT">#</a></span></h3> <p>The module being returned from the linker function is from a different context than the parent module. Linked modules must share the same context.</p> <p><a id="ERR_VM_MODULE_LINKING_ERRORED"></a></p> <h3>ERR_VM_MODULE_LINKING_ERRORED<span><a class="mark" href="#errors_err_vm_module_linking_errored" id="errors_err_vm_module_linking_errored">#</a></span><span><a class="mark" href="#ERR_VM_MODULE_LINKING_ERRORED" id="ERR_VM_MODULE_LINKING_ERRORED">#</a></span></h3> <p>The linker function returned a module for which linking has failed.</p> <p><a id="ERR_VM_MODULE_NOT_LINKED"></a></p> <h3>ERR_VM_MODULE_NOT_LINKED<span><a class="mark" href="#errors_err_vm_module_not_linked" id="errors_err_vm_module_not_linked">#</a></span><span><a class="mark" href="#ERR_VM_MODULE_NOT_LINKED" id="ERR_VM_MODULE_NOT_LINKED">#</a></span></h3> <p>The module must be successfully linked before instantiation.</p> <p><a id="ERR_VM_MODULE_NOT_MODULE"></a></p> <h3>ERR_VM_MODULE_NOT_MODULE<span><a class="mark" href="#errors_err_vm_module_not_module" id="errors_err_vm_module_not_module">#</a></span><span><a class="mark" href="#ERR_VM_MODULE_NOT_MODULE" id="ERR_VM_MODULE_NOT_MODULE">#</a></span></h3> <p>The fulfilled value of a linking promise is not a <code>vm.SourceTextModule</code> object.</p> <p><a id="ERR_VM_MODULE_STATUS"></a></p> <h3>ERR_VM_MODULE_STATUS<span><a class="mark" href="#errors_err_vm_module_status" id="errors_err_vm_module_status">#</a></span><span><a class="mark" href="#ERR_VM_MODULE_STATUS" id="ERR_VM_MODULE_STATUS">#</a></span></h3> <p>The current module's status does not allow for this operation. The specific meaning of the error depends on the specific function.</p> <p><a id="ERR_WORKER_PATH"></a></p> <h3>ERR_WORKER_PATH<span><a class="mark" href="#errors_err_worker_path" id="errors_err_worker_path">#</a></span><span><a class="mark" href="#ERR_WORKER_PATH" id="ERR_WORKER_PATH">#</a></span></h3> <p>The path for the main script of a worker is neither an absolute path nor a relative path starting with <code>./</code> or <code>../</code>.</p> <p><a id="ERR_WORKER_UNSERIALIZABLE_ERROR"></a></p> <h3>ERR_WORKER_UNSERIALIZABLE_ERROR<span><a class="mark" href="#errors_err_worker_unserializable_error" id="errors_err_worker_unserializable_error">#</a></span><span><a class="mark" href="#ERR_WORKER_UNSERIALIZABLE_ERROR" id="ERR_WORKER_UNSERIALIZABLE_ERROR">#</a></span></h3> <p>All attempts at serializing an uncaught exception from a worker thread failed.</p> <p><a id="ERR_WORKER_UNSUPPORTED_EXTENSION"></a></p> <h3>ERR_WORKER_UNSUPPORTED_EXTENSION<span><a class="mark" href="#errors_err_worker_unsupported_extension" id="errors_err_worker_unsupported_extension">#</a></span><span><a class="mark" href="#ERR_WORKER_UNSUPPORTED_EXTENSION" id="ERR_WORKER_UNSUPPORTED_EXTENSION">#</a></span></h3> <p>The pathname used for the main script of a worker has an unknown file extension.</p> <p><a id="ERR_ZLIB_INITIALIZATION_FAILED"></a></p> <h3>ERR_ZLIB_INITIALIZATION_FAILED<span><a class="mark" href="#errors_err_zlib_initialization_failed" id="errors_err_zlib_initialization_failed">#</a></span><span><a class="mark" href="#ERR_ZLIB_INITIALIZATION_FAILED" id="ERR_ZLIB_INITIALIZATION_FAILED">#</a></span></h3> <p>Creation of a <a href="zlib.html"><code>zlib</code></a> object failed due to incorrect configuration.</p> <p><a id="HPE_HEADER_OVERFLOW"></a></p> <h3>HPE_HEADER_OVERFLOW<span><a class="mark" href="#errors_hpe_header_overflow" id="errors_hpe_header_overflow">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.15.0</td> <td><p>Max header size in <code>http_parser</code> was set to 8KB.</p></td></tr> </tbody></table> </details> </div> <p>Too much HTTP header data was received. In order to protect against malicious or malconfigured clients, if more than 8KB of HTTP header data is received then HTTP parsing will abort without a request or response object being created, and an <code>Error</code> with this code will be emitted.</p> <p><a id="MODULE_NOT_FOUND"></a></p> <h3>MODULE_NOT_FOUND<span><a class="mark" href="#errors_module_not_found" id="errors_module_not_found">#</a></span></h3> <p>A module file could not be resolved while attempting a <a href="#modules_require"><code>require()</code></a> or <code>import</code> operation.</p> <h2>Legacy Node.js Error Codes<span><a class="mark" href="#errors_legacy_node_js_error_codes" id="errors_legacy_node_js_error_codes">#</a></span></h2> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated. These error codes are either inconsistent, or have been removed.</div><p></p> <p><a id="ERR_HTTP2_FRAME_ERROR"></a></p> <h3>ERR_HTTP2_FRAME_ERROR<span><a class="mark" href="#errors_err_http2_frame_error" id="errors_err_http2_frame_error">#</a></span><span><a class="mark" href="#ERR_HTTP2_FRAME_ERROR" id="ERR_HTTP2_FRAME_ERROR">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>Used when a failure occurs sending an individual frame on the HTTP/2 session.</p> <p><a id="ERR_HTTP2_HEADERS_OBJECT"></a></p> <h3>ERR_HTTP2_HEADERS_OBJECT<span><a class="mark" href="#errors_err_http2_headers_object" id="errors_err_http2_headers_object">#</a></span><span><a class="mark" href="#ERR_HTTP2_HEADERS_OBJECT" id="ERR_HTTP2_HEADERS_OBJECT">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>Used when an HTTP/2 Headers Object is expected.</p> <p><a id="ERR_HTTP2_HEADER_REQUIRED"></a></p> <h3>ERR_HTTP2_HEADER_REQUIRED<span><a class="mark" href="#errors_err_http2_header_required" id="errors_err_http2_header_required">#</a></span><span><a class="mark" href="#ERR_HTTP2_HEADER_REQUIRED" id="ERR_HTTP2_HEADER_REQUIRED">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>Used when a required header is missing in an HTTP/2 message.</p> <p><a id="ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND"></a></p> <h3>ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND<span><a class="mark" href="#errors_err_http2_info_headers_after_respond" id="errors_err_http2_info_headers_after_respond">#</a></span><span><a class="mark" href="#ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND" id="ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>HTTP/2 informational headers must only be sent <em>prior</em> to calling the <code>Http2Stream.prototype.respond()</code> method.</p> <p><a id="ERR_HTTP2_STREAM_CLOSED"></a></p> <h3>ERR_HTTP2_STREAM_CLOSED<span><a class="mark" href="#errors_err_http2_stream_closed" id="errors_err_http2_stream_closed">#</a></span><span><a class="mark" href="#ERR_HTTP2_STREAM_CLOSED" id="ERR_HTTP2_STREAM_CLOSED">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>Used when an action has been performed on an HTTP/2 Stream that has already been closed.</p> <p><a id="ERR_HTTP_INVALID_CHAR"></a></p> <h3>ERR_HTTP_INVALID_CHAR<span><a class="mark" href="#errors_err_http_invalid_char" id="errors_err_http_invalid_char">#</a></span><span><a class="mark" href="#ERR_HTTP_INVALID_CHAR" id="ERR_HTTP_INVALID_CHAR">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>Used when an invalid character is found in an HTTP response status message (reason phrase).</p> <p><a id="ERR_NAPI_CONS_PROTOTYPE_OBJECT"></a></p> <h3>ERR_NAPI_CONS_PROTOTYPE_OBJECT<span><a class="mark" href="#errors_err_napi_cons_prototype_object" id="errors_err_napi_cons_prototype_object">#</a></span><span><a class="mark" href="#ERR_NAPI_CONS_PROTOTYPE_OBJECT" id="ERR_NAPI_CONS_PROTOTYPE_OBJECT">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>Used by the <code>N-API</code> when <code>Constructor.prototype</code> is not an object.</p> <p><a id="ERR_OUTOFMEMORY"></a></p> <h3>ERR_OUTOFMEMORY<span><a class="mark" href="#errors_err_outofmemory" id="errors_err_outofmemory">#</a></span><span><a class="mark" href="#ERR_OUTOFMEMORY" id="ERR_OUTOFMEMORY">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>Used generically to identify that an operation caused an out of memory condition.</p> <p><a id="ERR_PARSE_HISTORY_DATA"></a></p> <h3>ERR_PARSE_HISTORY_DATA<span><a class="mark" href="#errors_err_parse_history_data" id="errors_err_parse_history_data">#</a></span><span><a class="mark" href="#ERR_PARSE_HISTORY_DATA" id="ERR_PARSE_HISTORY_DATA">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>The <code>repl</code> module was unable to parse data from the REPL history file.</p> <p><a id="ERR_STDERR_CLOSE"></a></p> <h3>ERR_STDERR_CLOSE<span><a class="mark" href="#errors_err_stderr_close" id="errors_err_stderr_close">#</a></span><span><a class="mark" href="#ERR_STDERR_CLOSE" id="ERR_STDERR_CLOSE">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.12.0</td> <td><p>Rather than emitting an error, <code>process.stderr.end()</code> now only closes the stream side but not the underlying resource, making this error obsolete.</p></td></tr> <tr><td>v10.12.0</td> <td><p><span>Removed in: v10.12.0</span></p></td></tr> </tbody></table> </details> </div> <p>An attempt was made to close the <code>process.stderr</code> stream. By design, Node.js does not allow <code>stdout</code> or <code>stderr</code> streams to be closed by user code.</p> <p><a id="ERR_STDOUT_CLOSE"></a></p> <h3>ERR_STDOUT_CLOSE<span><a class="mark" href="#errors_err_stdout_close" id="errors_err_stdout_close">#</a></span><span><a class="mark" href="#ERR_STDOUT_CLOSE" id="ERR_STDOUT_CLOSE">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.12.0</td> <td><p>Rather than emitting an error, <code>process.stderr.end()</code> now only closes the stream side but not the underlying resource, making this error obsolete.</p></td></tr> <tr><td>v10.12.0</td> <td><p><span>Removed in: v10.12.0</span></p></td></tr> </tbody></table> </details> </div> <p>An attempt was made to close the <code>process.stdout</code> stream. By design, Node.js does not allow <code>stdout</code> or <code>stderr</code> streams to be closed by user code.</p> <p><a id="ERR_STREAM_READ_NOT_IMPLEMENTED"></a></p> <h3>ERR_STREAM_READ_NOT_IMPLEMENTED<span><a class="mark" href="#errors_err_stream_read_not_implemented" id="errors_err_stream_read_not_implemented">#</a></span><span><a class="mark" href="#ERR_STREAM_READ_NOT_IMPLEMENTED" id="ERR_STREAM_READ_NOT_IMPLEMENTED">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>Used when an attempt is made to use a readable stream that has not implemented <a href="#stream_readable_read_size_1"><code>readable._read()</code></a>.</p> <p><a id="ERR_TLS_RENEGOTIATION_FAILED"></a></p> <h3>ERR_TLS_RENEGOTIATION_FAILED<span><a class="mark" href="#errors_err_tls_renegotiation_failed" id="errors_err_tls_renegotiation_failed">#</a></span><span><a class="mark" href="#ERR_TLS_RENEGOTIATION_FAILED" id="ERR_TLS_RENEGOTIATION_FAILED">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>Used when a TLS renegotiation request has failed in a non-specific way.</p> <p><a id="ERR_UNKNOWN_BUILTIN_MODULE"></a></p> <h3>ERR_UNKNOWN_BUILTIN_MODULE<span><a class="mark" href="#errors_err_unknown_builtin_module_1" id="errors_err_unknown_builtin_module_1">#</a></span><span><a class="mark" href="#ERR_UNKNOWN_BUILTIN_MODULE" id="ERR_UNKNOWN_BUILTIN_MODULE">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span><span>Removed in: v9.0.0</span> </div> <p>The <code>'ERR_UNKNOWN_BUILTIN_MODULE'</code> error code is used to identify a specific kind of internal Node.js error that should not typically be triggered by user code. Instances of this error point to an internal bug within the Node.js binary itself.</p> <p><a id="ERR_VALUE_OUT_OF_RANGE"></a></p> <h3>ERR_VALUE_OUT_OF_RANGE<span><a class="mark" href="#errors_err_value_out_of_range" id="errors_err_value_out_of_range">#</a></span><span><a class="mark" href="#ERR_VALUE_OUT_OF_RANGE" id="ERR_VALUE_OUT_OF_RANGE">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>Used when a given value is out of the accepted range.</p> <p><a id="ERR_ZLIB_BINDING_CLOSED"></a></p> <h3>ERR_ZLIB_BINDING_CLOSED<span><a class="mark" href="#errors_err_zlib_binding_closed" id="errors_err_zlib_binding_closed">#</a></span><span><a class="mark" href="#ERR_ZLIB_BINDING_CLOSED" id="ERR_ZLIB_BINDING_CLOSED">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span> </div> <p>Used when an attempt is made to use a <code>zlib</code> object after it has already been closed.</p> <h3>Other error codes<span><a class="mark" href="#errors_other_error_codes" id="errors_other_error_codes">#</a></span></h3> <p>These errors have never been released, but had been present on master between releases.</p> <p><a id="ERR_FS_WATCHER_ALREADY_STARTED"></a></p> <h4>ERR_FS_WATCHER_ALREADY_STARTED<span><a class="mark" href="#errors_err_fs_watcher_already_started" id="errors_err_fs_watcher_already_started">#</a></span><span><a class="mark" href="#ERR_FS_WATCHER_ALREADY_STARTED" id="ERR_FS_WATCHER_ALREADY_STARTED">#</a></span></h4> <p>An attempt was made to start a watcher returned by <code>fs.watch()</code> that has already been started.</p> <p><a id="ERR_FS_WATCHER_NOT_STARTED"></a></p> <h4>ERR_FS_WATCHER_NOT_STARTED<span><a class="mark" href="#errors_err_fs_watcher_not_started" id="errors_err_fs_watcher_not_started">#</a></span><span><a class="mark" href="#ERR_FS_WATCHER_NOT_STARTED" id="ERR_FS_WATCHER_NOT_STARTED">#</a></span></h4> <p>An attempt was made to initiate operations on a watcher returned by <code>fs.watch()</code> that has not yet been started.</p> <p><a id="ERR_HTTP2_ALREADY_SHUTDOWN"></a></p> <h4>ERR_HTTP2_ALREADY_SHUTDOWN<span><a class="mark" href="#errors_err_http2_already_shutdown" id="errors_err_http2_already_shutdown">#</a></span><span><a class="mark" href="#ERR_HTTP2_ALREADY_SHUTDOWN" id="ERR_HTTP2_ALREADY_SHUTDOWN">#</a></span></h4> <p>Occurs with multiple attempts to shutdown an HTTP/2 session.</p> <p><a id="ERR_HTTP2_ERROR"></a></p> <h4>ERR_HTTP2_ERROR<span><a class="mark" href="#errors_err_http2_error_1" id="errors_err_http2_error_1">#</a></span><span><a class="mark" href="#ERR_HTTP2_ERROR" id="ERR_HTTP2_ERROR">#</a></span></h4> <p>A non-specific HTTP/2 error has occurred.</p> <p><a id="ERR_INVALID_REPL_HISTORY"></a></p> <h4>ERR_INVALID_REPL_HISTORY<span><a class="mark" href="#errors_err_invalid_repl_history" id="errors_err_invalid_repl_history">#</a></span><span><a class="mark" href="#ERR_INVALID_REPL_HISTORY" id="ERR_INVALID_REPL_HISTORY">#</a></span></h4> <p>Used in the <code>repl</code> in case the old history file is used and an error occurred while trying to read and parse it.</p> <p><a id="ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK"></a></p> <h4>ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK<span><a class="mark" href="#errors_err_missing_dynamic_instantiate_hook_1" id="errors_err_missing_dynamic_instantiate_hook_1">#</a></span><span><a class="mark" href="#ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK" id="ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK">#</a></span></h4> <p>Used when an <a href="esm.html">ES6 module</a> loader hook specifies <code>format: 'dynamic'</code> but does not provide a <code>dynamicInstantiate</code> hook.</p> <p><a id="ERR_STREAM_HAS_STRINGDECODER"></a></p> <h4>ERR_STREAM_HAS_STRINGDECODER<span><a class="mark" href="#errors_err_stream_has_stringdecoder" id="errors_err_stream_has_stringdecoder">#</a></span><span><a class="mark" href="#ERR_STREAM_HAS_STRINGDECODER" id="ERR_STREAM_HAS_STRINGDECODER">#</a></span></h4> <p>Used to prevent an abort if a string decoder was set on the Socket.</p> <pre><code class="language-js">const Socket = require('net').Socket; const instance = new Socket(); instance.setEncoding('utf8'); </code></pre> <p><a id="ERR_STRING_TOO_LARGE"></a></p> <h4>ERR_STRING_TOO_LARGE<span><a class="mark" href="#errors_err_string_too_large" id="errors_err_string_too_large">#</a></span><span><a class="mark" href="#ERR_STRING_TOO_LARGE" id="ERR_STRING_TOO_LARGE">#</a></span></h4> <p>An attempt has been made to create a string larger than the maximum allowed size.</p> <h1>Events<span><a class="mark" href="#events_events" id="events_events">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") emit named events that cause <code>Function</code> objects ("listeners") to be called.</p> <p>For instance: a <a href="#net_class_net_server"><code>net.Server</code></a> object emits an event each time a peer connects to it; a <a href="#fs_class_fs_readstream"><code>fs.ReadStream</code></a> emits an event when the file is opened; a <a href="stream.html">stream</a> emits an event whenever data is available to be read.</p> <p>All objects that emit events are instances of the <code>EventEmitter</code> class. These objects expose an <code>eventEmitter.on()</code> function that allows one or more functions to be attached to named events emitted by the object. Typically, event names are camel-cased strings but any valid JavaScript property key can be used.</p> <p>When the <code>EventEmitter</code> object emits an event, all of the functions attached to that specific event are called <em>synchronously</em>. Any values returned by the called listeners are <em>ignored</em> and will be discarded.</p> <p>The following example shows a simple <code>EventEmitter</code> instance with a single listener. The <code>eventEmitter.on()</code> method is used to register listeners, while the <code>eventEmitter.emit()</code> method is used to trigger the event.</p> <pre><code class="language-js">const EventEmitter = require('events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', () => { console.log('an event occurred!'); }); myEmitter.emit('event'); </code></pre> <h2>Passing arguments and <code>this</code> to listeners<span><a class="mark" href="#events_passing_arguments_and_this_to_listeners" id="events_passing_arguments_and_this_to_listeners">#</a></span></h2> <p>The <code>eventEmitter.emit()</code> method allows an arbitrary set of arguments to be passed to the listener functions. It is important to keep in mind that when an ordinary listener function is called, the standard <code>this</code> keyword is intentionally set to reference the <code>EventEmitter</code> instance to which the listener is attached.</p> <pre><code class="language-js">const myEmitter = new MyEmitter(); myEmitter.on('event', function(a, b) { console.log(a, b, this, this === myEmitter); // Prints: // a b MyEmitter { // domain: null, // _events: { event: [Function] }, // _eventsCount: 1, // _maxListeners: undefined } true }); myEmitter.emit('event', 'a', 'b'); </code></pre> <p>It is possible to use ES6 Arrow Functions as listeners, however, when doing so, the <code>this</code> keyword will no longer reference the <code>EventEmitter</code> instance:</p> <pre><code class="language-js">const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { console.log(a, b, this); // Prints: a b {} }); myEmitter.emit('event', 'a', 'b'); </code></pre> <h2>Asynchronous vs. Synchronous<span><a class="mark" href="#events_asynchronous_vs_synchronous" id="events_asynchronous_vs_synchronous">#</a></span></h2> <p>The <code>EventEmitter</code> calls all listeners synchronously in the order in which they were registered. This is important to ensure the proper sequencing of events and to avoid race conditions or logic errors. When appropriate, listener functions can switch to an asynchronous mode of operation using the <code>setImmediate()</code> or <code>process.nextTick()</code> methods:</p> <pre><code class="language-js">const myEmitter = new MyEmitter(); myEmitter.on('event', (a, b) => { setImmediate(() => { console.log('this happens asynchronously'); }); }); myEmitter.emit('event', 'a', 'b'); </code></pre> <h2>Handling events only once<span><a class="mark" href="#events_handling_events_only_once" id="events_handling_events_only_once">#</a></span></h2> <p>When a listener is registered using the <code>eventEmitter.on()</code> method, that listener will be invoked <em>every time</em> the named event is emitted.</p> <pre><code class="language-js">const myEmitter = new MyEmitter(); let m = 0; myEmitter.on('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Prints: 2 </code></pre> <p>Using the <code>eventEmitter.once()</code> method, it is possible to register a listener that is called at most once for a particular event. Once the event is emitted, the listener is unregistered and <em>then</em> called.</p> <pre><code class="language-js">const myEmitter = new MyEmitter(); let m = 0; myEmitter.once('event', () => { console.log(++m); }); myEmitter.emit('event'); // Prints: 1 myEmitter.emit('event'); // Ignored </code></pre> <h2>Error events<span><a class="mark" href="#events_error_events" id="events_error_events">#</a></span></h2> <p>When an error occurs within an <code>EventEmitter</code> instance, the typical action is for an <code>'error'</code> event to be emitted. These are treated as special cases within Node.js.</p> <p>If an <code>EventEmitter</code> does <em>not</em> have at least one listener registered for the <code>'error'</code> event, and an <code>'error'</code> event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.</p> <pre><code class="language-js">const myEmitter = new MyEmitter(); myEmitter.emit('error', new Error('whoops!')); // Throws and crashes Node.js </code></pre> <p>To guard against crashing the Node.js process the <a href="domain.html"><code>domain</code></a> module can be used. (Note, however, that the <code>domain</code> module is deprecated.)</p> <p>As a best practice, listeners should always be added for the <code>'error'</code> events.</p> <pre><code class="language-js">const myEmitter = new MyEmitter(); myEmitter.on('error', (err) => { console.error('whoops! there was an error'); }); myEmitter.emit('error', new Error('whoops!')); // Prints: whoops! there was an error </code></pre> <h2>Class: EventEmitter<span><a class="mark" href="#events_class_eventemitter" id="events_class_eventemitter">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.26</span> </div> <p>The <code>EventEmitter</code> class is defined and exposed by the <code>events</code> module:</p> <pre><code class="language-js">const EventEmitter = require('events'); </code></pre> <p>All <code>EventEmitter</code>s emit the event <code>'newListener'</code> when new listeners are added and <code>'removeListener'</code> when existing listeners are removed.</p> <h3>Event: 'newListener'<span><a class="mark" href="#events_event_newlistener" id="events_event_newlistener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.26</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> The name of the event being listened for</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The event handler function</li> </ul> <p>The <code>EventEmitter</code> instance will emit its own <code>'newListener'</code> event <em>before</em> a listener is added to its internal array of listeners.</p> <p>Listeners registered for the <code>'newListener'</code> event will be passed the event name and a reference to the listener being added.</p> <p>The fact that the event is triggered before adding the listener has a subtle but important side effect: any <em>additional</em> listeners registered to the same <code>name</code> <em>within</em> the <code>'newListener'</code> callback will be inserted <em>before</em> the listener that is in the process of being added.</p> <pre><code class="language-js">const myEmitter = new MyEmitter(); // Only do this once so we don't loop forever myEmitter.once('newListener', (event, listener) => { if (event === 'event') { // Insert a new listener in front myEmitter.on('event', () => { console.log('B'); }); } }); myEmitter.on('event', () => { console.log('A'); }); myEmitter.emit('event'); // Prints: // B // A </code></pre> <h3>Event: 'removeListener'<span><a class="mark" href="#events_event_removelistener" id="events_event_removelistener">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.1.0, v4.7.0</td> <td><p>For listeners attached using <code>.once()</code>, the <code>listener</code> argument now yields the original listener function.</p></td></tr> <tr><td>v0.9.3</td> <td><p><span>Added in: v0.9.3</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> The event name</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The event handler function</li> </ul> <p>The <code>'removeListener'</code> event is emitted <em>after</em> the <code>listener</code> is removed.</p> <h3>EventEmitter.listenerCount(emitter, eventName)<span><a class="mark" href="#events_eventemitter_listenercount_emitter_eventname" id="events_eventemitter_listenercount_emitter_eventname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.12</span><span>Deprecated since: v4.0.0</span> </div> <ul> <li><code>emitter</code> <a href="#events_class_eventemitter" class="type"><EventEmitter></a> The emitter to query</li> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> The event name</li> </ul> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#events_emitter_listenercount_eventname"><code>emitter.listenerCount()</code></a> instead.</div><p></p> <p>A class method that returns the number of listeners for the given <code>eventName</code> registered on the given <code>emitter</code>.</p> <pre><code class="language-js">const myEmitter = new MyEmitter(); myEmitter.on('event', () => {}); myEmitter.on('event', () => {}); console.log(EventEmitter.listenerCount(myEmitter, 'event')); // Prints: 2 </code></pre> <h3>EventEmitter.defaultMaxListeners<span><a class="mark" href="#events_eventemitter_defaultmaxlisteners" id="events_eventemitter_defaultmaxlisteners">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.2</span> </div> <p>By default, a maximum of <code>10</code> listeners can be registered for any single event. This limit can be changed for individual <code>EventEmitter</code> instances using the <a href="#events_emitter_setmaxlisteners_n"><code>emitter.setMaxListeners(n)</code></a> method. To change the default for <em>all</em> <code>EventEmitter</code> instances, the <code>EventEmitter.defaultMaxListeners</code> property can be used. If this value is not a positive number, a <code>TypeError</code> will be thrown.</p> <p>Take caution when setting the <code>EventEmitter.defaultMaxListeners</code> because the change affects <em>all</em> <code>EventEmitter</code> instances, including those created before the change is made. However, calling <a href="#events_emitter_setmaxlisteners_n"><code>emitter.setMaxListeners(n)</code></a> still has precedence over <code>EventEmitter.defaultMaxListeners</code>.</p> <p>Note that this is not a hard limit. The <code>EventEmitter</code> instance will allow more listeners to be added but will output a trace warning to stderr indicating that a "possible EventEmitter memory leak" has been detected. For any single <code>EventEmitter</code>, the <code>emitter.getMaxListeners()</code> and <code>emitter.setMaxListeners()</code> methods can be used to temporarily avoid this warning:</p> <pre><code class="language-js">emitter.setMaxListeners(emitter.getMaxListeners() + 1); emitter.once('event', () => { // do stuff emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); }); </code></pre> <p>The <a href="#cli_trace_warnings"><code>--trace-warnings</code></a> command line flag can be used to display the stack trace for such warnings.</p> <p>The emitted warning can be inspected with <a href="#process_event_warning"><code>process.on('warning')</code></a> and will have the additional <code>emitter</code>, <code>type</code> and <code>count</code> properties, referring to the event emitter instance, the event’s name and the number of attached listeners, respectively. Its <code>name</code> property is set to <code>'MaxListenersExceededWarning'</code>.</p> <h3>emitter.addListener(eventName, listener)<span><a class="mark" href="#events_emitter_addlistener_eventname_listener" id="events_emitter_addlistener_eventname_listener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.26</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Alias for <code>emitter.on(eventName, listener)</code>.</p> <h3>emitter.emit(eventName[, ...args])<span><a class="mark" href="#events_emitter_emit_eventname_args" id="events_emitter_emit_eventname_args">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.26</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li> </ul> <ul> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Synchronously calls each of the listeners registered for the event named <code>eventName</code>, in the order they were registered, passing the supplied arguments to each.</p> <p>Returns <code>true</code> if the event had listeners, <code>false</code> otherwise.</p> <h3>emitter.eventNames()<span><a class="mark" href="#events_emitter_eventnames" id="events_emitter_eventnames">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li> </ul> <p>Returns an array listing the events for which the emitter has registered listeners. The values in the array will be strings or <code>Symbol</code>s.</p> <pre><code class="language-js">const EventEmitter = require('events'); const myEE = new EventEmitter(); myEE.on('foo', () => {}); myEE.on('bar', () => {}); const sym = Symbol('symbol'); myEE.on(sym, () => {}); console.log(myEE.eventNames()); // Prints: [ 'foo', 'bar', Symbol(symbol) ] </code></pre> <h3>emitter.getMaxListeners()<span><a class="mark" href="#events_emitter_getmaxlisteners" id="events_emitter_getmaxlisteners">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.0.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Returns the current max listener value for the <code>EventEmitter</code> which is either set by <a href="#events_emitter_setmaxlisteners_n"><code>emitter.setMaxListeners(n)</code></a> or defaults to <a href="#events_eventemitter_defaultmaxlisteners"><code>EventEmitter.defaultMaxListeners</code></a>.</p> <h3>emitter.listenerCount(eventName)<span><a class="mark" href="#events_emitter_listenercount_eventname" id="events_emitter_listenercount_eventname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v3.2.0</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> The name of the event being listened for</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Returns the number of listeners listening to the event named <code>eventName</code>.</p> <h3>emitter.listeners(eventName)<span><a class="mark" href="#events_emitter_listeners_eventname" id="events_emitter_listeners_eventname">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.0.0</td> <td><p>For listeners attached using <code>.once()</code> this returns the original listeners instead of wrapper functions now.</p></td></tr> <tr><td>v0.1.26</td> <td><p><span>Added in: v0.1.26</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a></li> </ul> <p>Returns a copy of the array of listeners for the event named <code>eventName</code>.</p> <pre><code class="language-js">server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] </code></pre> <h3>emitter.off(eventName, listener)<span><a class="mark" href="#events_emitter_off_eventname_listener" id="events_emitter_off_eventname_listener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Alias for <a href="#events_emitter_removelistener_eventname_listener"><code>emitter.removeListener()</code></a>.</p> <h3>emitter.on(eventName, listener)<span><a class="mark" href="#events_emitter_on_eventname_listener" id="events_emitter_on_eventname_listener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.101</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> The name of the event.</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li> <li>Returns: <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Adds the <code>listener</code> function to the end of the listeners array for the event named <code>eventName</code>. No checks are made to see if the <code>listener</code> has already been added. Multiple calls passing the same combination of <code>eventName</code> and <code>listener</code> will result in the <code>listener</code> being added, and called, multiple times.</p> <pre><code class="language-js">server.on('connection', (stream) => { console.log('someone connected!'); }); </code></pre> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <p>By default, event listeners are invoked in the order they are added. The <code>emitter.prependListener()</code> method can be used as an alternative to add the event listener to the beginning of the listeners array.</p> <pre><code class="language-js">const myEE = new EventEmitter(); myEE.on('foo', () => console.log('a')); myEE.prependListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a </code></pre> <h3>emitter.once(eventName, listener)<span><a class="mark" href="#events_emitter_once_eventname_listener" id="events_emitter_once_eventname_listener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> The name of the event.</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li> <li>Returns: <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Adds a <strong>one-time</strong> <code>listener</code> function for the event named <code>eventName</code>. The next time <code>eventName</code> is triggered, this listener is removed and then invoked.</p> <pre><code class="language-js">server.once('connection', (stream) => { console.log('Ah, we have our first user!'); }); </code></pre> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <p>By default, event listeners are invoked in the order they are added. The <code>emitter.prependOnceListener()</code> method can be used as an alternative to add the event listener to the beginning of the listeners array.</p> <pre><code class="language-js">const myEE = new EventEmitter(); myEE.once('foo', () => console.log('a')); myEE.prependOnceListener('foo', () => console.log('b')); myEE.emit('foo'); // Prints: // b // a </code></pre> <h3>emitter.prependListener(eventName, listener)<span><a class="mark" href="#events_emitter_prependlistener_eventname_listener" id="events_emitter_prependlistener_eventname_listener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> The name of the event.</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li> <li>Returns: <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Adds the <code>listener</code> function to the <em>beginning</em> of the listeners array for the event named <code>eventName</code>. No checks are made to see if the <code>listener</code> has already been added. Multiple calls passing the same combination of <code>eventName</code> and <code>listener</code> will result in the <code>listener</code> being added, and called, multiple times.</p> <pre><code class="language-js">server.prependListener('connection', (stream) => { console.log('someone connected!'); }); </code></pre> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <h3>emitter.prependOnceListener(eventName, listener)<span><a class="mark" href="#events_emitter_prependoncelistener_eventname_listener" id="events_emitter_prependoncelistener_eventname_listener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> The name of the event.</li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The callback function</li> <li>Returns: <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Adds a <strong>one-time</strong> <code>listener</code> function for the event named <code>eventName</code> to the <em>beginning</em> of the listeners array. The next time <code>eventName</code> is triggered, this listener is removed, and then invoked.</p> <pre><code class="language-js">server.prependOnceListener('connection', (stream) => { console.log('Ah, we have our first user!'); }); </code></pre> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <h3>emitter.removeAllListeners([eventName])<span><a class="mark" href="#events_emitter_removealllisteners_eventname" id="events_emitter_removealllisteners_eventname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.26</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li> <li>Returns: <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Removes all listeners, or those of the specified <code>eventName</code>.</p> <p>Note that it is bad practice to remove listeners added elsewhere in the code, particularly when the <code>EventEmitter</code> instance was created by some other component or module (e.g. sockets or file streams).</p> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <h3>emitter.removeListener(eventName, listener)<span><a class="mark" href="#events_emitter_removelistener_eventname_listener" id="events_emitter_removelistener_eventname_listener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.26</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Removes the specified <code>listener</code> from the listener array for the event named <code>eventName</code>.</p> <pre><code class="language-js">const callback = (stream) => { console.log('someone connected!'); }; server.on('connection', callback); // ... server.removeListener('connection', callback); </code></pre> <p><code>removeListener()</code> will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified <code>eventName</code>, then <code>removeListener()</code> must be called multiple times to remove each instance.</p> <p>Note that once an event has been emitted, all listeners attached to it at the time of emitting will be called in order. This implies that any <code>removeListener()</code> or <code>removeAllListeners()</code> calls <em>after</em> emitting and <em>before</em> the last listener finishes execution will not remove them from <code>emit()</code> in progress. Subsequent events will behave as expected.</p> <pre><code class="language-js">const myEmitter = new MyEmitter(); const callbackA = () => { console.log('A'); myEmitter.removeListener('event', callbackB); }; const callbackB = () => { console.log('B'); }; myEmitter.on('event', callbackA); myEmitter.on('event', callbackB); // callbackA removes listener callbackB but it will still be called. // Internal listener array at time of emit [callbackA, callbackB] myEmitter.emit('event'); // Prints: // A // B // callbackB is now removed. // Internal listener array [callbackA] myEmitter.emit('event'); // Prints: // A </code></pre> <p>Because listeners are managed using an internal array, calling this will change the position indices of any listener registered <em>after</em> the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the <code>emitter.listeners()</code> method will need to be recreated.</p> <p>When a single function has been added as a handler multiple times for a single event (as in the example below), <code>removeListener()</code> will remove the most recently added instance. In the example the <code>once('ping')</code> listener is removed:</p> <pre><code class="language-js">const ee = new EventEmitter(); function pong() { console.log('pong'); } ee.on('ping', pong); ee.once('ping', pong); ee.removeListener('ping', pong); ee.emit('ping'); ee.emit('ping'); </code></pre> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <h3>emitter.setMaxListeners(n)<span><a class="mark" href="#events_emitter_setmaxlisteners_n" id="events_emitter_setmaxlisteners_n">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.5</span> </div> <ul> <li><code>n</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>By default <code>EventEmitter</code>s will print a warning if more than <code>10</code> listeners are added for a particular event. This is a useful default that helps finding memory leaks. Obviously, not all events should be limited to just 10 listeners. The <code>emitter.setMaxListeners()</code> method allows the limit to be modified for this specific <code>EventEmitter</code> instance. The value can be set to <code>Infinity</code> (or <code>0</code>) to indicate an unlimited number of listeners.</p> <p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p> <h3>emitter.rawListeners(eventName)<span><a class="mark" href="#events_emitter_rawlisteners_eventname" id="events_emitter_rawlisteners_eventname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function[]></a></li> </ul> <p>Returns a copy of the array of listeners for the event named <code>eventName</code>, including any wrappers (such as those created by <code>.once()</code>).</p> <pre><code class="language-js">const emitter = new EventEmitter(); emitter.once('log', () => console.log('log once')); // Returns a new Array with a function `onceWrapper` which has a property // `listener` which contains the original listener bound above const listeners = emitter.rawListeners('log'); const logFnWrapper = listeners[0]; // logs "log once" to the console and does not unbind the `once` event logFnWrapper.listener(); // logs "log once" to the console and removes the listener logFnWrapper(); emitter.on('log', () => console.log('log persistently')); // will return a new Array with a single function bound by `.on()` above const newListeners = emitter.rawListeners('log'); // logs "log persistently" twice newListeners[0](); emitter.emit('log'); </code></pre> <h2>events.once(emitter, name)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/events.js#L487">[src]</a><span><a class="mark" href="#events_events_once_emitter_name" id="events_events_once_emitter_name">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><code>emitter</code> <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Creates a <code>Promise</code> that is resolved when the <code>EventEmitter</code> emits the given event or that is rejected when the <code>EventEmitter</code> emits <code>'error'</code>. The <code>Promise</code> will resolve with an array of all the arguments emitted to the given event.</p> <pre><code class="language-js">const { once, EventEmitter } = require('events'); async function run() { const ee = new EventEmitter(); process.nextTick(() => { ee.emit('myevent', 42); }); const [value] = await once(ee, 'myevent'); console.log(value); const err = new Error('kaboom'); process.nextTick(() => { ee.emit('error', err); }); try { await once(ee, 'myevent'); } catch (err) { console.log('error happened', err); } } run(); </code></pre> <h1>File System<span><a class="mark" href="#fs_file_system" id="fs_file_system">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>fs</code> module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions.</p> <p>To use this module:</p> <pre><code class="language-js">const fs = require('fs'); </code></pre> <p>All file system operations have synchronous and asynchronous forms.</p> <p>The asynchronous form always takes a completion callback as its last argument. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation was completed successfully, then the first argument will be <code>null</code> or <code>undefined</code>.</p> <pre><code class="language-js">const fs = require('fs'); fs.unlink('/tmp/hello', (err) => { if (err) throw err; console.log('successfully deleted /tmp/hello'); }); </code></pre> <p>Exceptions that occur using synchronous operations are thrown immediately and may be handled using <code>try</code>/<code>catch</code>, or may be allowed to bubble up.</p> <pre><code class="language-js">const fs = require('fs'); try { fs.unlinkSync('/tmp/hello'); console.log('successfully deleted /tmp/hello'); } catch (err) { // handle the error } </code></pre> <p>There is no guaranteed ordering when using asynchronous methods. So the following is prone to error because the <code>fs.stat()</code> operation may complete before the <code>fs.rename()</code> operation:</p> <pre><code class="language-js">fs.rename('/tmp/hello', '/tmp/world', (err) => { if (err) throw err; console.log('renamed complete'); }); fs.stat('/tmp/world', (err, stats) => { if (err) throw err; console.log(`stats: ${JSON.stringify(stats)}`); }); </code></pre> <p>To correctly order the operations, move the <code>fs.stat()</code> call into the callback of the <code>fs.rename()</code> operation:</p> <pre><code class="language-js">fs.rename('/tmp/hello', '/tmp/world', (err) => { if (err) throw err; fs.stat('/tmp/world', (err, stats) => { if (err) throw err; console.log(`stats: ${JSON.stringify(stats)}`); }); }); </code></pre> <p>In busy processes, the programmer is <em>strongly encouraged</em> to use the asynchronous versions of these calls. The synchronous versions will block the entire process until they complete — halting all connections.</p> <p>While it is not recommended, most fs functions allow the callback argument to be omitted, in which case a default callback is used that rethrows errors. To get a trace to the original call site, set the <code>NODE_DEBUG</code> environment variable:</p> <p>Omitting the callback function on asynchronous fs functions is deprecated and may result in an error being thrown in the future.</p> <pre><code class="language-txt">$ cat script.js function bad() { require('fs').readFile('/'); } bad(); $ env NODE_DEBUG=fs node script.js fs.js:88 throw backtrace; ^ Error: EISDIR: illegal operation on a directory, read <stack trace.> </code></pre> <h2>File paths<span><a class="mark" href="#fs_file_paths" id="fs_file_paths">#</a></span></h2> <p>Most <code>fs</code> operations accept filepaths that may be specified in the form of a string, a <a href="#buffer_buffer"><code>Buffer</code></a>, or a <a href="#url_the_whatwg_url_api"><code>URL</code></a> object using the <code>file:</code> protocol.</p> <p>String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as specified by <code>process.cwd()</code>.</p> <p>Example using an absolute path on POSIX:</p> <pre><code class="language-js">const fs = require('fs'); fs.open('/open/some/file.txt', 'r', (err, fd) => { if (err) throw err; fs.close(fd, (err) => { if (err) throw err; }); }); </code></pre> <p>Example using a relative path on POSIX (relative to <code>process.cwd()</code>):</p> <pre><code class="language-js">fs.open('file.txt', 'r', (err, fd) => { if (err) throw err; fs.close(fd, (err) => { if (err) throw err; }); }); </code></pre> <p>Paths specified using a <a href="#buffer_buffer"><code>Buffer</code></a> are useful primarily on certain POSIX operating systems that treat file paths as opaque byte sequences. On such systems, it is possible for a single file path to contain sub-sequences that use multiple character encodings. As with string paths, <code>Buffer</code> paths may be relative or absolute:</p> <p>Example using an absolute path on POSIX:</p> <pre><code class="language-js">fs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => { if (err) throw err; fs.close(fd, (err) => { if (err) throw err; }); }); </code></pre> <p>On Windows, Node.js follows the concept of per-drive working directory. This behavior can be observed when using a drive path without a backslash. For example <code>fs.readdirSync('c:\\')</code> can potentially return a different result than <code>fs.readdirSync('c:')</code>. For more information, see <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths">this MSDN page</a>.</p> <h3>URL object support<span><a class="mark" href="#fs_url_object_support" id="fs_url_object_support">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.6.0</span> </div> <p>For most <code>fs</code> module functions, the <code>path</code> or <code>filename</code> argument may be passed as a WHATWG <a href="#url_the_whatwg_url_api"><code>URL</code></a> object. Only <a href="#url_the_whatwg_url_api"><code>URL</code></a> objects using the <code>file:</code> protocol are supported.</p> <pre><code class="language-js">const fs = require('fs'); const fileUrl = new URL('file:///tmp/hello'); fs.readFileSync(fileUrl); </code></pre> <p><code>file:</code> URLs are always absolute paths.</p> <p>Using WHATWG <a href="#url_the_whatwg_url_api"><code>URL</code></a> objects might introduce platform-specific behaviors.</p> <p>On Windows, <code>file:</code> URLs with a hostname convert to UNC paths, while <code>file:</code> URLs with drive letters convert to local absolute paths. <code>file:</code> URLs without a hostname nor a drive letter will result in a throw:</p> <pre><code class="language-js">// On Windows : // - WHATWG file URLs with hostname convert to UNC path // file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file fs.readFileSync(new URL('file://hostname/p/a/t/h/file')); // - WHATWG file URLs with drive letters convert to absolute path // file:///C:/tmp/hello => C:\tmp\hello fs.readFileSync(new URL('file:///C:/tmp/hello')); // - WHATWG file URLs without hostname must have a drive letters fs.readFileSync(new URL('file:///notdriveletter/p/a/t/h/file')); fs.readFileSync(new URL('file:///c/p/a/t/h/file')); // TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute </code></pre> <p><code>file:</code> URLs with drive letters must use <code>:</code> as a separator just after the drive letter. Using another separator will result in a throw.</p> <p>On all other platforms, <code>file:</code> URLs with a hostname are unsupported and will result in a throw:</p> <pre><code class="language-js">// On other platforms: // - WHATWG file URLs with hostname are unsupported // file://hostname/p/a/t/h/file => throw! fs.readFileSync(new URL('file://hostname/p/a/t/h/file')); // TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute // - WHATWG file URLs convert to absolute path // file:///tmp/hello => /tmp/hello fs.readFileSync(new URL('file:///tmp/hello')); </code></pre> <p>A <code>file:</code> URL having encoded slash characters will result in a throw on all platforms:</p> <pre><code class="language-js">// On Windows fs.readFileSync(new URL('file:///C:/p/a/t/h/%2F')); fs.readFileSync(new URL('file:///C:/p/a/t/h/%2f')); /* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded \ or / characters */ // On POSIX fs.readFileSync(new URL('file:///p/a/t/h/%2F')); fs.readFileSync(new URL('file:///p/a/t/h/%2f')); /* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded / characters */ </code></pre> <p>On Windows, <code>file:</code> URLs having encoded backslash will result in a throw:</p> <pre><code class="language-js">// On Windows fs.readFileSync(new URL('file:///C:/path/%5C')); fs.readFileSync(new URL('file:///C:/path/%5c')); /* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded \ or / characters */ </code></pre> <h2>File Descriptors<span><a class="mark" href="#fs_file_descriptors" id="fs_file_descriptors">#</a></span></h2> <p>On POSIX systems, for every process, the kernel maintains a table of currently open files and resources. Each open file is assigned a simple numeric identifier called a <em>file descriptor</em>. At the system-level, all file system operations use these file descriptors to identify and track each specific file. Windows systems use a different but conceptually similar mechanism for tracking resources. To simplify things for users, Node.js abstracts away the specific differences between operating systems and assigns all open files a numeric file descriptor.</p> <p>The <code>fs.open()</code> method is used to allocate a new file descriptor. Once allocated, the file descriptor may be used to read data from, write data to, or request information about the file.</p> <pre><code class="language-js">fs.open('/open/some/file.txt', 'r', (err, fd) => { if (err) throw err; fs.fstat(fd, (err, stat) => { if (err) throw err; // use stat // always close the file descriptor! fs.close(fd, (err) => { if (err) throw err; }); }); }); </code></pre> <p>Most operating systems limit the number of file descriptors that may be open at any given time so it is critical to close the descriptor when operations are completed. Failure to do so will result in a memory leak that will eventually cause an application to crash.</p> <h2>Threadpool Usage<span><a class="mark" href="#fs_threadpool_usage" id="fs_threadpool_usage">#</a></span></h2> <p>All file system APIs except <code>fs.FSWatcher()</code> and those that are explicitly synchronous use libuv's threadpool, which can have surprising and negative performance implications for some applications. See the <a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p> <h2>Class: fs.Dirent<span><a class="mark" href="#fs_class_fs_dirent" id="fs_class_fs_dirent">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <p>When <a href="#fs_fs_readdir_path_options_callback"><code>fs.readdir()</code></a> or <a href="#fs_fs_readdirsync_path_options"><code>fs.readdirSync()</code></a> is called with the <code>withFileTypes</code> option set to <code>true</code>, the resulting array is filled with <code>fs.Dirent</code> objects, rather than strings or <code>Buffers</code>.</p> <h3>dirent.isBlockDevice()<span><a class="mark" href="#fs_dirent_isblockdevice" id="fs_dirent_isblockdevice">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a block device.</p> <h3>dirent.isCharacterDevice()<span><a class="mark" href="#fs_dirent_ischaracterdevice" id="fs_dirent_ischaracterdevice">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a character device.</p> <h3>dirent.isDirectory()<span><a class="mark" href="#fs_dirent_isdirectory" id="fs_dirent_isdirectory">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a file system directory.</p> <h3>dirent.isFIFO()<span><a class="mark" href="#fs_dirent_isfifo" id="fs_dirent_isfifo">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a first-in-first-out (FIFO) pipe.</p> <h3>dirent.isFile()<span><a class="mark" href="#fs_dirent_isfile" id="fs_dirent_isfile">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a regular file.</p> <h3>dirent.isSocket()<span><a class="mark" href="#fs_dirent_issocket" id="fs_dirent_issocket">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a socket.</p> <h3>dirent.isSymbolicLink()<span><a class="mark" href="#fs_dirent_issymboliclink" id="fs_dirent_issymboliclink">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a symbolic link.</p> <h3>dirent.name<span><a class="mark" href="#fs_dirent_name" id="fs_dirent_name">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>The file name that this <code>fs.Dirent</code> object refers to. The type of this value is determined by the <code>options.encoding</code> passed to <a href="#fs_fs_readdir_path_options_callback"><code>fs.readdir()</code></a> or <a href="#fs_fs_readdirsync_path_options"><code>fs.readdirSync()</code></a>.</p> <h2>Class: fs.FSWatcher<span><a class="mark" href="#fs_class_fs_fswatcher" id="fs_class_fs_fswatcher">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <p>A successful call to <a href="#fs_fs_watch_filename_options_listener"><code>fs.watch()</code></a> method will return a new <code>fs.FSWatcher</code> object.</p> <p>All <code>fs.FSWatcher</code> objects are <a href="events.html"><code>EventEmitter</code></a>'s that will emit a <code>'change'</code> event whenever a specific watched file is modified.</p> <h3>Event: 'change'<span><a class="mark" href="#fs_event_change" id="fs_event_change">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <ul> <li><code>eventType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The type of change event that has occurred</li> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> The filename that changed (if relevant/available)</li> </ul> <p>Emitted when something changes in a watched directory or file. See more details in <a href="#fs_fs_watch_filename_options_listener"><code>fs.watch()</code></a>.</p> <p>The <code>filename</code> argument may not be provided depending on operating system support. If <code>filename</code> is provided, it will be provided as a <code>Buffer</code> if <code>fs.watch()</code> is called with its <code>encoding</code> option set to <code>'buffer'</code>, otherwise <code>filename</code> will be a UTF-8 string.</p> <pre><code class="language-js">// Example when handled through fs.watch() listener fs.watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => { if (filename) { console.log(filename); // Prints: <Buffer ...> } }); </code></pre> <h3>Event: 'close'<span><a class="mark" href="#fs_event_close" id="fs_event_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>Emitted when the watcher stops watching for changes. The closed <code>fs.FSWatcher</code> object is no longer usable in the event handler.</p> <h3>Event: 'error'<span><a class="mark" href="#fs_event_error" id="fs_event_error">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Emitted when an error occurs while watching the file. The errored <code>fs.FSWatcher</code> object is no longer usable in the event handler.</p> <h3>watcher.close()<span><a class="mark" href="#fs_watcher_close" id="fs_watcher_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <p>Stop watching for changes on the given <code>fs.FSWatcher</code>. Once stopped, the <code>fs.FSWatcher</code> object is no longer usable.</p> <h2>Class: fs.ReadStream<span><a class="mark" href="#fs_class_fs_readstream" id="fs_class_fs_readstream">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.93</span> </div> <p>A successful call to <code>fs.createReadStream()</code> will return a new <code>fs.ReadStream</code> object.</p> <p>All <code>fs.ReadStream</code> objects are <a href="#stream_class_stream_readable">Readable Streams</a>.</p> <h3>Event: 'close'<span><a class="mark" href="#fs_event_close_1" id="fs_event_close_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.93</span> </div> <p>Emitted when the <code>fs.ReadStream</code>'s underlying file descriptor has been closed.</p> <h3>Event: 'open'<span><a class="mark" href="#fs_event_open" id="fs_event_open">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.93</span> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Integer file descriptor used by the <code>ReadStream</code>.</li> </ul> <p>Emitted when the <code>fs.ReadStream</code>'s file descriptor has been opened.</p> <h3>Event: 'ready'<span><a class="mark" href="#fs_event_ready" id="fs_event_ready">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.11.0</span> </div> <p>Emitted when the <code>fs.ReadStream</code> is ready to be used.</p> <p>Fires immediately after <code>'open'</code>.</p> <h3>readStream.bytesRead<span><a class="mark" href="#fs_readstream_bytesread" id="fs_readstream_bytesread">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The number of bytes that have been read so far.</p> <h3>readStream.path<span><a class="mark" href="#fs_readstream_path" id="fs_readstream_path">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.93</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>The path to the file the stream is reading from as specified in the first argument to <code>fs.createReadStream()</code>. If <code>path</code> is passed as a string, then <code>readStream.path</code> will be a string. If <code>path</code> is passed as a <code>Buffer</code>, then <code>readStream.path</code> will be a <code>Buffer</code>.</p> <h3>readStream.pending<span><a class="mark" href="#fs_readstream_pending" id="fs_readstream_pending">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>This property is <code>true</code> if the underlying file has not been opened yet, i.e. before the <code>'ready'</code> event is emitted.</p> <h2>Class: fs.Stats<span><a class="mark" href="#fs_class_fs_stats" id="fs_class_fs_stats">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.1.0</td> <td><p>Added times as numbers.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <p>A <code>fs.Stats</code> object provides information about a file.</p> <p>Objects returned from <a href="#fs_fs_stat_path_options_callback"><code>fs.stat()</code></a>, <a href="#fs_fs_lstat_path_options_callback"><code>fs.lstat()</code></a> and <a href="#fs_fs_fstat_fd_options_callback"><code>fs.fstat()</code></a> and their synchronous counterparts are of this type. If <code>bigint</code> in the <code>options</code> passed to those methods is true, the numeric values will be <code>bigint</code> instead of <code>number</code>.</p> <pre><code class="language-console">Stats { dev: 2114, ino: 48064969, mode: 33188, nlink: 1, uid: 85, gid: 100, rdev: 0, size: 527, blksize: 4096, blocks: 8, atimeMs: 1318289051000.1, mtimeMs: 1318289051000.1, ctimeMs: 1318289051000.1, birthtimeMs: 1318289051000.1, atime: Mon, 10 Oct 2011 23:24:11 GMT, mtime: Mon, 10 Oct 2011 23:24:11 GMT, ctime: Mon, 10 Oct 2011 23:24:11 GMT, birthtime: Mon, 10 Oct 2011 23:24:11 GMT } </code></pre> <p><code>bigint</code> version:</p> <pre><code class="language-console">Stats { dev: 2114n, ino: 48064969n, mode: 33188n, nlink: 1n, uid: 85n, gid: 100n, rdev: 0n, size: 527n, blksize: 4096n, blocks: 8n, atimeMs: 1318289051000n, mtimeMs: 1318289051000n, ctimeMs: 1318289051000n, birthtimeMs: 1318289051000n, atime: Mon, 10 Oct 2011 23:24:11 GMT, mtime: Mon, 10 Oct 2011 23:24:11 GMT, ctime: Mon, 10 Oct 2011 23:24:11 GMT, birthtime: Mon, 10 Oct 2011 23:24:11 GMT } </code></pre> <h3>stats.isBlockDevice()<span><a class="mark" href="#fs_stats_isblockdevice" id="fs_stats_isblockdevice">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.10</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a block device.</p> <h3>stats.isCharacterDevice()<span><a class="mark" href="#fs_stats_ischaracterdevice" id="fs_stats_ischaracterdevice">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.10</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a character device.</p> <h3>stats.isDirectory()<span><a class="mark" href="#fs_stats_isdirectory" id="fs_stats_isdirectory">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.10</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a file system directory.</p> <h3>stats.isFIFO()<span><a class="mark" href="#fs_stats_isfifo" id="fs_stats_isfifo">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.10</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a first-in-first-out (FIFO) pipe.</p> <h3>stats.isFile()<span><a class="mark" href="#fs_stats_isfile" id="fs_stats_isfile">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.10</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a regular file.</p> <h3>stats.isSocket()<span><a class="mark" href="#fs_stats_issocket" id="fs_stats_issocket">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.10</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a socket.</p> <h3>stats.isSymbolicLink()<span><a class="mark" href="#fs_stats_issymboliclink" id="fs_stats_issymboliclink">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.10</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a symbolic link.</p> <p>This method is only valid when using <a href="#fs_fs_lstat_path_options_callback"><code>fs.lstat()</code></a>.</p> <h3>stats.dev<span><a class="mark" href="#fs_stats_dev" id="fs_stats_dev">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The numeric identifier of the device containing the file.</p> <h3>stats.ino<span><a class="mark" href="#fs_stats_ino" id="fs_stats_ino">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The file system specific "Inode" number for the file.</p> <h3>stats.mode<span><a class="mark" href="#fs_stats_mode" id="fs_stats_mode">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>A bit-field describing the file type and mode.</p> <h3>stats.nlink<span><a class="mark" href="#fs_stats_nlink" id="fs_stats_nlink">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The number of hard-links that exist for the file.</p> <h3>stats.uid<span><a class="mark" href="#fs_stats_uid" id="fs_stats_uid">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The numeric user identifier of the user that owns the file (POSIX).</p> <h3>stats.gid<span><a class="mark" href="#fs_stats_gid" id="fs_stats_gid">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The numeric group identifier of the group that owns the file (POSIX).</p> <h3>stats.rdev<span><a class="mark" href="#fs_stats_rdev" id="fs_stats_rdev">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>A numeric device identifier if the file is considered "special".</p> <h3>stats.size<span><a class="mark" href="#fs_stats_size" id="fs_stats_size">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The size of the file in bytes.</p> <h3>stats.blksize<span><a class="mark" href="#fs_stats_blksize" id="fs_stats_blksize">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The file system block size for i/o operations.</p> <h3>stats.blocks<span><a class="mark" href="#fs_stats_blocks" id="fs_stats_blocks">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The number of blocks allocated for this file.</p> <h3>stats.atimeMs<span><a class="mark" href="#fs_stats_atimems" id="fs_stats_atimems">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.1.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The timestamp indicating the last time this file was accessed expressed in milliseconds since the POSIX Epoch.</p> <h3>stats.mtimeMs<span><a class="mark" href="#fs_stats_mtimems" id="fs_stats_mtimems">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.1.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The timestamp indicating the last time this file was modified expressed in milliseconds since the POSIX Epoch.</p> <h3>stats.ctimeMs<span><a class="mark" href="#fs_stats_ctimems" id="fs_stats_ctimems">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.1.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The timestamp indicating the last time the file status was changed expressed in milliseconds since the POSIX Epoch.</p> <h3>stats.birthtimeMs<span><a class="mark" href="#fs_stats_birthtimems" id="fs_stats_birthtimems">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.1.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The timestamp indicating the creation time of this file expressed in milliseconds since the POSIX Epoch.</p> <h3>stats.atime<span><a class="mark" href="#fs_stats_atime" id="fs_stats_atime">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.13</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> </ul> <p>The timestamp indicating the last time this file was accessed.</p> <h3>stats.mtime<span><a class="mark" href="#fs_stats_mtime" id="fs_stats_mtime">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.13</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> </ul> <p>The timestamp indicating the last time this file was modified.</p> <h3>stats.ctime<span><a class="mark" href="#fs_stats_ctime" id="fs_stats_ctime">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.13</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> </ul> <p>The timestamp indicating the last time the file status was changed.</p> <h3>stats.birthtime<span><a class="mark" href="#fs_stats_birthtime" id="fs_stats_birthtime">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.13</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> </ul> <p>The timestamp indicating the creation time of this file.</p> <h3>Stat Time Values<span><a class="mark" href="#fs_stat_time_values" id="fs_stat_time_values">#</a></span></h3> <p>The <code>atimeMs</code>, <code>mtimeMs</code>, <code>ctimeMs</code>, <code>birthtimeMs</code> properties are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type">numbers</a> that hold the corresponding times in milliseconds. Their precision is platform specific. <code>atime</code>, <code>mtime</code>, <code>ctime</code>, and <code>birthtime</code> are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date"><code>Date</code></a> object alternate representations of the various times. The <code>Date</code> and number values are not connected. Assigning a new number value, or mutating the <code>Date</code> value, will not be reflected in the corresponding alternate representation.</p> <p>The times in the stat object have the following semantics:</p> <ul> <li><code>atime</code> "Access Time" - Time when file data last accessed. Changed by the <a href="http://man7.org/linux/man-pages/man2/mknod.2.html"><code>mknod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a>, and <a href="http://man7.org/linux/man-pages/man2/read.2.html"><code>read(2)</code></a> system calls.</li> <li><code>mtime</code> "Modified Time" - Time when file data last modified. Changed by the <a href="http://man7.org/linux/man-pages/man2/mknod.2.html"><code>mknod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a>, and <a href="http://man7.org/linux/man-pages/man2/write.2.html"><code>write(2)</code></a> system calls.</li> <li><code>ctime</code> "Change Time" - Time when file status was last changed (inode data modification). Changed by the <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/mknod.2.html"><code>mknod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/rename.2.html"><code>rename(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/read.2.html"><code>read(2)</code></a>, and <a href="http://man7.org/linux/man-pages/man2/write.2.html"><code>write(2)</code></a> system calls.</li> <li><code>birthtime</code> "Birth Time" - Time of file creation. Set once when the file is created. On filesystems where birthtime is not available, this field may instead hold either the <code>ctime</code> or <code>1970-01-01T00:00Z</code> (ie, unix epoch timestamp <code>0</code>). This value may be greater than <code>atime</code> or <code>mtime</code> in this case. On Darwin and other FreeBSD variants, also set if the <code>atime</code> is explicitly set to an earlier value than the current <code>birthtime</code> using the <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a> system call.</li> </ul> <p>Prior to Node.js 0.12, the <code>ctime</code> held the <code>birthtime</code> on Windows systems. As of 0.12, <code>ctime</code> is not "creation time", and on Unix systems, it never was.</p> <h2>Class: fs.WriteStream<span><a class="mark" href="#fs_class_fs_writestream" id="fs_class_fs_writestream">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.93</span> </div> <p><code>WriteStream</code> is a <a href="#stream_class_stream_writable">Writable Stream</a>.</p> <h3>Event: 'close'<span><a class="mark" href="#fs_event_close_2" id="fs_event_close_2">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.93</span> </div> <p>Emitted when the <code>WriteStream</code>'s underlying file descriptor has been closed.</p> <h3>Event: 'open'<span><a class="mark" href="#fs_event_open_1" id="fs_event_open_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.93</span> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Integer file descriptor used by the <code>WriteStream</code>.</li> </ul> <p>Emitted when the <code>WriteStream</code>'s file is opened.</p> <h3>Event: 'ready'<span><a class="mark" href="#fs_event_ready_1" id="fs_event_ready_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.11.0</span> </div> <p>Emitted when the <code>fs.WriteStream</code> is ready to be used.</p> <p>Fires immediately after <code>'open'</code>.</p> <h3>writeStream.bytesWritten<span><a class="mark" href="#fs_writestream_byteswritten" id="fs_writestream_byteswritten">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.4.7</span> </div> <p>The number of bytes written so far. Does not include data that is still queued for writing.</p> <h3>writeStream.path<span><a class="mark" href="#fs_writestream_path" id="fs_writestream_path">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.93</span> </div> <p>The path to the file the stream is writing to as specified in the first argument to <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a>. If <code>path</code> is passed as a string, then <code>writeStream.path</code> will be a string. If <code>path</code> is passed as a <code>Buffer</code>, then <code>writeStream.path</code> will be a <code>Buffer</code>.</p> <h3>writeStream.pending<span><a class="mark" href="#fs_writestream_pending" id="fs_writestream_pending">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>This property is <code>true</code> if the underlying file has not been opened yet, i.e. before the <code>'ready'</code> event is emitted.</p> <h2>fs.access(path[, mode], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L166">[src]</a><span><a class="mark" href="#fs_fs_access_path_mode_callback" id="fs_fs_access_path_mode_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v6.3.0</td> <td><p>The constants like <code>fs.R_OK</code>, etc which were present directly on <code>fs</code> were moved into <code>fs.constants</code> as a soft deprecation. Thus for Node.js <code>< v6.3.0</code> use <code>fs</code> to access those constants, or do something like <code>(fs.constants || fs).R_OK</code> to work with all versions.</p></td></tr> <tr><td>v0.11.15</td> <td><p><span>Added in: v0.11.15</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>fs.constants.F_OK</code></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Tests a user's permissions for the file or directory specified by <code>path</code>. The <code>mode</code> argument is an optional integer that specifies the accessibility checks to be performed. Check <a href="#fs_file_access_constants">File Access Constants</a> for possible values of <code>mode</code>. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. <code>fs.constants.W_OK | fs.constants.R_OK</code>).</p> <p>The final argument, <code>callback</code>, is a callback function that is invoked with a possible error argument. If any of the accessibility checks fail, the error argument will be an <code>Error</code> object. The following examples check if <code>package.json</code> exists, and if it is readable or writable.</p> <pre><code class="language-js">const file = 'package.json'; // Check if the file exists in the current directory. fs.access(file, fs.constants.F_OK, (err) => { console.log(`${file} ${err ? 'does not exist' : 'exists'}`); }); // Check if the file is readable. fs.access(file, fs.constants.R_OK, (err) => { console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); }); // Check if the file is writable. fs.access(file, fs.constants.W_OK, (err) => { console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); }); // Check if the file exists in the current directory, and if it is writable. fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => { if (err) { console.error( `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`); } else { console.log(`${file} exists, and it is writable`); } }); </code></pre> <p>Using <code>fs.access()</code> to check for the accessibility of a file before calling <code>fs.open()</code>, <code>fs.readFile()</code> or <code>fs.writeFile()</code> is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.</p> <p><strong>write (NOT RECOMMENDED)</strong></p> <pre><code class="language-js">fs.access('myfile', (err) => { if (!err) { console.error('myfile already exists'); return; } fs.open('myfile', 'wx', (err, fd) => { if (err) throw err; writeMyData(fd); }); }); </code></pre> <p><strong>write (RECOMMENDED)</strong></p> <pre><code class="language-js">fs.open('myfile', 'wx', (err, fd) => { if (err) { if (err.code === 'EEXIST') { console.error('myfile already exists'); return; } throw err; } writeMyData(fd); }); </code></pre> <p><strong>read (NOT RECOMMENDED)</strong></p> <pre><code class="language-js">fs.access('myfile', (err) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } fs.open('myfile', 'r', (err, fd) => { if (err) throw err; readMyData(fd); }); }); </code></pre> <p><strong>read (RECOMMENDED)</strong></p> <pre><code class="language-js">fs.open('myfile', 'r', (err, fd) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } readMyData(fd); }); </code></pre> <p>The "not recommended" examples above check for accessibility and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.</p> <p>In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process.</p> <p>On Windows, access-control policies (ACLs) on a directory may limit access to a file or directory. The <code>fs.access()</code> function, however, does not check the ACL and therefore may report that a path is accessible even if the ACL restricts the user from reading or writing to it.</p> <h2>fs.accessSync(path[, mode])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L181">[src]</a><span><a class="mark" href="#fs_fs_accesssync_path_mode" id="fs_fs_accesssync_path_mode">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.11.15</td> <td><p><span>Added in: v0.11.15</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>fs.constants.F_OK</code></li> </ul> <p>Synchronously tests a user's permissions for the file or directory specified by <code>path</code>. The <code>mode</code> argument is an optional integer that specifies the accessibility checks to be performed. Check <a href="#fs_file_access_constants">File Access Constants</a> for possible values of <code>mode</code>. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. <code>fs.constants.W_OK | fs.constants.R_OK</code>).</p> <p>If any of the accessibility checks fail, an <code>Error</code> will be thrown. Otherwise, the method will return <code>undefined</code>.</p> <pre><code class="language-js">try { fs.accessSync('etc/passwd', fs.constants.R_OK | fs.constants.W_OK); console.log('can read/write'); } catch (err) { console.error('no access!'); } </code></pre> <h2>fs.appendFile(path, data[, options], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1216">[src]</a><span><a class="mark" href="#fs_fs_appendfile_path_data_options_callback" id="fs_fs_appendfile_path_data_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The passed <code>options</code> object will never be modified.</p></td></tr> <tr><td>v5.0.0</td> <td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr> <tr><td>v0.6.7</td> <td><p><span>Added in: v0.6.7</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> filename or file descriptor</li> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronously append data to a file, creating the file if it does not yet exist. <code>data</code> can be a string or a <a href="#buffer_buffer"><code>Buffer</code></a>.</p> <pre><code class="language-js">fs.appendFile('message.txt', 'data to append', (err) => { if (err) throw err; console.log('The "data to append" was appended to file!'); }); </code></pre> <p>If <code>options</code> is a string, then it specifies the encoding:</p> <pre><code class="language-js">fs.appendFile('message.txt', 'data to append', 'utf8', callback); </code></pre> <p>The <code>path</code> may be specified as a numeric file descriptor that has been opened for appending (using <code>fs.open()</code> or <code>fs.openSync()</code>). The file descriptor will not be closed automatically.</p> <pre><code class="language-js">fs.open('message.txt', 'a', (err, fd) => { if (err) throw err; fs.appendFile(fd, 'data to append', 'utf8', (err) => { fs.close(fd, (err) => { if (err) throw err; }); if (err) throw err; }); }); </code></pre> <h2>fs.appendFileSync(path, data[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1230">[src]</a><span><a class="mark" href="#fs_fs_appendfilesync_path_data_options" id="fs_fs_appendfilesync_path_data_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.0.0</td> <td><p>The passed <code>options</code> object will never be modified.</p></td></tr> <tr><td>v5.0.0</td> <td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr> <tr><td>v0.6.7</td> <td><p><span>Added in: v0.6.7</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> filename or file descriptor</li> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li> </ul> </li> </ul> <p>Synchronously append data to a file, creating the file if it does not yet exist. <code>data</code> can be a string or a <a href="#buffer_buffer"><code>Buffer</code></a>.</p> <pre><code class="language-js">try { fs.appendFileSync('message.txt', 'data to append'); console.log('The "data to append" was appended to file!'); } catch (err) { /* Handle the error */ } </code></pre> <p>If <code>options</code> is a string, then it specifies the encoding:</p> <pre><code class="language-js">fs.appendFileSync('message.txt', 'data to append', 'utf8'); </code></pre> <p>The <code>path</code> may be specified as a numeric file descriptor that has been opened for appending (using <code>fs.open()</code> or <code>fs.openSync()</code>). The file descriptor will not be closed automatically.</p> <pre><code class="language-js">let fd; try { fd = fs.openSync('message.txt', 'a'); fs.appendFileSync(fd, 'data to append', 'utf8'); } catch (err) { /* Handle the error */ } finally { if (fd !== undefined) fs.closeSync(fd); } </code></pre> <h2>fs.chmod(path, mode, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1009">[src]</a><span><a class="mark" href="#fs_fs_chmod_path_mode_callback" id="fs_fs_chmod_path_mode_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.1.30</td> <td><p><span>Added in: v0.1.30</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback.</p> <p>See also: <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a>.</p> <h3>File modes<span><a class="mark" href="#fs_file_modes" id="fs_file_modes">#</a></span></h3> <p>The <code>mode</code> argument used in both the <code>fs.chmod()</code> and <code>fs.chmodSync()</code> methods is a numeric bitmask created using a logical OR of the following constants:</p> <table><thead><tr><th>Constant</th><th>Octal</th><th>Description</th></tr></thead><tbody><tr><td><code>fs.constants.S_IRUSR</code></td><td><code>0o400</code></td><td>read by owner</td></tr><tr><td><code>fs.constants.S_IWUSR</code></td><td><code>0o200</code></td><td>write by owner</td></tr><tr><td><code>fs.constants.S_IXUSR</code></td><td><code>0o100</code></td><td>execute/search by owner</td></tr><tr><td><code>fs.constants.S_IRGRP</code></td><td><code>0o40</code></td><td>read by group</td></tr><tr><td><code>fs.constants.S_IWGRP</code></td><td><code>0o20</code></td><td>write by group</td></tr><tr><td><code>fs.constants.S_IXGRP</code></td><td><code>0o10</code></td><td>execute/search by group</td></tr><tr><td><code>fs.constants.S_IROTH</code></td><td><code>0o4</code></td><td>read by others</td></tr><tr><td><code>fs.constants.S_IWOTH</code></td><td><code>0o2</code></td><td>write by others</td></tr><tr><td><code>fs.constants.S_IXOTH</code></td><td><code>0o1</code></td><td>execute/search by others</td></tr></tbody></table> <p>An easier method of constructing the <code>mode</code> is to use a sequence of three octal digits (e.g. <code>765</code>). The left-most digit (<code>7</code> in the example), specifies the permissions for the file owner. The middle digit (<code>6</code> in the example), specifies permissions for the group. The right-most digit (<code>5</code> in the example), specifies the permissions for others.</p> <table><thead><tr><th>Number</th><th>Description</th></tr></thead><tbody><tr><td><code>7</code></td><td>read, write, and execute</td></tr><tr><td><code>6</code></td><td>read and write</td></tr><tr><td><code>5</code></td><td>read and execute</td></tr><tr><td><code>4</code></td><td>read only</td></tr><tr><td><code>3</code></td><td>write and execute</td></tr><tr><td><code>2</code></td><td>write only</td></tr><tr><td><code>1</code></td><td>execute only</td></tr><tr><td><code>0</code></td><td>no permission</td></tr></tbody></table> <p>For example, the octal value <code>0o765</code> means:</p> <ul> <li>The owner may read, write and execute the file.</li> <li>The group may read and write the file.</li> <li>Others may read and execute the file.</li> </ul> <p>When using raw numbers where file modes are expected, any value larger than <code>0o777</code> may result in platform-specific behaviors that are not supported to work consistently. Therefore constants like <code>S_ISVTX</code>, <code>S_ISGID</code> or <code>S_ISUID</code> are not exposed in <code>fs.constants</code>.</p> <p>Caveats: on Windows only the write permission can be changed, and the distinction among the permissions of group, owner or others is not implemented.</p> <h2>fs.chmodSync(path, mode)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1020">[src]</a><span><a class="mark" href="#fs_fs_chmodsync_path_mode" id="fs_fs_chmodsync_path_mode">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.6.7</td> <td><p><span>Added in: v0.6.7</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_chmod_path_mode_callback"><code>fs.chmod()</code></a>.</p> <p>See also: <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a>.</p> <h2>fs.chown(path, uid, gid, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1071">[src]</a><span><a class="mark" href="#fs_fs_chown_path_uid_gid_callback" id="fs_fs_chown_path_uid_gid_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.1.97</td> <td><p><span>Added in: v0.1.97</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronously changes owner and group of a file. No arguments other than a possible exception are given to the completion callback.</p> <p>See also: <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a>.</p> <h2>fs.chownSync(path, uid, gid)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1083">[src]</a><span><a class="mark" href="#fs_fs_chownsync_path_uid_gid" id="fs_fs_chownsync_path_uid_gid">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.97</td> <td><p><span>Added in: v0.1.97</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Synchronously changes owner and group of a file. Returns <code>undefined</code>. This is the synchronous version of <a href="#fs_fs_chown_path_uid_gid_callback"><code>fs.chown()</code></a>.</p> <p>See also: <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a>.</p> <h2>fs.close(fd, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L391">[src]</a><span><a class="mark" href="#fs_fs_close_fd_callback" id="fs_fs_close_fd_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.0.2</td> <td><p><span>Added in: v0.0.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/close.2.html"><code>close(2)</code></a>. No arguments other than a possible exception are given to the completion callback.</p> <h2>fs.closeSync(fd)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L398">[src]</a><span><a class="mark" href="#fs_fs_closesync_fd" id="fs_fs_closesync_fd">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.21</span> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/close.2.html"><code>close(2)</code></a>. Returns <code>undefined</code>.</p> <h2>fs.constants<span><a class="mark" href="#fs_fs_constants" id="fs_fs_constants">#</a></span></h2> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns an object containing commonly used constants for file system operations. The specific constants currently defined are described in <a href="#fs_fs_constants_1">FS Constants</a>.</p> <h2>fs.copyFile(src, dest[, flags], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1694">[src]</a><span><a class="mark" href="#fs_fs_copyfile_src_dest_flags_callback" id="fs_fs_copyfile_src_dest_flags_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> source filename to copy</li> <li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> destination filename of the copy operation</li> <li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Asynchronously copies <code>src</code> to <code>dest</code>. By default, <code>dest</code> is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.</p> <p><code>flags</code> is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. <code>fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE</code>).</p> <ul> <li><code>fs.constants.COPYFILE_EXCL</code> - The copy operation will fail if <code>dest</code> already exists.</li> <li><code>fs.constants.COPYFILE_FICLONE</code> - The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.</li> <li><code>fs.constants.COPYFILE_FICLONE_FORCE</code> - The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.</li> </ul> <pre><code class="language-js">const fs = require('fs'); // destination.txt will be created or overwritten by default. fs.copyFile('source.txt', 'destination.txt', (err) => { if (err) throw err; console.log('source.txt was copied to destination.txt'); }); </code></pre> <p>If the third argument is a number, then it specifies <code>flags</code>:</p> <pre><code class="language-js">const fs = require('fs'); const { COPYFILE_EXCL } = fs.constants; // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. fs.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL, callback); </code></pre> <h2>fs.copyFileSync(src, dest[, flags])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1716">[src]</a><span><a class="mark" href="#fs_fs_copyfilesync_src_dest_flags" id="fs_fs_copyfilesync_src_dest_flags">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> source filename to copy</li> <li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> destination filename of the copy operation</li> <li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.</li> </ul> <p>Synchronously copies <code>src</code> to <code>dest</code>. By default, <code>dest</code> is overwritten if it already exists. Returns <code>undefined</code>. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.</p> <p><code>flags</code> is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. <code>fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE</code>).</p> <ul> <li><code>fs.constants.COPYFILE_EXCL</code> - The copy operation will fail if <code>dest</code> already exists.</li> <li><code>fs.constants.COPYFILE_FICLONE</code> - The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.</li> <li><code>fs.constants.COPYFILE_FICLONE_FORCE</code> - The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.</li> </ul> <pre><code class="language-js">const fs = require('fs'); // destination.txt will be created or overwritten by default. fs.copyFileSync('source.txt', 'destination.txt'); console.log('source.txt was copied to destination.txt'); </code></pre> <p>If the third argument is a number, then it specifies <code>flags</code>:</p> <pre><code class="language-js">const fs = require('fs'); const { COPYFILE_EXCL } = fs.constants; // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. fs.copyFileSync('source.txt', 'destination.txt', COPYFILE_EXCL); </code></pre> <h2>fs.createReadStream(path[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1731">[src]</a><span><a class="mark" href="#fs_fs_createreadstream_path_options" id="fs_fs_createreadstream_path_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The passed <code>options</code> object will never be modified.</p></td></tr> <tr><td>v2.3.0</td> <td><p>The passed <code>options</code> object can be a string now.</p></td></tr> <tr><td>v0.1.31</td> <td><p><span>Added in: v0.1.31</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>null</code></li> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>null</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li> <li><code>autoClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code></li> <li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>Infinity</code></li> <li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>64 * 1024</code></li> </ul> </li> <li>Returns: <a href="#fs_class_fs_readstream" class="type"><fs.ReadStream></a> See <a href="#stream_class_stream_readable">Readable Streams</a>.</li> </ul> <p>Unlike the 16 kb default <code>highWaterMark</code> for a readable stream, the stream returned by this method has a default <code>highWaterMark</code> of 64 kb.</p> <p><code>options</code> can include <code>start</code> and <code>end</code> values to read a range of bytes from the file instead of the entire file. Both <code>start</code> and <code>end</code> are inclusive and start counting at 0. If <code>fd</code> is specified and <code>start</code> is omitted or <code>undefined</code>, <code>fs.createReadStream()</code> reads sequentially from the current file position. The <code>encoding</code> can be any one of those accepted by <a href="#buffer_buffer"><code>Buffer</code></a>.</p> <p>If <code>fd</code> is specified, <code>ReadStream</code> will ignore the <code>path</code> argument and will use the specified file descriptor. This means that no <code>'open'</code> event will be emitted. <code>fd</code> should be blocking; non-blocking <code>fd</code>s should be passed to <a href="#net_class_net_socket"><code>net.Socket</code></a>.</p> <p>If <code>fd</code> points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally.</p> <pre><code class="language-js">const fs = require('fs'); // Create a stream from some character device. const stream = fs.createReadStream('/dev/input/event0'); setTimeout(() => { stream.close(); // This may not close the stream. // Artificially marking end-of-stream, as if the underlying resource had // indicated end-of-file by itself, allows the stream to close. // This does not cancel pending read operations, and if there is such an // operation, the process may still not be able to exit successfully // until it finishes. stream.push(null); stream.read(0); }, 100); </code></pre> <p>If <code>autoClose</code> is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If <code>autoClose</code> is set to true (default behavior), on <code>'error'</code> or <code>'end'</code> the file descriptor will be closed automatically.</p> <p><code>mode</code> sets the file mode (permission and sticky bits), but only if the file was created.</p> <p>An example to read the last 10 bytes of a file which is 100 bytes long:</p> <pre><code class="language-js">fs.createReadStream('sample.txt', { start: 90, end: 99 }); </code></pre> <p>If <code>options</code> is a string, then it specifies the encoding.</p> <h2>fs.createWriteStream(path[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1735">[src]</a><span><a class="mark" href="#fs_fs_createwritestream_path_options" id="fs_fs_createwritestream_path_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The passed <code>options</code> object will never be modified.</p></td></tr> <tr><td>v5.5.0</td> <td><p>The <code>autoClose</code> option is supported now.</p></td></tr> <tr><td>v2.3.0</td> <td><p>The passed <code>options</code> object can be a string now.</p></td></tr> <tr><td>v0.1.31</td> <td><p><span>Added in: v0.1.31</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>null</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li> <li><code>autoClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code></li> <li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> </li> <li>Returns: <a href="#fs_class_fs_writestream" class="type"><fs.WriteStream></a> See <a href="#stream_class_stream_writable">Writable Stream</a>.</li> </ul> <p><code>options</code> may also include a <code>start</code> option to allow writing data at some position past the beginning of the file. Modifying a file rather than replacing it may require a <code>flags</code> mode of <code>r+</code> rather than the default mode <code>w</code>. The <code>encoding</code> can be any one of those accepted by <a href="#buffer_buffer"><code>Buffer</code></a>.</p> <p>If <code>autoClose</code> is set to true (default behavior) on <code>'error'</code> or <code>'finish'</code> the file descriptor will be closed automatically. If <code>autoClose</code> is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.</p> <p>Like <a href="#fs_class_fs_readstream"><code>ReadStream</code></a>, if <code>fd</code> is specified, <a href="#fs_class_fs_writestream"><code>WriteStream</code></a> will ignore the <code>path</code> argument and will use the specified file descriptor. This means that no <code>'open'</code> event will be emitted. <code>fd</code> should be blocking; non-blocking <code>fd</code>s should be passed to <a href="#net_class_net_socket"><code>net.Socket</code></a>.</p> <p>If <code>options</code> is a string, then it specifies the encoding.</p> <h2>fs.exists(path, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L195">[src]</a><span><a class="mark" href="#fs_fs_exists_path_callback" id="fs_fs_exists_path_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v1.0.0</td> <td><p><span>Deprecated since: v1.0.0</span></p></td></tr> <tr><td>v0.0.2</td> <td><p><span>Added in: v0.0.2</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#fs_fs_stat_path_options_callback"><code>fs.stat()</code></a> or <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a> instead.</div><p></p> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>exists</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> </li> </ul> <p>Test whether or not the given path exists by checking with the file system. Then call the <code>callback</code> argument with either true or false:</p> <pre><code class="language-js">fs.exists('/etc/passwd', (exists) => { console.log(exists ? 'it\'s there' : 'no passwd!'); }); </code></pre> <p><strong>The parameters for this callback are not consistent with other Node.js callbacks.</strong> Normally, the first parameter to a Node.js callback is an <code>err</code> parameter, optionally followed by other parameters. The <code>fs.exists()</code> callback has only one boolean parameter. This is one reason <code>fs.access()</code> is recommended instead of <code>fs.exists()</code>.</p> <p>Using <code>fs.exists()</code> to check for the existence of a file before calling <code>fs.open()</code>, <code>fs.readFile()</code> or <code>fs.writeFile()</code> is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file does not exist.</p> <p><strong>write (NOT RECOMMENDED)</strong></p> <pre><code class="language-js">fs.exists('myfile', (exists) => { if (exists) { console.error('myfile already exists'); } else { fs.open('myfile', 'wx', (err, fd) => { if (err) throw err; writeMyData(fd); }); } }); </code></pre> <p><strong>write (RECOMMENDED)</strong></p> <pre><code class="language-js">fs.open('myfile', 'wx', (err, fd) => { if (err) { if (err.code === 'EEXIST') { console.error('myfile already exists'); return; } throw err; } writeMyData(fd); }); </code></pre> <p><strong>read (NOT RECOMMENDED)</strong></p> <pre><code class="language-js">fs.exists('myfile', (exists) => { if (exists) { fs.open('myfile', 'r', (err, fd) => { if (err) throw err; readMyData(fd); }); } else { console.error('myfile does not exist'); } }); </code></pre> <p><strong>read (RECOMMENDED)</strong></p> <pre><code class="language-js">fs.open('myfile', 'r', (err, fd) => { if (err) { if (err.code === 'ENOENT') { console.error('myfile does not exist'); return; } throw err; } readMyData(fd); }); </code></pre> <p>The "not recommended" examples above check for existence and then use the file; the "recommended" examples are better because they use the file directly and handle the error, if any.</p> <p>In general, check for the existence of a file only if the file won’t be used directly, for example when its existence is a signal from another process.</p> <h2>fs.existsSync(path)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L221">[src]</a><span><a class="mark" href="#fs_fs_existssync_path" id="fs_fs_existssync_path">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the path exists, <code>false</code> otherwise.</p> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_exists_path_callback"><code>fs.exists()</code></a>.</p> <p><code>fs.exists()</code> is deprecated, but <code>fs.existsSync()</code> is not. The <code>callback</code> parameter to <code>fs.exists()</code> accepts parameters that are inconsistent with other Node.js callbacks. <code>fs.existsSync()</code> does not use a callback.</p> <h2>fs.fchmod(fd, mode, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L959">[src]</a><span><a class="mark" href="#fs_fs_fchmod_fd_mode_callback" id="fs_fs_fchmod_fd_mode_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.4.7</td> <td><p><span>Added in: v0.4.7</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fchmod.2.html"><code>fchmod(2)</code></a>. No arguments other than a possible exception are given to the completion callback.</p> <h2>fs.fchmodSync(fd, mode)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L969">[src]</a><span><a class="mark" href="#fs_fs_fchmodsync_fd_mode" id="fs_fs_fchmodsync_fd_mode">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.4.7</span> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fchmod.2.html"><code>fchmod(2)</code></a>. Returns <code>undefined</code>.</p> <h2>fs.fchown(fd, uid, gid, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1051">[src]</a><span><a class="mark" href="#fs_fs_fchown_fd_uid_gid_callback" id="fs_fs_fchown_fd_uid_gid_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.4.7</td> <td><p><span>Added in: v0.4.7</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fchown.2.html"><code>fchown(2)</code></a>. No arguments other than a possible exception are given to the completion callback.</p> <h2>fs.fchownSync(fd, uid, gid)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1061">[src]</a><span><a class="mark" href="#fs_fs_fchownsync_fd_uid_gid" id="fs_fs_fchownsync_fd_uid_gid">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.4.7</span> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fchown.2.html"><code>fchown(2)</code></a>. Returns <code>undefined</code>.</p> <h2>fs.fdatasync(fd, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L687">[src]</a><span><a class="mark" href="#fs_fs_fdatasync_fd_callback" id="fs_fs_fdatasync_fd_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.1.96</td> <td><p><span>Added in: v0.1.96</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a>. No arguments other than a possible exception are given to the completion callback.</p> <h2>fs.fdatasyncSync(fd)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L694">[src]</a><span><a class="mark" href="#fs_fs_fdatasyncsync_fd" id="fs_fs_fdatasyncsync_fd">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.96</span> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a>. Returns <code>undefined</code>.</p> <h2>fs.fstat(fd[, options], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L794">[src]</a><span><a class="mark" href="#fs_fs_fstat_fd_options_callback" id="fs_fs_fstat_fd_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.5.0</td> <td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.1.95</td> <td><p><span>Added in: v0.1.95</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>stats</code> <a href="#fs_class_fs_stats" class="type"><fs.Stats></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fstat.2.html"><code>fstat(2)</code></a>. The callback gets two arguments <code>(err, stats)</code> where <code>stats</code> is an <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object. <code>fstat()</code> is identical to <a href="#fs_fs_stat_path_options_callback"><code>stat()</code></a>, except that the file to be stat-ed is specified by the file descriptor <code>fd</code>.</p> <h2>fs.fstatSync(fd[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L831">[src]</a><span><a class="mark" href="#fs_fs_fstatsync_fd_options" id="fs_fs_fstatsync_fd_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.5.0</td> <td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr> <tr><td>v0.1.95</td> <td><p><span>Added in: v0.1.95</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="#fs_class_fs_stats" class="type"><fs.Stats></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fstat.2.html"><code>fstat(2)</code></a>.</p> <h2>fs.fsync(fd, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L701">[src]</a><span><a class="mark" href="#fs_fs_fsync_fd_callback" id="fs_fs_fsync_fd_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.1.96</td> <td><p><span>Added in: v0.1.96</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a>. No arguments other than a possible exception are given to the completion callback.</p> <h2>fs.fsyncSync(fd)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L708">[src]</a><span><a class="mark" href="#fs_fs_fsyncsync_fd" id="fs_fs_fsyncsync_fd">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.96</span> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a>. Returns <code>undefined</code>.</p> <h2>fs.ftruncate(fd[, len], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L648">[src]</a><span><a class="mark" href="#fs_fs_ftruncate_fd_len_callback" id="fs_fs_ftruncate_fd_len_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.8.6</td> <td><p><span>Added in: v0.8.6</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/ftruncate.2.html"><code>ftruncate(2)</code></a>. No arguments other than a possible exception are given to the completion callback.</p> <p>If the file referred to by the file descriptor was larger than <code>len</code> bytes, only the first <code>len</code> bytes will be retained in the file.</p> <p>For example, the following program retains only the first four bytes of the file:</p> <pre><code class="language-js">console.log(fs.readFileSync('temp.txt', 'utf8')); // Prints: Node.js // get the file descriptor of the file to be truncated const fd = fs.openSync('temp.txt', 'r+'); // truncate the file to first four bytes fs.ftruncate(fd, 4, (err) => { assert.ifError(err); console.log(fs.readFileSync('temp.txt', 'utf8')); }); // Prints: Node </code></pre> <p>If the file previously was shorter than <code>len</code> bytes, it is extended, and the extended part is filled with null bytes (<code>'\0'</code>):</p> <pre><code class="language-js">console.log(fs.readFileSync('temp.txt', 'utf8')); // Prints: Node.js // get the file descriptor of the file to be truncated const fd = fs.openSync('temp.txt', 'r+'); // truncate the file to 10 bytes, whereas the actual size is 7 bytes fs.ftruncate(fd, 10, (err) => { assert.ifError(err); console.log(fs.readFileSync('temp.txt')); }); // Prints: <Buffer 4e 6f 64 65 2e 6a 73 00 00 00> // ('Node.js\0\0\0' in UTF8) </code></pre> <p>The last three bytes are null bytes (<code>'\0'</code>), to compensate the over-truncation.</p> <h2>fs.ftruncateSync(fd[, len])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L661">[src]</a><span><a class="mark" href="#fs_fs_ftruncatesync_fd_len" id="fs_fs_ftruncatesync_fd_len">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.8.6</span> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li> </ul> <p>Returns <code>undefined</code>.</p> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_ftruncate_fd_len_callback"><code>fs.ftruncate()</code></a>.</p> <h2>fs.futimes(fd, atime, mtime, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1116">[src]</a><span><a class="mark" href="#fs_fs_futimes_fd_atime_mtime_callback" id="fs_fs_futimes_fd_atime_mtime_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v4.1.0</td> <td><p>Numeric strings, <code>NaN</code> and <code>Infinity</code> are now allowed time specifiers.</p></td></tr> <tr><td>v0.4.2</td> <td><p><span>Added in: v0.4.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> <li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Change the file system timestamps of the object referenced by the supplied file descriptor. See <a href="#fs_fs_utimes_path_atime_mtime_callback"><code>fs.utimes()</code></a>.</p> <p>This function does not work on AIX versions before 7.1, it will return the error <code>UV_ENOSYS</code>.</p> <h2>fs.futimesSync(fd, atime, mtime)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1125">[src]</a><span><a class="mark" href="#fs_fs_futimessync_fd_atime_mtime" id="fs_fs_futimessync_fd_atime_mtime">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.1.0</td> <td><p>Numeric strings, <code>NaN</code> and <code>Infinity</code> are now allowed time specifiers.</p></td></tr> <tr><td>v0.4.2</td> <td><p><span>Added in: v0.4.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Synchronous version of <a href="#fs_fs_futimes_fd_atime_mtime_callback"><code>fs.futimes()</code></a>. Returns <code>undefined</code>.</p> <h2>fs.lchmod(path, mode, callback)<span><a class="mark" href="#fs_fs_lchmod_path_mode_callback" id="fs_fs_lchmod_path_mode_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.4.7</td> <td><p><span>Deprecated since: v0.4.7</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2"><code>lchmod(2)</code></a>. No arguments other than a possible exception are given to the completion callback.</p> <p>Only available on macOS.</p> <h2>fs.lchmodSync(path, mode)<span><a class="mark" href="#fs_fs_lchmodsync_path_mode" id="fs_fs_lchmodsync_path_mode">#</a></span></h2> <div class="api_metadata"> <span>Deprecated since: v0.4.7</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Synchronous <a href="https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2"><code>lchmod(2)</code></a>. Returns <code>undefined</code>.</p> <h2>fs.lchown(path, uid, gid, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1030">[src]</a><span><a class="mark" href="#fs_fs_lchown_path_uid_gid_callback" id="fs_fs_lchown_path_uid_gid_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.6.0</td> <td><p>This API is no longer deprecated.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/lchown.2.html"><code>lchown(2)</code></a>. No arguments other than a possible exception are given to the completion callback.</p> <h2>fs.lchownSync(path, uid, gid)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1041">[src]</a><span><a class="mark" href="#fs_fs_lchownsync_path_uid_gid" id="fs_fs_lchownsync_path_uid_gid">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.6.0</td> <td><p>This API is no longer deprecated.</p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/lchown.2.html"><code>lchown(2)</code></a>. Returns <code>undefined</code>.</p> <h2>fs.link(existingPath, newPath, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L912">[src]</a><span><a class="mark" href="#fs_fs_link_existingpath_newpath_callback" id="fs_fs_link_existingpath_newpath_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>existingPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.1.31</td> <td><p><span>Added in: v0.1.31</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>existingPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a>. No arguments other than a possible exception are given to the completion callback.</p> <h2>fs.linkSync(existingPath, newPath)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L928">[src]</a><span><a class="mark" href="#fs_fs_linksync_existingpath_newpath" id="fs_fs_linksync_existingpath_newpath">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>existingPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.31</td> <td><p><span>Added in: v0.1.31</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>existingPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a>. Returns <code>undefined</code>.</p> <h2>fs.lstat(path[, options], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L805">[src]</a><span><a class="mark" href="#fs_fs_lstat_path_options_callback" id="fs_fs_lstat_path_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.5.0</td> <td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.1.30</td> <td><p><span>Added in: v0.1.30</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>stats</code> <a href="#fs_class_fs_stats" class="type"><fs.Stats></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a>. The callback gets two arguments <code>(err, stats)</code> where <code>stats</code> is a <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object. <code>lstat()</code> is identical to <code>stat()</code>, except that if <code>path</code> is a symbolic link, then the link itself is stat-ed, not the file that it refers to.</p> <h2>fs.lstatSync(path[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L839">[src]</a><span><a class="mark" href="#fs_fs_lstatsync_path_options" id="fs_fs_lstatsync_path_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.5.0</td> <td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.30</td> <td><p><span>Added in: v0.1.30</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="#fs_class_fs_stats" class="type"><fs.Stats></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a>.</p> <h2>fs.mkdir(path[, options], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L715">[src]</a><span><a class="mark" href="#fs_fs_mkdir_path_options_callback" id="fs_fs_mkdir_path_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.12.0</td> <td><p>The second argument can now be an <code>options</code> object with <code>recursive</code> and <code>mode</code> properties.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.1.8</td> <td><p><span>Added in: v0.1.8</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></p> <ul> <li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Not supported on Windows. <strong>Default:</strong> <code>0o777</code>.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronously creates a directory. No arguments other than a possible exception are given to the completion callback.</p> <p>The optional <code>options</code> argument can be an integer specifying mode (permission and sticky bits), or an object with a <code>mode</code> property and a <code>recursive</code> property indicating whether parent folders should be created.</p> <pre><code class="language-js">// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist. fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => { if (err) throw err; }); </code></pre> <p>On Windows, using <code>fs.mkdir()</code> on the root directory even with recursion will result in an error:</p> <pre><code class="language-js">fs.mkdir('/', { recursive: true }, (err) => { // => [Error: EPERM: operation not permitted, mkdir 'C:\'] }); </code></pre> <p>See also: <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html"><code>mkdir(2)</code></a>.</p> <h2>fs.mkdirSync(path[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L739">[src]</a><span><a class="mark" href="#fs_fs_mkdirsync_path_options" id="fs_fs_mkdirsync_path_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.12.0</td> <td><p>The second argument can now be an <code>options</code> object with <code>recursive</code> and <code>mode</code> properties.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></p> <ul> <li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Not supported on Windows. <strong>Default:</strong> <code>0o777</code>.</li> </ul> </li> </ul> <p>Synchronously creates a directory. Returns <code>undefined</code>. This is the synchronous version of <a href="#fs_fs_mkdir_path_options_callback"><code>fs.mkdir()</code></a>.</p> <p>See also: <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html"><code>mkdir(2)</code></a>.</p> <h2>fs.mkdtemp(prefix[, options], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1666">[src]</a><span><a class="mark" href="#fs_fs_mkdtemp_prefix_options_callback" id="fs_fs_mkdtemp_prefix_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v6.2.1</td> <td><p>The <code>callback</code> parameter is optional now.</p></td></tr> <tr><td>v5.10.0</td> <td><p><span>Added in: v5.10.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>prefix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>folder</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> </li> </ul> <p>Creates a unique temporary directory.</p> <p>Generates six random characters to be appended behind a required <code>prefix</code> to create a unique temporary directory.</p> <p>The created folder path is passed as a string to the callback's second parameter.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use.</p> <pre><code class="language-js">fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, folder) => { if (err) throw err; console.log(folder); // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 }); </code></pre> <p>The <code>fs.mkdtemp()</code> method will append the six randomly selected characters directly to the <code>prefix</code> string. For instance, given a directory <code>/tmp</code>, if the intention is to create a temporary directory <em>within</em> <code>/tmp</code>, the <code>prefix</code> must end with a trailing platform-specific path separator (<code>require('path').sep</code>).</p> <pre><code class="language-js">// The parent directory for the new temporary directory const tmpDir = os.tmpdir(); // This method is *INCORRECT*: fs.mkdtemp(tmpDir, (err, folder) => { if (err) throw err; console.log(folder); // Will print something similar to `/tmpabc123`. // A new temporary directory is created at the file system root // rather than *within* the /tmp directory. }); // This method is *CORRECT*: const { sep } = require('path'); fs.mkdtemp(`${tmpDir}${sep}`, (err, folder) => { if (err) throw err; console.log(folder); // Will print something similar to `/tmp/abc123`. // A new temporary directory is created within // the /tmp directory. }); </code></pre> <h2>fs.mkdtempSync(prefix[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1679">[src]</a><span><a class="mark" href="#fs_fs_mkdtempsync_prefix_options" id="fs_fs_mkdtempsync_prefix_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v5.10.0</span> </div> <ul> <li><code>prefix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the created folder path.</p> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_mkdtemp_prefix_options_callback"><code>fs.mkdtemp()</code></a>.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use.</p> <h2>fs.open(path[, flags[, mode]], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L406">[src]</a><span><a class="mark" href="#fs_fs_open_path_flags_mode_callback" id="fs_fs_open_path_flags_mode_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v11.1.0</td> <td><p>The <code>flags</code> argument is now optional and defaults to <code>'r'</code>.</p></td></tr> <tr><td>v9.9.0</td> <td><p>The <code>as</code> and <code>as+</code> modes are supported now.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.0.2</td> <td><p><span>Added in: v0.0.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code> (readable and writable)</li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> </li> </ul> <p>Asynchronous file open. See <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a>.</p> <p><code>mode</code> sets the file mode (permission and sticky bits), but only if the file was created. On Windows, only the write permission can be manipulated; see <a href="#fs_fs_chmod_path_mode_callback"><code>fs.chmod()</code></a>.</p> <p>The callback gets two arguments <code>(err, fd)</code>.</p> <p>Some characters (<code>< > : " / \ | ? *</code>) are reserved under Windows as documented by <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file">Naming Files, Paths, and Namespaces</a>. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams">this MSDN page</a>.</p> <p>Functions based on <code>fs.open()</code> exhibit this behavior as well: <code>fs.writeFile()</code>, <code>fs.readFile()</code>, etc.</p> <h2>fs.openSync(path[, flags, mode])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L433">[src]</a><span><a class="mark" href="#fs_fs_opensync_path_flags_mode" id="fs_fs_opensync_path_flags_mode">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v11.1.0</td> <td><p>The <code>flags</code> argument is now optional and defaults to <code>'r'</code>.</p></td></tr> <tr><td>v9.9.0</td> <td><p>The <code>as</code> and <code>as+</code> modes are supported now.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>'r'</code>. See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>.</li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Returns an integer representing the file descriptor.</p> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_open_path_flags_mode_callback"><code>fs.open()</code></a>.</p> <h2>fs.read(fd, buffer, offset, length, position, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L447">[src]</a><span><a class="mark" href="#fs_fs_read_fd_buffer_offset_length_position_callback" id="fs_fs_read_fd_buffer_offset_length_position_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code>, or a <code>DataView</code>.</p></td></tr> <tr><td>v7.4.0</td> <td><p>The <code>buffer</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The <code>length</code> parameter can now be <code>0</code>.</p></td></tr> <tr><td>v0.0.2</td> <td><p><span>Added in: v0.0.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> </ul> <p>Read data from the file specified by <code>fd</code>.</p> <p><code>buffer</code> is the buffer that the data will be written to.</p> <p><code>offset</code> is the offset in the buffer to start writing at.</p> <p><code>length</code> is an integer specifying the number of bytes to read.</p> <p><code>position</code> is an argument specifying where to begin reading from in the file. If <code>position</code> is <code>null</code>, data will be read from the current file position, and the file position will be updated. If <code>position</code> is an integer, the file position will remain unchanged.</p> <p>The callback is given the three arguments, <code>(err, bytesRead, buffer)</code>.</p> <p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns a <code>Promise</code> for an <code>Object</code> with <code>bytesRead</code> and <code>buffer</code> properties.</p> <h2>fs.readdir(path[, options], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L760">[src]</a><span><a class="mark" href="#fs_fs_readdir_path_options_callback" id="fs_fs_readdir_path_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>New option <code>withFileTypes</code> was added.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The <code>options</code> parameter was added.</p></td></tr> <tr><td>v0.1.8</td> <td><p><span>Added in: v0.1.8</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>withFileTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>files</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#buffer_class_buffer" class="type"><Buffer[]></a> | <a href="#fs_class_fs_dirent" class="type"><fs.Dirent[]></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a>. Reads the contents of a directory. The callback gets two arguments <code>(err, files)</code> where <code>files</code> is an array of the names of the files in the directory excluding <code>'.'</code> and <code>'..'</code>.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use for the filenames passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>, the filenames returned will be passed as <code>Buffer</code> objects.</p> <p>If <code>options.withFileTypes</code> is set to <code>true</code>, the <code>files</code> array will contain <a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a> objects.</p> <h2>fs.readdirSync(path[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L782">[src]</a><span><a class="mark" href="#fs_fs_readdirsync_path_options" id="fs_fs_readdirsync_path_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>New option <code>withFileTypes</code> was added.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>withFileTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#buffer_class_buffer" class="type"><Buffer[]></a> | <a href="#fs_class_fs_dirent" class="type"><fs.Dirent[]></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a>.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use for the filenames returned. If the <code>encoding</code> is set to <code>'buffer'</code>, the filenames returned will be passed as <code>Buffer</code> objects.</p> <p>If <code>options.withFileTypes</code> is set to <code>true</code>, the result will contain <a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a> objects.</p> <h2>fs.readFile(path[, options], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L276">[src]</a><span><a class="mark" href="#fs_fs_readfile_path_options_callback" id="fs_fs_readfile_path_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v5.1.0</td> <td><p>The <code>callback</code> will always be called with <code>null</code> as the <code>error</code> parameter in case of success.</p></td></tr> <tr><td>v5.0.0</td> <td><p>The <code>path</code> parameter can be a file descriptor now.</p></td></tr> <tr><td>v0.1.29</td> <td><p><span>Added in: v0.1.29</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> filename or file descriptor</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> </ul> <p>Asynchronously reads the entire contents of a file.</p> <pre><code class="language-js">fs.readFile('/etc/passwd', (err, data) => { if (err) throw err; console.log(data); }); </code></pre> <p>The callback is passed two arguments <code>(err, data)</code>, where <code>data</code> is the contents of the file.</p> <p>If no encoding is specified, then the raw buffer is returned.</p> <p>If <code>options</code> is a string, then it specifies the encoding:</p> <pre><code class="language-js">fs.readFile('/etc/passwd', 'utf8', callback); </code></pre> <p>When the path is a directory, the behavior of <code>fs.readFile()</code> and <a href="#fs_fs_readfilesync_path_options"><code>fs.readFileSync()</code></a> is platform-specific. On macOS, Linux, and Windows, an error will be returned. On FreeBSD, a representation of the directory's contents will be returned.</p> <pre><code class="language-js">// macOS, Linux, and Windows fs.readFile('<directory>', (err, data) => { // => [Error: EISDIR: illegal operation on a directory, read <directory>] }); // FreeBSD fs.readFile('<directory>', (err, data) => { // => null, <data> }); </code></pre> <p>The <code>fs.readFile()</code> function buffers the entire file. To minimize memory costs, when possible prefer streaming via <code>fs.createReadStream()</code>.</p> <h3>File Descriptors<span><a class="mark" href="#fs_file_descriptors_1" id="fs_file_descriptors_1">#</a></span></h3> <ol> <li>Any specified file descriptor has to support reading.</li> <li>If a file descriptor is specified as the <code>path</code>, it will not be closed automatically.</li> <li>The reading will begin at the current position. For example, if the file already had <code>'Hello World</code>' and six bytes are read with the file descriptor, the call to <code>fs.readFile()</code> with the same file descriptor, would give <code>'World'</code>, rather than <code>'Hello World'</code>.</li> </ol> <h2>fs.readFileSync(path[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L340">[src]</a><span><a class="mark" href="#fs_fs_readfilesync_path_options" id="fs_fs_readfilesync_path_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v5.0.0</td> <td><p>The <code>path</code> parameter can be a file descriptor now.</p></td></tr> <tr><td>v0.1.8</td> <td><p><span>Added in: v0.1.8</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> filename or file descriptor</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Returns the contents of the <code>path</code>.</p> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_readfile_path_options_callback"><code>fs.readFile()</code></a>.</p> <p>If the <code>encoding</code> option is specified then this function returns a string. Otherwise it returns a buffer.</p> <p>Similar to <a href="#fs_fs_readfile_path_options_callback"><code>fs.readFile()</code></a>, when the path is a directory, the behavior of <code>fs.readFileSync()</code> is platform-specific.</p> <pre><code class="language-js">// macOS, Linux, and Windows fs.readFileSync('<directory>'); // => [Error: EISDIR: illegal operation on a directory, read <directory>] // FreeBSD fs.readFileSync('<directory>'); // => <data> </code></pre> <h2>fs.readlink(path[, options], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L859">[src]</a><span><a class="mark" href="#fs_fs_readlink_path_options_callback" id="fs_fs_readlink_path_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.1.31</td> <td><p><span>Added in: v0.1.31</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>linkString</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a>. The callback gets two arguments <code>(err, linkString)</code>.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use for the link path passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>, the link path returned will be passed as a <code>Buffer</code> object.</p> <h2>fs.readlinkSync(path[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L869">[src]</a><span><a class="mark" href="#fs_fs_readlinksync_path_options" id="fs_fs_readlinksync_path_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.31</td> <td><p><span>Added in: v0.1.31</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a>. Returns the symbolic link's string value.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use for the link path returned. If the <code>encoding</code> is set to <code>'buffer'</code>, the link path returned will be passed as a <code>Buffer</code> object.</p> <h2>fs.readSync(fd, buffer, offset, length, position)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L479">[src]</a><span><a class="mark" href="#fs_fs_readsync_fd_buffer_offset_length_position" id="fs_fs_readsync_fd_buffer_offset_length_position">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The <code>length</code> parameter can now be <code>0</code>.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Returns the number of <code>bytesRead</code>.</p> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_read_fd_buffer_offset_length_position_callback"><code>fs.read()</code></a>.</p> <h2>fs.realpath(path[, options], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1526">[src]</a><span><a class="mark" href="#fs_fs_realpath_path_options_callback" id="fs_fs_realpath_path_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v8.0.0</td> <td><p>Pipe/Socket resolve support was added.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v6.4.0</td> <td><p>Calling <code>realpath</code> now works again for various edge cases on Windows.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The <code>cache</code> parameter was removed.</p></td></tr> <tr><td>v0.1.31</td> <td><p><span>Added in: v0.1.31</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>resolvedPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> </ul> <p>Asynchronously computes the canonical pathname by resolving <code>.</code>, <code>..</code> and symbolic links.</p> <p>A canonical pathname is not necessarily unique. Hard links and bind mounts can expose a file system entity through many pathnames.</p> <p>This function behaves like <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a>, with some exceptions:</p> <ol> <li> <p>No case conversion is performed on case-insensitive file systems.</p> </li> <li> <p>The maximum number of symbolic links is platform-independent and generally (much) higher than what the native <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a> implementation supports.</p> </li> </ol> <p>The <code>callback</code> gets two arguments <code>(err, resolvedPath)</code>. May use <code>process.cwd</code> to resolve relative paths.</p> <p>Only paths that can be converted to UTF8 strings are supported.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use for the path passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>, the path returned will be passed as a <code>Buffer</code> object.</p> <p>If <code>path</code> resolves to a socket or a pipe, the function will return a system dependent name for that object.</p> <h2>fs.realpath.native(path[, options], callback)<span><a class="mark" href="#fs_fs_realpath_native_path_options_callback" id="fs_fs_realpath_native_path_options_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v9.2.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>resolvedPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a>.</p> <p>The <code>callback</code> gets two arguments <code>(err, resolvedPath)</code>.</p> <p>Only paths that can be converted to UTF8 strings are supported.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use for the path passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>, the path returned will be passed as a <code>Buffer</code> object.</p> <p>On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on <code>/proc</code> in order for this function to work. Glibc does not have this restriction.</p> <h2>fs.realpathSync(path[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1380">[src]</a><span><a class="mark" href="#fs_fs_realpathsync_path_options" id="fs_fs_realpathsync_path_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Pipe/Socket resolve support was added.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v6.4.0</td> <td><p>Calling <code>realpathSync</code> now works again for various edge cases on Windows.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The <code>cache</code> parameter was removed.</p></td></tr> <tr><td>v0.1.31</td> <td><p><span>Added in: v0.1.31</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Returns the resolved pathname.</p> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_realpath_path_options_callback"><code>fs.realpath()</code></a>.</p> <h2>fs.realpathSync.native(path[, options])<span><a class="mark" href="#fs_fs_realpathsync_native_path_options" id="fs_fs_realpathsync_native_path_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v9.2.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a>.</p> <p>Only paths that can be converted to UTF8 strings are supported.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use for the path returned. If the <code>encoding</code> is set to <code>'buffer'</code>, the path returned will be passed as a <code>Buffer</code> object.</p> <p>On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on <code>/proc</code> in order for this function to work. Glibc does not have this restriction.</p> <h2>fs.rename(oldPath, newPath, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L577">[src]</a><span><a class="mark" href="#fs_fs_rename_oldpath_newpath_callback" id="fs_fs_rename_oldpath_newpath_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>oldPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.0.2</td> <td><p><span>Added in: v0.0.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>oldPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronously rename file at <code>oldPath</code> to the pathname provided as <code>newPath</code>. In the case that <code>newPath</code> already exists, it will be overwritten. No arguments other than a possible exception are given to the completion callback.</p> <p>See also: <a href="http://man7.org/linux/man-pages/man2/rename.2.html"><code>rename(2)</code></a>.</p> <pre><code class="language-js">fs.rename('oldFile.txt', 'newFile.txt', (err) => { if (err) throw err; console.log('Rename complete!'); }); </code></pre> <h2>fs.renameSync(oldPath, newPath)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L590">[src]</a><span><a class="mark" href="#fs_fs_renamesync_oldpath_newpath" id="fs_fs_renamesync_oldpath_newpath">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>oldPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>oldPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/rename.2.html"><code>rename(2)</code></a>. Returns <code>undefined</code>.</p> <h2>fs.rmdir(path, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L670">[src]</a><span><a class="mark" href="#fs_fs_rmdir_path_callback" id="fs_fs_rmdir_path_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameters can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.0.2</td> <td><p><span>Added in: v0.0.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/rmdir.2.html"><code>rmdir(2)</code></a>. No arguments other than a possible exception are given to the completion callback.</p> <p>Using <code>fs.rmdir()</code> on a file (not a directory) results in an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code> error on POSIX.</p> <h2>fs.rmdirSync(path)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L679">[src]</a><span><a class="mark" href="#fs_fs_rmdirsync_path" id="fs_fs_rmdirsync_path">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameters can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/rmdir.2.html"><code>rmdir(2)</code></a>. Returns <code>undefined</code>.</p> <p>Using <code>fs.rmdirSync()</code> on a file (not a directory) results in an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code> error on POSIX.</p> <h2>fs.stat(path[, options], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L818">[src]</a><span><a class="mark" href="#fs_fs_stat_path_options_callback" id="fs_fs_stat_path_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.5.0</td> <td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.0.2</td> <td><p><span>Added in: v0.0.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>stats</code> <a href="#fs_class_fs_stats" class="type"><fs.Stats></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/stat.2.html"><code>stat(2)</code></a>. The callback gets two arguments <code>(err, stats)</code> where <code>stats</code> is an <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object.</p> <p>In case of an error, the <code>err.code</code> will be one of <a href="#errors_common_system_errors">Common System Errors</a>.</p> <p>Using <code>fs.stat()</code> to check for the existence of a file before calling <code>fs.open()</code>, <code>fs.readFile()</code> or <code>fs.writeFile()</code> is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.</p> <p>To check if a file exists without manipulating it afterwards, <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a> is recommended.</p> <h2>fs.statSync(path[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L849">[src]</a><span><a class="mark" href="#fs_fs_statsync_path_options" id="fs_fs_statsync_path_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.5.0</td> <td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="#fs_class_fs_stats" class="type"><fs.Stats></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/stat.2.html"><code>stat(2)</code></a>.</p> <h2>fs.symlink(target, path[, type], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L880">[src]</a><span><a class="mark" href="#fs_fs_symlink_target_path_type_callback" id="fs_fs_symlink_target_path_type_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>target</code> and <code>path</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.31</td> <td><p><span>Added in: v0.1.31</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'file'</code></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/symlink.2.html"><code>symlink(2)</code></a>. No arguments other than a possible exception are given to the completion callback. The <code>type</code> argument can be set to <code>'dir'</code>, <code>'file'</code>, or <code>'junction'</code> and is only available on Windows (ignored on other platforms). Windows junction points require the destination path to be absolute. When using <code>'junction'</code>, the <code>target</code> argument will automatically be normalized to absolute path.</p> <p>Here is an example below:</p> <pre><code class="language-js">fs.symlink('./foo', './new-port', callback); </code></pre> <p>It creates a symbolic link named "new-port" that points to "foo".</p> <h2>fs.symlinkSync(target, path[, type])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L897">[src]</a><span><a class="mark" href="#fs_fs_symlinksync_target_path_type" id="fs_fs_symlinksync_target_path_type">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>target</code> and <code>path</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.31</td> <td><p><span>Added in: v0.1.31</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'file'</code></li> </ul> <p>Returns <code>undefined</code>.</p> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_symlink_target_path_type_callback"><code>fs.symlink()</code></a>.</p> <h2>fs.truncate(path[, len], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L601">[src]</a><span><a class="mark" href="#fs_fs_truncate_path_len_callback" id="fs_fs_truncate_path_len_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.8.6</td> <td><p><span>Added in: v0.8.6</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/truncate.2.html"><code>truncate(2)</code></a>. No arguments other than a possible exception are given to the completion callback. A file descriptor can also be passed as the first argument. In this case, <code>fs.ftruncate()</code> is called.</p> <p>Passing a file descriptor is deprecated and may result in an error being thrown in the future.</p> <h2>fs.truncateSync(path[, len])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L627">[src]</a><span><a class="mark" href="#fs_fs_truncatesync_path_len" id="fs_fs_truncatesync_path_len">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.8.6</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/truncate.2.html"><code>truncate(2)</code></a>. Returns <code>undefined</code>. A file descriptor can also be passed as the first argument. In this case, <code>fs.ftruncateSync()</code> is called.</p> <p>Passing a file descriptor is deprecated and may result in an error being thrown in the future.</p> <h2>fs.unlink(path, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L942">[src]</a><span><a class="mark" href="#fs_fs_unlink_path_callback" id="fs_fs_unlink_path_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.0.2</td> <td><p><span>Added in: v0.0.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.</p> <pre><code class="language-js">// Assuming that 'path/file.txt' is a regular file. fs.unlink('path/file.txt', (err) => { if (err) throw err; console.log('path/file.txt was deleted'); }); </code></pre> <p><code>fs.unlink()</code> will not work on a directory, empty or otherwise. To remove a directory, use <a href="#fs_fs_rmdir_path_callback"><code>fs.rmdir()</code></a>.</p> <p>See also: <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>.</p> <h2>fs.unlinkSync(path)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L951">[src]</a><span><a class="mark" href="#fs_fs_unlinksync_path" id="fs_fs_unlinksync_path">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> </ul> <p>Synchronous <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>. Returns <code>undefined</code>.</p> <h2>fs.unwatchFile(filename[, listener])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1312">[src]</a><span><a class="mark" href="#fs_fs_unwatchfile_filename_listener" id="fs_fs_unwatchfile_filename_listener">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.31</span> </div> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional, a listener previously attached using <code>fs.watchFile()</code></li> </ul> <p>Stop watching for changes on <code>filename</code>. If <code>listener</code> is specified, only that particular listener is removed. Otherwise, <em>all</em> listeners are removed, effectively stopping watching of <code>filename</code>.</p> <p>Calling <code>fs.unwatchFile()</code> with a filename that is not being watched is a no-op, not an error.</p> <p>Using <a href="#fs_fs_watch_filename_options_listener"><code>fs.watch()</code></a> is more efficient than <code>fs.watchFile()</code> and <code>fs.unwatchFile()</code>. <code>fs.watch()</code> should be used instead of <code>fs.watchFile()</code> and <code>fs.unwatchFile()</code> when possible.</p> <h2>fs.utimes(path, atime, mtime, callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1093">[src]</a><span><a class="mark" href="#fs_fs_utimes_path_atime_mtime_callback" id="fs_fs_utimes_path_atime_mtime_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v8.0.0</td> <td><p><code>NaN</code>, <code>Infinity</code>, and <code>-Infinity</code> are no longer valid time specifiers.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v4.1.0</td> <td><p>Numeric strings, <code>NaN</code> and <code>Infinity</code> are now allowed time specifiers.</p></td></tr> <tr><td>v0.4.2</td> <td><p><span>Added in: v0.4.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> <li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Change the file system timestamps of the object referenced by <code>path</code>.</p> <p>The <code>atime</code> and <code>mtime</code> arguments follow these rules:</p> <ul> <li>Values can be either numbers representing Unix epoch time, <code>Date</code>s, or a numeric string like <code>'123456789.0'</code>.</li> <li>If the value can not be converted to a number, or is <code>NaN</code>, <code>Infinity</code> or <code>-Infinity</code>, an <code>Error</code> will be thrown.</li> </ul> <h2>fs.utimesSync(path, atime, mtime)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1106">[src]</a><span><a class="mark" href="#fs_fs_utimessync_path_atime_mtime" id="fs_fs_utimessync_path_atime_mtime">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p><code>NaN</code>, <code>Infinity</code>, and <code>-Infinity</code> are no longer valid time specifiers.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v4.1.0</td> <td><p>Numeric strings, <code>NaN</code> and <code>Infinity</code> are now allowed time specifiers.</p></td></tr> <tr><td>v0.4.2</td> <td><p><span>Added in: v0.4.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Returns <code>undefined</code>.</p> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_utimes_path_atime_mtime_callback"><code>fs.utimes()</code></a>.</p> <h2>fs.watch(filename[, options][, listener])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1243">[src]</a><span><a class="mark" href="#fs_fs_watch_filename_options_listener" id="fs_fs_watch_filename_options_listener">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.6.0</td> <td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The passed <code>options</code> object will never be modified.</p></td></tr> <tr><td>v0.5.10</td> <td><p><span>Added in: v0.5.10</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>persistent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether the process should continue to run as long as files are being watched. <strong>Default:</strong> <code>true</code>.</li> <li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether all subdirectories should be watched, or only the current directory. This applies when a directory is specified, and only on supported platforms (See <a href="#fs_caveats">Caveats</a>). <strong>Default:</strong> <code>false</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the character encoding to be used for the filename passed to the listener. <strong>Default:</strong> <code>'utf8'</code>.</li> </ul> </li> <li> <p><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> <strong>Default:</strong> <code>undefined</code></p> <ul> <li><code>eventType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> <li>Returns: <a href="#fs_class_fs_fswatcher" class="type"><fs.FSWatcher></a></li> </ul> <p>Watch for changes on <code>filename</code>, where <code>filename</code> is either a file or a directory.</p> <p>The second argument is optional. If <code>options</code> is provided as a string, it specifies the <code>encoding</code>. Otherwise <code>options</code> should be passed as an object.</p> <p>The listener callback gets two arguments <code>(eventType, filename)</code>. <code>eventType</code> is either <code>'rename'</code> or <code>'change'</code>, and <code>filename</code> is the name of the file which triggered the event.</p> <p>On most platforms, <code>'rename'</code> is emitted whenever a filename appears or disappears in the directory.</p> <p>The listener callback is attached to the <code>'change'</code> event fired by <a href="#fs_class_fs_fswatcher"><code>fs.FSWatcher</code></a>, but it is not the same thing as the <code>'change'</code> value of <code>eventType</code>.</p> <h3>Caveats<span><a class="mark" href="#fs_caveats" id="fs_caveats">#</a></span></h3> <p>The <code>fs.watch</code> API is not 100% consistent across platforms, and is unavailable in some situations.</p> <p>The recursive option is only supported on macOS and Windows.</p> <h4>Availability<span><a class="mark" href="#fs_availability" id="fs_availability">#</a></span></h4> <p>This feature depends on the underlying operating system providing a way to be notified of filesystem changes.</p> <ul> <li>On Linux systems, this uses <a href="http://man7.org/linux/man-pages/man7/inotify.7.html"><code>inotify(7)</code></a>.</li> <li>On BSD systems, this uses <a href="https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2"><code>kqueue(2)</code></a>.</li> <li>On macOS, this uses <a href="https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2"><code>kqueue(2)</code></a> for files and <a href="https://developer.apple.com/documentation/coreservices/file_system_events"><code>FSEvents</code></a> for directories.</li> <li>On SunOS systems (including Solaris and SmartOS), this uses <a href="http://illumos.org/man/port_create"><code>event ports</code></a>.</li> <li>On Windows systems, this feature depends on <a href="https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-readdirectorychangesw"><code>ReadDirectoryChangesW</code></a>.</li> <li>On Aix systems, this feature depends on <a href="https://www.ibm.com/developerworks/aix/library/au-aix_event_infrastructure/"><code>AHAFS</code></a>, which must be enabled.</li> </ul> <p>If the underlying functionality is not available for some reason, then <code>fs.watch</code> will not be able to function. For example, watching files or directories can be unreliable, and in some cases impossible, on network file systems (NFS, SMB, etc), or host file systems when using virtualization software such as Vagrant, Docker, etc.</p> <p>It is still possible to use <code>fs.watchFile()</code>, which uses stat polling, but this method is slower and less reliable.</p> <h4>Inodes<span><a class="mark" href="#fs_inodes" id="fs_inodes">#</a></span></h4> <p>On Linux and macOS systems, <code>fs.watch()</code> resolves the path to an <a href="https://en.wikipedia.org/wiki/Inode">inode</a> and watches the inode. If the watched path is deleted and recreated, it is assigned a new inode. The watch will emit an event for the delete but will continue watching the <em>original</em> inode. Events for the new inode will not be emitted. This is expected behavior.</p> <p>AIX files retain the same inode for the lifetime of a file. Saving and closing a watched file on AIX will result in two notifications (one for adding new content, and one for truncation).</p> <h4>Filename Argument<span><a class="mark" href="#fs_filename_argument" id="fs_filename_argument">#</a></span></h4> <p>Providing <code>filename</code> argument in the callback is only supported on Linux, macOS, Windows, and AIX. Even on supported platforms, <code>filename</code> is not always guaranteed to be provided. Therefore, don't assume that <code>filename</code> argument is always provided in the callback, and have some fallback logic if it is <code>null</code>.</p> <pre><code class="language-js">fs.watch('somedir', (eventType, filename) => { console.log(`event type is: ${eventType}`); if (filename) { console.log(`filename provided: ${filename}`); } else { console.log('filename not provided'); } }); </code></pre> <h2>fs.watchFile(filename[, options], listener)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1273">[src]</a><span><a class="mark" href="#fs_fs_watchfile_filename_options_listener" id="fs_fs_watchfile_filename_options_listener">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.5.0</td> <td><p>The <code>bigint</code> option is now supported.</p></td></tr> <tr><td>v7.6.0</td> <td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr> <tr><td>v0.1.31</td> <td><p><span>Added in: v0.1.31</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li> <li><code>persistent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code></li> <li><code>interval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>5007</code></li> </ul> </li> <li> <p><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>current</code> <a href="#fs_class_fs_stats" class="type"><fs.Stats></a></li> <li><code>previous</code> <a href="#fs_class_fs_stats" class="type"><fs.Stats></a></li> </ul> </li> </ul> <p>Watch for changes on <code>filename</code>. The callback <code>listener</code> will be called each time the file is accessed.</p> <p>The <code>options</code> argument may be omitted. If provided, it should be an object. The <code>options</code> object may contain a boolean named <code>persistent</code> that indicates whether the process should continue to run as long as files are being watched. The <code>options</code> object may specify an <code>interval</code> property indicating how often the target should be polled in milliseconds.</p> <p>The <code>listener</code> gets two arguments the current stat object and the previous stat object:</p> <pre><code class="language-js">fs.watchFile('message.text', (curr, prev) => { console.log(`the current mtime is: ${curr.mtime}`); console.log(`the previous mtime was: ${prev.mtime}`); }); </code></pre> <p>These stat objects are instances of <code>fs.Stat</code>. If the <code>bigint</code> option is <code>true</code>, the numeric values in these objects are specified as <code>BigInt</code>s.</p> <p>To be notified when the file was modified, not just accessed, it is necessary to compare <code>curr.mtime</code> and <code>prev.mtime</code>.</p> <p>When an <code>fs.watchFile</code> operation results in an <code>ENOENT</code> error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). In Windows, <code>blksize</code> and <code>blocks</code> fields will be <code>undefined</code>, instead of zero. If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.</p> <p>Using <a href="#fs_fs_watch_filename_options_listener"><code>fs.watch()</code></a> is more efficient than <code>fs.watchFile</code> and <code>fs.unwatchFile</code>. <code>fs.watch</code> should be used instead of <code>fs.watchFile</code> and <code>fs.unwatchFile</code> when possible.</p> <p>When a file being watched by <code>fs.watchFile()</code> disappears and reappears, then the <code>previousStat</code> reported in the second callback event (the file's reappearance) will be the same as the <code>previousStat</code> of the first callback event (its disappearance).</p> <p>This happens when:</p> <ul> <li>the file is deleted, followed by a restore</li> <li>the file is renamed twice - the second time back to its original name</li> </ul> <h2>fs.write(fd, buffer[, offset[, length[, position]]], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L506">[src]</a><span><a class="mark" href="#fs_fs_write_fd_buffer_offset_length_position_callback" id="fs_fs_write_fd_buffer_offset_length_position_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code></p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.4.0</td> <td><p>The <code>buffer</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v7.2.0</td> <td><p>The <code>offset</code> and <code>length</code> parameters are optional now.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.0.2</td> <td><p><span>Added in: v0.0.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> </ul> </li> </ul> <p>Write <code>buffer</code> to the file specified by <code>fd</code>.</p> <p><code>offset</code> determines the part of the buffer to be written, and <code>length</code> is an integer specifying the number of bytes to write.</p> <p><code>position</code> refers to the offset from the beginning of the file where this data should be written. If <code>typeof position !== 'number'</code>, the data will be written at the current position. See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>.</p> <p>The callback will be given three arguments <code>(err, bytesWritten, buffer)</code> where <code>bytesWritten</code> specifies how many <em>bytes</em> were written from <code>buffer</code>.</p> <p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns a <code>Promise</code> for an <code>Object</code> with <code>bytesWritten</code> and <code>buffer</code> properties.</p> <p>It is unsafe to use <code>fs.write()</code> multiple times on the same file without waiting for the callback. For this scenario, <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a> is recommended.</p> <p>On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.</p> <h2>fs.write(fd, string[, position[, encoding]], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L506">[src]</a><span><a class="mark" href="#fs_fs_write_fd_string_position_encoding_callback" id="fs_fs_write_fd_string_position_encoding_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.2.0</td> <td><p>The <code>position</code> parameter is optional now.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v0.11.5</td> <td><p><span>Added in: v0.11.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>written</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> </li> </ul> <p>Write <code>string</code> to the file specified by <code>fd</code>. If <code>string</code> is not a string, then the value will be coerced to one.</p> <p><code>position</code> refers to the offset from the beginning of the file where this data should be written. If <code>typeof position !== 'number'</code> the data will be written at the current position. See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>.</p> <p><code>encoding</code> is the expected string encoding.</p> <p>The callback will receive the arguments <code>(err, written, string)</code> where <code>written</code> specifies how many <em>bytes</em> the passed string required to be written. Bytes written is not necessarily the same as string characters written. See <a href="#buffer_class_method_buffer_bytelength_string_encoding"><code>Buffer.byteLength</code></a>.</p> <p>It is unsafe to use <code>fs.write()</code> multiple times on the same file without waiting for the callback. For this scenario, <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a> is recommended.</p> <p>On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.</p> <p>On Windows, if the file descriptor is connected to the console (e.g. <code>fd == 1</code> or <code>stdout</code>) a string containing non-ASCII characters will not be rendered properly by default, regardless of the encoding used. It is possible to configure the console to render UTF-8 properly by changing the active codepage with the <code>chcp 65001</code> command. See the <a href="https://ss64.com/nt/chcp.html">chcp</a> docs for more details.</p> <h2>fs.writeFile(file, data[, options], callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1162">[src]</a><span><a class="mark" href="#fs_fs_writefile_file_data_options_callback" id="fs_fs_writefile_file_data_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>The <code>data</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr> <tr><td>v7.4.0</td> <td><p>The <code>data</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v7.0.0</td> <td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr> <tr><td>v5.0.0</td> <td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr> <tr><td>v0.1.29</td> <td><p><span>Added in: v0.1.29</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> filename or file descriptor</li> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> </li> </ul> <p>Asynchronously writes data to a file, replacing the file if it already exists. <code>data</code> can be a string or a buffer.</p> <p>The <code>encoding</code> option is ignored if <code>data</code> is a buffer.</p> <pre><code class="language-js">const data = new Uint8Array(Buffer.from('Hello Node.js')); fs.writeFile('message.txt', data, (err) => { if (err) throw err; console.log('The file has been saved!'); }); </code></pre> <p>If <code>options</code> is a string, then it specifies the encoding:</p> <pre><code class="language-js">fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback); </code></pre> <p>It is unsafe to use <code>fs.writeFile()</code> multiple times on the same file without waiting for the callback. For this scenario, <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a> is recommended.</p> <h3>File Descriptors<span><a class="mark" href="#fs_file_descriptors_2" id="fs_file_descriptors_2">#</a></span></h3> <ol> <li>Any specified file descriptor has to support writing.</li> <li>If a file descriptor is specified as the <code>file</code>, it will not be closed automatically.</li> <li>The writing will begin at the beginning of the file. For example, if the file already had <code>'Hello World'</code> and the newly written content is <code>'Aloha'</code>, then the contents of the file would be <code>'Aloha World'</code>, rather than just <code>'Aloha'</code>.</li> </ol> <h2>fs.writeFileSync(file, data[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L1189">[src]</a><span><a class="mark" href="#fs_fs_writefilesync_file_data_options" id="fs_fs_writefilesync_file_data_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>The <code>data</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr> <tr><td>v7.4.0</td> <td><p>The <code>data</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v5.0.0</td> <td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr> <tr><td>v0.1.29</td> <td><p><span>Added in: v0.1.29</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> filename or file descriptor</li> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li> </ul> </li> </ul> <p>Returns <code>undefined</code>.</p> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_writefile_file_data_options_callback"><code>fs.writeFile()</code></a>.</p> <h2>fs.writeSync(fd, buffer[, offset[, length[, position]]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L551">[src]</a><span><a class="mark" href="#fs_fs_writesync_fd_buffer_offset_length_position" id="fs_fs_writesync_fd_buffer_offset_length_position">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr> <tr><td>v7.4.0</td> <td><p>The <code>buffer</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr> <tr><td>v7.2.0</td> <td><p>The <code>offset</code> and <code>length</code> parameters are optional now.</p></td></tr> <tr><td>v0.1.21</td> <td><p><span>Added in: v0.1.21</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes written.</li> </ul> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_write_fd_buffer_offset_length_position_callback"><code>fs.write(fd, buffer...)</code></a>.</p> <h2>fs.writeSync(fd, string[, position[, encoding]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/fs.js#L551">[src]</a><span><a class="mark" href="#fs_fs_writesync_fd_string_position_encoding" id="fs_fs_writesync_fd_string_position_encoding">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.2.0</td> <td><p>The <code>position</code> parameter is optional now.</p></td></tr> <tr><td>v0.11.5</td> <td><p><span>Added in: v0.11.5</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes written.</li> </ul> <p>For detailed information, see the documentation of the asynchronous version of this API: <a href="#fs_fs_write_fd_string_position_encoding_callback"><code>fs.write(fd, string...)</code></a>.</p> <h2>fs Promises API<span><a class="mark" href="#fs_fs_promises_api" id="fs_fs_promises_api">#</a></span></h2> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>fs.promises</code> API provides an alternative set of asynchronous file system methods that return <code>Promise</code> objects rather than using callbacks. The API is accessible via <code>require('fs').promises</code>.</p> <h3>class: FileHandle<span><a class="mark" href="#fs_class_filehandle" id="fs_class_filehandle">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>A <code>FileHandle</code> object is a wrapper for a numeric file descriptor. Instances of <code>FileHandle</code> are distinct from numeric file descriptors in that, if the <code>FileHandle</code> is not explicitly closed using the <code>filehandle.close()</code> method, they will automatically close the file descriptor and will emit a process warning, thereby helping to prevent memory leaks.</p> <p>Instances of the <code>FileHandle</code> object are created internally by the <code>fsPromises.open()</code> method.</p> <p>Unlike the callback-based API (<code>fs.fstat()</code>, <code>fs.fchown()</code>, <code>fs.fchmod()</code>, and so on), a numeric file descriptor is not used by the promise-based API. Instead, the promise-based API uses the <code>FileHandle</code> class in order to help avoid accidental leaking of unclosed file descriptors after a <code>Promise</code> is resolved or rejected.</p> <h4>filehandle.appendFile(data, options)<span><a class="mark" href="#fs_filehandle_appendfile_data_options" id="fs_filehandle_appendfile_data_options">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronously append data to this file, creating the file if it does not yet exist. <code>data</code> can be a string or a <a href="#buffer_buffer"><code>Buffer</code></a>. The <code>Promise</code> will be resolved with no arguments upon success.</p> <p>If <code>options</code> is a string, then it specifies the encoding.</p> <p>The <code>FileHandle</code> must have been opened for appending.</p> <h4>filehandle.chmod(mode)<span><a class="mark" href="#fs_filehandle_chmod_mode" id="fs_filehandle_chmod_mode">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Modifies the permissions on the file. The <code>Promise</code> is resolved with no arguments upon success.</p> <h4>filehandle.chown(uid, gid)<span><a class="mark" href="#fs_filehandle_chown_uid_gid" id="fs_filehandle_chown_uid_gid">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Changes the ownership of the file then resolves the <code>Promise</code> with no arguments upon success.</p> <h4>filehandle.close()<span><a class="mark" href="#fs_filehandle_close" id="fs_filehandle_close">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> A <code>Promise</code> that will be resolved once the underlying file descriptor is closed, or will be rejected if an error occurs while closing.</li> </ul> <p>Closes the file descriptor.</p> <pre><code class="language-js">const fsPromises = require('fs').promises; async function openAndClose() { let filehandle; try { filehandle = await fsPromises.open('thefile.txt', 'r'); } finally { if (filehandle !== undefined) await filehandle.close(); } } </code></pre> <h4>filehandle.datasync()<span><a class="mark" href="#fs_filehandle_datasync" id="fs_filehandle_datasync">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a>. The <code>Promise</code> is resolved with no arguments upon success.</p> <h4>filehandle.fd<span><a class="mark" href="#fs_filehandle_fd" id="fs_filehandle_fd">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The numeric file descriptor managed by the <code>FileHandle</code> object.</li> </ul> <h4>filehandle.read(buffer, offset, length, position)<span><a class="mark" href="#fs_filehandle_read_buffer_offset_length_position" id="fs_filehandle_read_buffer_offset_length_position">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Read data from the file.</p> <p><code>buffer</code> is the buffer that the data will be written to.</p> <p><code>offset</code> is the offset in the buffer to start writing at.</p> <p><code>length</code> is an integer specifying the number of bytes to read.</p> <p><code>position</code> is an argument specifying where to begin reading from in the file. If <code>position</code> is <code>null</code>, data will be read from the current file position, and the file position will be updated. If <code>position</code> is an integer, the file position will remain unchanged.</p> <p>Following successful read, the <code>Promise</code> is resolved with an object with a <code>bytesRead</code> property specifying the number of bytes read, and a <code>buffer</code> property that is a reference to the passed in <code>buffer</code> argument.</p> <h4>filehandle.readFile(options)<span><a class="mark" href="#fs_filehandle_readfile_options" id="fs_filehandle_readfile_options">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronously reads the entire contents of a file.</p> <p>The <code>Promise</code> is resolved with the contents of the file. If no encoding is specified (using <code>options.encoding</code>), the data is returned as a <code>Buffer</code> object. Otherwise, the data will be a string.</p> <p>If <code>options</code> is a string, then it specifies the encoding.</p> <p>When the <code>path</code> is a directory, the behavior of <code>fsPromises.readFile()</code> is platform-specific. On macOS, Linux, and Windows, the promise will be rejected with an error. On FreeBSD, a representation of the directory's contents will be returned.</p> <p>The <code>FileHandle</code> has to support reading.</p> <p>If one or more <code>filehandle.read()</code> calls are made on a file handle and then a <code>filehandle.readFile()</code> call is made, the data will be read from the current position till the end of the file. It doesn't always read from the beginning of the file.</p> <h4>filehandle.stat([options])<span><a class="mark" href="#fs_filehandle_stat_options" id="fs_filehandle_stat_options">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.5.0</td> <td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr> <tr><td>v10.0.0</td> <td><p><span>Added in: v10.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Retrieves the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> for the file.</p> <h4>filehandle.sync()<span><a class="mark" href="#fs_filehandle_sync" id="fs_filehandle_sync">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a>. The <code>Promise</code> is resolved with no arguments upon success.</p> <h4>filehandle.truncate(len)<span><a class="mark" href="#fs_filehandle_truncate_len" id="fs_filehandle_truncate_len">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Truncates the file then resolves the <code>Promise</code> with no arguments upon success.</p> <p>If the file was larger than <code>len</code> bytes, only the first <code>len</code> bytes will be retained in the file.</p> <p>For example, the following program retains only the first four bytes of the file:</p> <pre><code class="language-js">const fs = require('fs'); const fsPromises = fs.promises; console.log(fs.readFileSync('temp.txt', 'utf8')); // Prints: Node.js async function doTruncate() { let filehandle = null; try { filehandle = await fsPromises.open('temp.txt', 'r+'); await filehandle.truncate(4); } finally { if (filehandle) { // close the file if it is opened. await filehandle.close(); } } console.log(fs.readFileSync('temp.txt', 'utf8')); // Prints: Node } doTruncate().catch(console.error); </code></pre> <p>If the file previously was shorter than <code>len</code> bytes, it is extended, and the extended part is filled with null bytes (<code>'\0'</code>):</p> <pre><code class="language-js">const fs = require('fs'); const fsPromises = fs.promises; console.log(fs.readFileSync('temp.txt', 'utf8')); // Prints: Node.js async function doTruncate() { let filehandle = null; try { filehandle = await fsPromises.open('temp.txt', 'r+'); await filehandle.truncate(10); } finally { if (filehandle) { // close the file if it is opened. await filehandle.close(); } } console.log(fs.readFileSync('temp.txt', 'utf8')); // Prints Node.js\0\0\0 } doTruncate().catch(console.error); </code></pre> <p>The last three bytes are null bytes (<code>'\0'</code>), to compensate the over-truncation.</p> <h4>filehandle.utimes(atime, mtime)<span><a class="mark" href="#fs_filehandle_utimes_atime_mtime" id="fs_filehandle_utimes_atime_mtime">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> <li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Change the file system timestamps of the object referenced by the <code>FileHandle</code> then resolves the <code>Promise</code> with no arguments upon success.</p> <p>This function does not work on AIX versions before 7.1, it will resolve the <code>Promise</code> with an error using code <code>UV_ENOSYS</code>.</p> <h4>filehandle.write(buffer, offset, length, position)<span><a class="mark" href="#fs_filehandle_write_buffer_offset_length_position" id="fs_filehandle_write_buffer_offset_length_position">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Write <code>buffer</code> to the file.</p> <p>The <code>Promise</code> is resolved with an object containing a <code>bytesWritten</code> property identifying the number of bytes written, and a <code>buffer</code> property containing a reference to the <code>buffer</code> written.</p> <p><code>offset</code> determines the part of the buffer to be written, and <code>length</code> is an integer specifying the number of bytes to write.</p> <p><code>position</code> refers to the offset from the beginning of the file where this data should be written. If <code>typeof position !== 'number'</code>, the data will be written at the current position. See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>.</p> <p>It is unsafe to use <code>filehandle.write()</code> multiple times on the same file without waiting for the <code>Promise</code> to be resolved (or rejected). For this scenario, <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a> is strongly recommended.</p> <p>On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.</p> <h4>filehandle.write(string[, position[, encoding]])<span><a class="mark" href="#fs_filehandle_write_string_position_encoding" id="fs_filehandle_write_string_position_encoding">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Write <code>string</code> to the file. If <code>string</code> is not a string, then the value will be coerced to one.</p> <p>The <code>Promise</code> is resolved with an object containing a <code>bytesWritten</code> property identifying the number of bytes written, and a <code>buffer</code> property containing a reference to the <code>string</code> written.</p> <p><code>position</code> refers to the offset from the beginning of the file where this data should be written. If the type of <code>position</code> is not a <code>number</code> the data will be written at the current position. See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>.</p> <p><code>encoding</code> is the expected string encoding.</p> <p>It is unsafe to use <code>filehandle.write()</code> multiple times on the same file without waiting for the <code>Promise</code> to be resolved (or rejected). For this scenario, <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a> is strongly recommended.</p> <p>On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.</p> <h4>filehandle.writeFile(data, options)<span><a class="mark" href="#fs_filehandle_writefile_data_options" id="fs_filehandle_writefile_data_options">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronously writes data to a file, replacing the file if it already exists. <code>data</code> can be a string or a buffer. The <code>Promise</code> will be resolved with no arguments upon success.</p> <p>The <code>encoding</code> option is ignored if <code>data</code> is a buffer.</p> <p>If <code>options</code> is a string, then it specifies the encoding.</p> <p>The <code>FileHandle</code> has to support writing.</p> <p>It is unsafe to use <code>filehandle.writeFile()</code> multiple times on the same file without waiting for the <code>Promise</code> to be resolved (or rejected).</p> <p>If one or more <code>filehandle.write()</code> calls are made on a file handle and then a <code>filehandle.writeFile()</code> call is made, the data will be written from the current position till the end of the file. It doesn't always write from the beginning of the file.</p> <h3>fsPromises.access(path[, mode])<span><a class="mark" href="#fs_fspromises_access_path_mode" id="fs_fspromises_access_path_mode">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>fs.constants.F_OK</code></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Tests a user's permissions for the file or directory specified by <code>path</code>. The <code>mode</code> argument is an optional integer that specifies the accessibility checks to be performed. Check <a href="#fs_file_access_constants">File Access Constants</a> for possible values of <code>mode</code>. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. <code>fs.constants.W_OK | fs.constants.R_OK</code>).</p> <p>If the accessibility check is successful, the <code>Promise</code> is resolved with no value. If any of the accessibility checks fail, the <code>Promise</code> is rejected with an <code>Error</code> object. The following example checks if the file <code>/etc/passwd</code> can be read and written by the current process.</p> <pre><code class="language-js">const fs = require('fs'); const fsPromises = fs.promises; fsPromises.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK) .then(() => console.log('can access')) .catch(() => console.error('cannot access')); </code></pre> <p>Using <code>fsPromises.access()</code> to check for the accessibility of a file before calling <code>fsPromises.open()</code> is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.</p> <h3>fsPromises.appendFile(path, data[, options])<span><a class="mark" href="#fs_fspromises_appendfile_path_data_options" id="fs_fspromises_appendfile_path_data_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="#fs_class_filehandle" class="type"><FileHandle></a> filename or <code>FileHandle</code></li> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronously append data to a file, creating the file if it does not yet exist. <code>data</code> can be a string or a <a href="#buffer_buffer"><code>Buffer</code></a>. The <code>Promise</code> will be resolved with no arguments upon success.</p> <p>If <code>options</code> is a string, then it specifies the encoding.</p> <p>The <code>path</code> may be specified as a <code>FileHandle</code> that has been opened for appending (using <code>fsPromises.open()</code>).</p> <h3>fsPromises.chmod(path, mode)<span><a class="mark" href="#fs_fspromises_chmod_path_mode" id="fs_fspromises_chmod_path_mode">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Changes the permissions of a file then resolves the <code>Promise</code> with no arguments upon succces.</p> <h3>fsPromises.chown(path, uid, gid)<span><a class="mark" href="#fs_fspromises_chown_path_uid_gid" id="fs_fspromises_chown_path_uid_gid">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Changes the ownership of a file then resolves the <code>Promise</code> with no arguments upon success.</p> <h3>fsPromises.copyFile(src, dest[, flags])<span><a class="mark" href="#fs_fspromises_copyfile_src_dest_flags" id="fs_fspromises_copyfile_src_dest_flags">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> source filename to copy</li> <li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> destination filename of the copy operation</li> <li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronously copies <code>src</code> to <code>dest</code>. By default, <code>dest</code> is overwritten if it already exists. The <code>Promise</code> will be resolved with no arguments upon success.</p> <p>Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.</p> <p><code>flags</code> is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. <code>fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE</code>).</p> <ul> <li><code>fs.constants.COPYFILE_EXCL</code> - The copy operation will fail if <code>dest</code> already exists.</li> <li><code>fs.constants.COPYFILE_FICLONE</code> - The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.</li> <li><code>fs.constants.COPYFILE_FICLONE_FORCE</code> - The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.</li> </ul> <pre><code class="language-js">const fsPromises = require('fs').promises; // destination.txt will be created or overwritten by default. fsPromises.copyFile('source.txt', 'destination.txt') .then(() => console.log('source.txt was copied to destination.txt')) .catch(() => console.log('The file could not be copied')); </code></pre> <p>If the third argument is a number, then it specifies <code>flags</code>:</p> <pre><code class="language-js">const fs = require('fs'); const fsPromises = fs.promises; const { COPYFILE_EXCL } = fs.constants; // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. fsPromises.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL) .then(() => console.log('source.txt was copied to destination.txt')) .catch(() => console.log('The file could not be copied')); </code></pre> <h3>fsPromises.lchmod(path, mode)<span><a class="mark" href="#fs_fspromises_lchmod_path_mode" id="fs_fspromises_lchmod_path_mode">#</a></span></h3> <div class="api_metadata"> <span>Deprecated since: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Changes the permissions on a symbolic link then resolves the <code>Promise</code> with no arguments upon success. This method is only implemented on macOS.</p> <h3>fsPromises.lchown(path, uid, gid)<span><a class="mark" href="#fs_fspromises_lchown_path_uid_gid" id="fs_fspromises_lchown_path_uid_gid">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.6.0</td> <td><p>This API is no longer deprecated.</p></td></tr> <tr><td>v10.0.0</td> <td><p><span>Added in: v10.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Changes the ownership on a symbolic link then resolves the <code>Promise</code> with no arguments upon success.</p> <h3>fsPromises.link(existingPath, newPath)<span><a class="mark" href="#fs_fspromises_link_existingpath_newpath" id="fs_fspromises_link_existingpath_newpath">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>existingPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a>. The <code>Promise</code> is resolved with no arguments upon success.</p> <h3>fsPromises.lstat(path[, options])<span><a class="mark" href="#fs_fspromises_lstat_path_options" id="fs_fspromises_lstat_path_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.5.0</td> <td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr> <tr><td>v10.0.0</td> <td><p><span>Added in: v10.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a>. The <code>Promise</code> is resolved with the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object for the given symbolic link <code>path</code>.</p> <h3>fsPromises.mkdir(path[, options])<span><a class="mark" href="#fs_fspromises_mkdir_path_options" id="fs_fspromises_mkdir_path_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></p> <ul> <li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Not supported on Windows. <strong>Default:</strong> <code>0o777</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronously creates a directory then resolves the <code>Promise</code> with no arguments upon success.</p> <p>The optional <code>options</code> argument can be an integer specifying mode (permission and sticky bits), or an object with a <code>mode</code> property and a <code>recursive</code> property indicating whether parent folders should be created.</p> <h3>fsPromises.mkdtemp(prefix[, options])<span><a class="mark" href="#fs_fspromises_mkdtemp_prefix_options" id="fs_fspromises_mkdtemp_prefix_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>prefix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Creates a unique temporary directory and resolves the <code>Promise</code> with the created folder path. A unique directory name is generated by appending six random characters to the end of the provided <code>prefix</code>.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use.</p> <pre><code class="language-js">fsPromises.mkdtemp(path.join(os.tmpdir(), 'foo-')) .catch(console.error); </code></pre> <p>The <code>fsPromises.mkdtemp()</code> method will append the six randomly selected characters directly to the <code>prefix</code> string. For instance, given a directory <code>/tmp</code>, if the intention is to create a temporary directory <em>within</em> <code>/tmp</code>, the <code>prefix</code> must end with a trailing platform-specific path separator (<code>require('path').sep</code>).</p> <h3>fsPromises.open(path, flags[, mode])<span><a class="mark" href="#fs_fspromises_open_path_flags_mode" id="fs_fspromises_open_path_flags_mode">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v11.1.0</td> <td><p>The <code>flags</code> argument is now optional and defaults to <code>'r'</code>.</p></td></tr> <tr><td>v10.0.0</td> <td><p><span>Added in: v10.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code> (readable and writable)</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronous file open that returns a <code>Promise</code> that, when resolved, yields a <code>FileHandle</code> object. See <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a>.</p> <p><code>mode</code> sets the file mode (permission and sticky bits), but only if the file was created.</p> <p>Some characters (<code>< > : " / \ | ? *</code>) are reserved under Windows as documented by <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file">Naming Files, Paths, and Namespaces</a>. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams">this MSDN page</a>.</p> <h3>fsPromises.readdir(path[, options])<span><a class="mark" href="#fs_fspromises_readdir_path_options" id="fs_fspromises_readdir_path_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.11.0</td> <td><p>New option <code>withFileTypes</code> was added.</p></td></tr> <tr><td>v10.0.0</td> <td><p><span>Added in: v10.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>withFileTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Reads the contents of a directory then resolves the <code>Promise</code> with an array of the names of the files in the directory excluding <code>'.'</code> and <code>'..'</code>.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use for the filenames. If the <code>encoding</code> is set to <code>'buffer'</code>, the filenames returned will be passed as <code>Buffer</code> objects.</p> <p>If <code>options.withFileTypes</code> is set to <code>true</code>, the resolved array will contain <a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a> objects.</p> <h3>fsPromises.readFile(path[, options])<span><a class="mark" href="#fs_fspromises_readfile_path_options" id="fs_fspromises_readfile_path_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="#fs_class_filehandle" class="type"><FileHandle></a> filename or <code>FileHandle</code></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>null</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronously reads the entire contents of a file.</p> <p>The <code>Promise</code> is resolved with the contents of the file. If no encoding is specified (using <code>options.encoding</code>), the data is returned as a <code>Buffer</code> object. Otherwise, the data will be a string.</p> <p>If <code>options</code> is a string, then it specifies the encoding.</p> <p>When the <code>path</code> is a directory, the behavior of <code>fsPromises.readFile()</code> is platform-specific. On macOS, Linux, and Windows, the promise will be rejected with an error. On FreeBSD, a representation of the directory's contents will be returned.</p> <p>Any specified <code>FileHandle</code> has to support reading.</p> <h3>fsPromises.readlink(path[, options])<span><a class="mark" href="#fs_fspromises_readlink_path_options" id="fs_fspromises_readlink_path_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a>. The <code>Promise</code> is resolved with the <code>linkString</code> upon success.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use for the link path returned. If the <code>encoding</code> is set to <code>'buffer'</code>, the link path returned will be passed as a <code>Buffer</code> object.</p> <h3>fsPromises.realpath(path[, options])<span><a class="mark" href="#fs_fspromises_realpath_path_options" id="fs_fspromises_realpath_path_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Determines the actual location of <code>path</code> using the same semantics as the <code>fs.realpath.native()</code> function then resolves the <code>Promise</code> with the resolved path.</p> <p>Only paths that can be converted to UTF8 strings are supported.</p> <p>The optional <code>options</code> argument can be a string specifying an encoding, or an object with an <code>encoding</code> property specifying the character encoding to use for the path. If the <code>encoding</code> is set to <code>'buffer'</code>, the path returned will be passed as a <code>Buffer</code> object.</p> <p>On Linux, when Node.js is linked against musl libc, the procfs file system must be mounted on <code>/proc</code> in order for this function to work. Glibc does not have this restriction.</p> <h3>fsPromises.rename(oldPath, newPath)<span><a class="mark" href="#fs_fspromises_rename_oldpath_newpath" id="fs_fspromises_rename_oldpath_newpath">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>oldPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Renames <code>oldPath</code> to <code>newPath</code> and resolves the <code>Promise</code> with no arguments upon success.</p> <h3>fsPromises.rmdir(path)<span><a class="mark" href="#fs_fspromises_rmdir_path" id="fs_fspromises_rmdir_path">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Removes the directory identified by <code>path</code> then resolves the <code>Promise</code> with no arguments upon success.</p> <p>Using <code>fsPromises.rmdir()</code> on a file (not a directory) results in the <code>Promise</code> being rejected with an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code> error on POSIX.</p> <h3>fsPromises.stat(path[, options])<span><a class="mark" href="#fs_fspromises_stat_path_options" id="fs_fspromises_stat_path_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.5.0</td> <td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr> <tr><td>v10.0.0</td> <td><p><span>Added in: v10.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether the numeric values in the returned <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>The <code>Promise</code> is resolved with the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object for the given <code>path</code>.</p> <h3>fsPromises.symlink(target, path[, type])<span><a class="mark" href="#fs_fspromises_symlink_target_path_type" id="fs_fspromises_symlink_target_path_type">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'file'</code></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Creates a symbolic link then resolves the <code>Promise</code> with no arguments upon success.</p> <p>The <code>type</code> argument is only used on Windows platforms and can be one of <code>'dir'</code>, <code>'file'</code>, or <code>'junction'</code>. Windows junction points require the destination path to be absolute. When using <code>'junction'</code>, the <code>target</code> argument will automatically be normalized to absolute path.</p> <h3>fsPromises.truncate(path[, len])<span><a class="mark" href="#fs_fspromises_truncate_path_len" id="fs_fspromises_truncate_path_len">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0</code></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Truncates the <code>path</code> then resolves the <code>Promise</code> with no arguments upon success. The <code>path</code> <em>must</em> be a string or <code>Buffer</code>.</p> <h3>fsPromises.unlink(path)<span><a class="mark" href="#fs_fspromises_unlink_path" id="fs_fspromises_unlink_path">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>. The <code>Promise</code> is resolved with no arguments upon success.</p> <h3>fsPromises.utimes(path, atime, mtime)<span><a class="mark" href="#fs_fspromises_utimes_path_atime_mtime" id="fs_fspromises_utimes_path_atime_mtime">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> <li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type"><Date></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Change the file system timestamps of the object referenced by <code>path</code> then resolves the <code>Promise</code> with no arguments upon success.</p> <p>The <code>atime</code> and <code>mtime</code> arguments follow these rules:</p> <ul> <li>Values can be either numbers representing Unix epoch time, <code>Date</code>s, or a numeric string like <code>'123456789.0'</code>.</li> <li>If the value can not be converted to a number, or is <code>NaN</code>, <code>Infinity</code> or <code>-Infinity</code>, an <code>Error</code> will be thrown.</li> </ul> <h3>fsPromises.writeFile(file, data[, options])<span><a class="mark" href="#fs_fspromises_writefile_file_data_options" id="fs_fspromises_writefile_file_data_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="#fs_class_filehandle" class="type"><FileHandle></a> filename or <code>FileHandle</code></li> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>0o666</code></li> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Asynchronously writes data to a file, replacing the file if it already exists. <code>data</code> can be a string or a buffer. The <code>Promise</code> will be resolved with no arguments upon success.</p> <p>The <code>encoding</code> option is ignored if <code>data</code> is a buffer.</p> <p>If <code>options</code> is a string, then it specifies the encoding.</p> <p>Any specified <code>FileHandle</code> has to support writing.</p> <p>It is unsafe to use <code>fsPromises.writeFile()</code> multiple times on the same file without waiting for the <code>Promise</code> to be resolved (or rejected).</p> <h2>FS Constants<span><a class="mark" href="#fs_fs_constants_1" id="fs_fs_constants_1">#</a></span></h2> <p>The following constants are exported by <code>fs.constants</code>.</p> <p>Not every constant will be available on every operating system.</p> <h3>File Access Constants<span><a class="mark" href="#fs_file_access_constants" id="fs_file_access_constants">#</a></span></h3> <p>The following constants are meant for use with <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a>.</p> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>F_OK</code></td> <td>Flag indicating that the file is visible to the calling process. This is useful for determining if a file exists, but says nothing about <code>rwx</code> permissions. Default if no mode is specified.</td> </tr> <tr> <td><code>R_OK</code></td> <td>Flag indicating that the file can be read by the calling process.</td> </tr> <tr> <td><code>W_OK</code></td> <td>Flag indicating that the file can be written by the calling process.</td> </tr> <tr> <td><code>X_OK</code></td> <td>Flag indicating that the file can be executed by the calling process. This has no effect on Windows (will behave like <code>fs.constants.F_OK</code>).</td> </tr> </tbody></table> <h3>File Copy Constants<span><a class="mark" href="#fs_file_copy_constants" id="fs_file_copy_constants">#</a></span></h3> <p>The following constants are meant for use with <a href="#fs_fs_copyfile_src_dest_flags_callback"><code>fs.copyFile()</code></a>.</p> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>COPYFILE_EXCL</code></td> <td>If present, the copy operation will fail with an error if the destination path already exists.</td> </tr> <tr> <td><code>COPYFILE_FICLONE</code></td> <td>If present, the copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.</td> </tr> <tr> <td><code>COPYFILE_FICLONE_FORCE</code></td> <td>If present, the copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error.</td> </tr> </tbody></table> <h3>File Open Constants<span><a class="mark" href="#fs_file_open_constants" id="fs_file_open_constants">#</a></span></h3> <p>The following constants are meant for use with <code>fs.open()</code>.</p> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>O_RDONLY</code></td> <td>Flag indicating to open a file for read-only access.</td> </tr> <tr> <td><code>O_WRONLY</code></td> <td>Flag indicating to open a file for write-only access.</td> </tr> <tr> <td><code>O_RDWR</code></td> <td>Flag indicating to open a file for read-write access.</td> </tr> <tr> <td><code>O_CREAT</code></td> <td>Flag indicating to create the file if it does not already exist.</td> </tr> <tr> <td><code>O_EXCL</code></td> <td>Flag indicating that opening a file should fail if the <code>O_CREAT</code> flag is set and the file already exists.</td> </tr> <tr> <td><code>O_NOCTTY</code></td> <td>Flag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one).</td> </tr> <tr> <td><code>O_TRUNC</code></td> <td>Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.</td> </tr> <tr> <td><code>O_APPEND</code></td> <td>Flag indicating that data will be appended to the end of the file.</td> </tr> <tr> <td><code>O_DIRECTORY</code></td> <td>Flag indicating that the open should fail if the path is not a directory.</td> </tr> <tr> <td><code>O_NOATIME</code></td> <td>Flag indicating reading accesses to the file system will no longer result in an update to the <code>atime</code> information associated with the file. This flag is available on Linux operating systems only.</td> </tr> <tr> <td><code>O_NOFOLLOW</code></td> <td>Flag indicating that the open should fail if the path is a symbolic link.</td> </tr> <tr> <td><code>O_SYNC</code></td> <td>Flag indicating that the file is opened for synchronized I/O with write operations waiting for file integrity.</td> </tr> <tr> <td><code>O_DSYNC</code></td> <td>Flag indicating that the file is opened for synchronized I/O with write operations waiting for data integrity.</td> </tr> <tr> <td><code>O_SYMLINK</code></td> <td>Flag indicating to open the symbolic link itself rather than the resource it is pointing to.</td> </tr> <tr> <td><code>O_DIRECT</code></td> <td>When set, an attempt will be made to minimize caching effects of file I/O.</td> </tr> <tr> <td><code>O_NONBLOCK</code></td> <td>Flag indicating to open the file in nonblocking mode when possible.</td> </tr> </tbody></table> <h3>File Type Constants<span><a class="mark" href="#fs_file_type_constants" id="fs_file_type_constants">#</a></span></h3> <p>The following constants are meant for use with the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object's <code>mode</code> property for determining a file's type.</p> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>S_IFMT</code></td> <td>Bit mask used to extract the file type code.</td> </tr> <tr> <td><code>S_IFREG</code></td> <td>File type constant for a regular file.</td> </tr> <tr> <td><code>S_IFDIR</code></td> <td>File type constant for a directory.</td> </tr> <tr> <td><code>S_IFCHR</code></td> <td>File type constant for a character-oriented device file.</td> </tr> <tr> <td><code>S_IFBLK</code></td> <td>File type constant for a block-oriented device file.</td> </tr> <tr> <td><code>S_IFIFO</code></td> <td>File type constant for a FIFO/pipe.</td> </tr> <tr> <td><code>S_IFLNK</code></td> <td>File type constant for a symbolic link.</td> </tr> <tr> <td><code>S_IFSOCK</code></td> <td>File type constant for a socket.</td> </tr> </tbody></table> <h3>File Mode Constants<span><a class="mark" href="#fs_file_mode_constants" id="fs_file_mode_constants">#</a></span></h3> <p>The following constants are meant for use with the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object's <code>mode</code> property for determining the access permissions for a file.</p> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>S_IRWXU</code></td> <td>File mode indicating readable, writable, and executable by owner.</td> </tr> <tr> <td><code>S_IRUSR</code></td> <td>File mode indicating readable by owner.</td> </tr> <tr> <td><code>S_IWUSR</code></td> <td>File mode indicating writable by owner.</td> </tr> <tr> <td><code>S_IXUSR</code></td> <td>File mode indicating executable by owner.</td> </tr> <tr> <td><code>S_IRWXG</code></td> <td>File mode indicating readable, writable, and executable by group.</td> </tr> <tr> <td><code>S_IRGRP</code></td> <td>File mode indicating readable by group.</td> </tr> <tr> <td><code>S_IWGRP</code></td> <td>File mode indicating writable by group.</td> </tr> <tr> <td><code>S_IXGRP</code></td> <td>File mode indicating executable by group.</td> </tr> <tr> <td><code>S_IRWXO</code></td> <td>File mode indicating readable, writable, and executable by others.</td> </tr> <tr> <td><code>S_IROTH</code></td> <td>File mode indicating readable by others.</td> </tr> <tr> <td><code>S_IWOTH</code></td> <td>File mode indicating writable by others.</td> </tr> <tr> <td><code>S_IXOTH</code></td> <td>File mode indicating executable by others.</td> </tr> </tbody></table> <h2>File System Flags<span><a class="mark" href="#fs_file_system_flags" id="fs_file_system_flags">#</a></span></h2> <p>The following flags are available wherever the <code>flag</code> option takes a string:</p> <ul> <li> <p><code>'a'</code> - Open file for appending. The file is created if it does not exist.</p> </li> <li> <p><code>'ax'</code> - Like <code>'a'</code> but fails if the path exists.</p> </li> <li> <p><code>'a+'</code> - Open file for reading and appending. The file is created if it does not exist.</p> </li> <li> <p><code>'ax+'</code> - Like <code>'a+'</code> but fails if the path exists.</p> </li> <li> <p><code>'as'</code> - Open file for appending in synchronous mode. The file is created if it does not exist.</p> </li> <li> <p><code>'as+'</code> - Open file for reading and appending in synchronous mode. The file is created if it does not exist.</p> </li> <li> <p><code>'r'</code> - Open file for reading. An exception occurs if the file does not exist.</p> </li> <li> <p><code>'r+'</code> - Open file for reading and writing. An exception occurs if the file does not exist.</p> </li> <li> <p><code>'rs+'</code> - Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache.</p> <p>This is primarily useful for opening files on NFS mounts as it allows skipping the potentially stale local cache. It has a very real impact on I/O performance so using this flag is not recommended unless it is needed.</p> <p>This doesn't turn <code>fs.open()</code> or <code>fsPromises.open()</code> into a synchronous blocking call. If synchronous operation is desired, something like <code>fs.openSync()</code> should be used.</p> </li> <li> <p><code>'w'</code> - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).</p> </li> <li> <p><code>'wx'</code> - Like <code>'w'</code> but fails if the path exists.</p> </li> <li> <p><code>'w+'</code> - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).</p> </li> <li> <p><code>'wx+'</code> - Like <code>'w+'</code> but fails if the path exists.</p> </li> </ul> <p><code>flag</code> can also be a number as documented by <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a>; commonly used constants are available from <code>fs.constants</code>. On Windows, flags are translated to their equivalent ones where applicable, e.g. <code>O_WRONLY</code> to <code>FILE_GENERIC_WRITE</code>, or <code>O_EXCL|O_CREAT</code> to <code>CREATE_NEW</code>, as accepted by <code>CreateFileW</code>.</p> <p>The exclusive flag <code>'x'</code> (<code>O_EXCL</code> flag in <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a>) ensures that path is newly created. On POSIX systems, path is considered to exist even if it is a symlink to a non-existent file. The exclusive flag may or may not work with network file systems.</p> <p>On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.</p> <p>Modifying a file rather than replacing it may require a flags mode of <code>'r+'</code> rather than the default mode <code>'w'</code>.</p> <p>The behavior of some flags are platform-specific. As such, opening a directory on macOS and Linux with the <code>'a+'</code> flag - see example below - will return an error. In contrast, on Windows and FreeBSD, a file descriptor or a <code>FileHandle</code> will be returned.</p> <pre><code class="language-js">// macOS and Linux fs.open('<directory>', 'a+', (err, fd) => { // => [Error: EISDIR: illegal operation on a directory, open <directory>] }); // Windows and FreeBSD fs.open('<directory>', 'a+', (err, fd) => { // => null, <fd> }); </code></pre> <p>On Windows, opening an existing hidden file using the <code>'w'</code> flag (either through <code>fs.open()</code> or <code>fs.writeFile()</code> or <code>fsPromises.open()</code>) will fail with <code>EPERM</code>. Existing hidden files can be opened for writing with the <code>'r+'</code> flag.</p> <p>A call to <code>fs.ftruncate()</code> or <code>filehandle.truncate()</code> can be used to reset the file contents.</p> <h1>Global Objects<span><a class="mark" href="#globals_global_objects" id="globals_global_objects">#</a></span></h1> <p>These objects are available in all modules. The following variables may appear to be global but are not. They exist only in the scope of modules, see the <a href="modules.html">module system documentation</a>:</p> <ul> <li><a href="#modules_dirname"><code>__dirname</code></a></li> <li><a href="#modules_filename"><code>__filename</code></a></li> <li><a href="#modules_exports"><code>exports</code></a></li> <li><a href="#modules_module"><code>module</code></a></li> <li><a href="#modules_require"><code>require()</code></a></li> </ul> <p>The objects listed here are specific to Node.js. There are a number of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects">built-in objects</a> that are part of the JavaScript language itself, which are also globally accessible.</p> <h2>Class: Buffer<span><a class="mark" href="#globals_class_buffer" id="globals_class_buffer">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.103</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Used to handle binary data. See the <a href="buffer.html">buffer section</a>.</p> <h2>__dirname<span><a class="mark" href="#globals_dirname" id="globals_dirname">#</a></span></h2> <p>This variable may appear to be global but is not. See <a href="#modules_dirname"><code>__dirname</code></a>.</p> <h2>__filename<span><a class="mark" href="#globals_filename" id="globals_filename">#</a></span></h2> <p>This variable may appear to be global but is not. See <a href="#modules_filename"><code>__filename</code></a>.</p> <h2>clearImmediate(immediateObject)<span><a class="mark" href="#globals_clearimmediate_immediateobject" id="globals_clearimmediate_immediateobject">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <p><a href="#timers_clearimmediate_immediate"><code>clearImmediate</code></a> is described in the <a href="timers.html">timers</a> section.</p> <h2>clearInterval(intervalObject)<span><a class="mark" href="#globals_clearinterval_intervalobject" id="globals_clearinterval_intervalobject">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.0.1</span> </div> <p><a href="#timers_clearinterval_timeout"><code>clearInterval</code></a> is described in the <a href="timers.html">timers</a> section.</p> <h2>clearTimeout(timeoutObject)<span><a class="mark" href="#globals_cleartimeout_timeoutobject" id="globals_cleartimeout_timeoutobject">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.0.1</span> </div> <p><a href="#timers_cleartimeout_timeout"><code>clearTimeout</code></a> is described in the <a href="timers.html">timers</a> section.</p> <h2>console<span><a class="mark" href="#globals_console" id="globals_console">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.100</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Used to print to stdout and stderr. See the <a href="console.html"><code>console</code></a> section.</p> <h2>exports<span><a class="mark" href="#globals_exports" id="globals_exports">#</a></span></h2> <p>This variable may appear to be global but is not. See <a href="#modules_exports"><code>exports</code></a>.</p> <h2>global<span><a class="mark" href="#globals_global" id="globals_global">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.27</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The global namespace object.</li> </ul> <p>In browsers, the top-level scope is the global scope. This means that within the browser <code>var something</code> will define a new global variable. In Node.js this is different. The top-level scope is not the global scope; <code>var something</code> inside a Node.js module will be local to that module.</p> <h2>module<span><a class="mark" href="#globals_module" id="globals_module">#</a></span></h2> <p>This variable may appear to be global but is not. See <a href="#modules_module"><code>module</code></a>.</p> <h2>process<span><a class="mark" href="#globals_process" id="globals_process">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.7</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The process object. See the <a href="#process_process"><code>process</code> object</a> section.</p> <h2>require()<span><a class="mark" href="#globals_require" id="globals_require">#</a></span></h2> <p>This variable may appear to be global but is not. See <a href="#modules_require"><code>require()</code></a>.</p> <h2>setImmediate(callback[, ...args])<span><a class="mark" href="#globals_setimmediate_callback_args" id="globals_setimmediate_callback_args">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <p><a href="#timers_setimmediate_callback_args"><code>setImmediate</code></a> is described in the <a href="timers.html">timers</a> section.</p> <h2>setInterval(callback, delay[, ...args])<span><a class="mark" href="#globals_setinterval_callback_delay_args" id="globals_setinterval_callback_delay_args">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.0.1</span> </div> <p><a href="#timers_setinterval_callback_delay_args"><code>setInterval</code></a> is described in the <a href="timers.html">timers</a> section.</p> <h2>setTimeout(callback, delay[, ...args])<span><a class="mark" href="#globals_settimeout_callback_delay_args" id="globals_settimeout_callback_delay_args">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.0.1</span> </div> <p><a href="#timers_settimeout_callback_delay_args"><code>setTimeout</code></a> is described in the <a href="timers.html">timers</a> section.</p> <h2>URL<span><a class="mark" href="#globals_url" id="globals_url">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>The WHATWG <code>URL</code> class. See the <a href="#url_class_url"><code>URL</code></a> section.</p> <h2>URLSearchParams<span><a class="mark" href="#globals_urlsearchparams" id="globals_urlsearchparams">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>The WHATWG <code>URLSearchParams</code> class. See the <a href="#url_class_urlsearchparams"><code>URLSearchParams</code></a> section.</p> <h2>WebAssembly<span><a class="mark" href="#globals_webassembly" id="globals_webassembly">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The object that acts as the namespace for all W3C <a href="https://webassembly.org">WebAssembly</a> related functionality. See the <a href="https://developer.mozilla.org/en-US/docs/WebAssembly">Mozilla Developer Network</a> for usage and compatibility.</p> <h1>HTTP<span><a class="mark" href="#http_http" id="http_http">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>To use the HTTP server and client one must <code>require('http')</code>.</p> <p>The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses, so the user is able to stream data.</p> <p>HTTP message headers are represented by an object like this:</p> <!-- eslint-skip --> <pre><code class="language-js">{ 'content-length': '123', 'content-type': 'text/plain', 'connection': 'keep-alive', 'host': 'mysite.com', 'accept': '*/*' } </code></pre> <p>Keys are lowercased. Values are not modified.</p> <p>In order to support the full spectrum of possible HTTP applications, Node.js's HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.</p> <p>See <a href="#http_message_headers"><code>message.headers</code></a> for details on how duplicate headers are handled.</p> <p>The raw headers as they were received are retained in the <code>rawHeaders</code> property, which is an array of <code>[key, value, key2, value2, ...]</code>. For example, the previous message header object might have a <code>rawHeaders</code> list like the following:</p> <!-- eslint-disable semi --> <pre><code class="language-js">[ 'ConTent-Length', '123456', 'content-LENGTH', '123', 'content-type', 'text/plain', 'CONNECTION', 'keep-alive', 'Host', 'mysite.com', 'accepT', '*/*' ] </code></pre> <h2>Class: http.Agent<span><a class="mark" href="#http_class_http_agent" id="http_class_http_agent">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.4</span> </div> <p>An <code>Agent</code> is responsible for managing connection persistence and reuse for HTTP clients. It maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty, at which time the socket is either destroyed or put into a pool where it is kept to be used again for requests to the same host and port. Whether it is destroyed or pooled depends on the <code>keepAlive</code> <a href="#http_new_agent_options">option</a>.</p> <p>Pooled connections have TCP Keep-Alive enabled for them, but servers may still close idle connections, in which case they will be removed from the pool and a new connection will be made when a new HTTP request is made for that host and port. Servers may also refuse to allow multiple requests over the same connection, in which case the connection will have to be remade for every request and cannot be pooled. The <code>Agent</code> will still make the requests to that server, but each one will occur over a new connection.</p> <p>When a connection is closed by the client or the server, it is removed from the pool. Any unused sockets in the pool will be unrefed so as not to keep the Node.js process running when there are no outstanding requests. (see <a href="#net_socket_unref"><code>socket.unref()</code></a>).</p> <p>It is good practice, to <a href="#http_agent_destroy"><code>destroy()</code></a> an <code>Agent</code> instance when it is no longer in use, because unused sockets consume OS resources.</p> <p>Sockets are removed from an agent when the socket emits either a <code>'close'</code> event or an <code>'agentRemove'</code> event. When intending to keep one HTTP request open for a long time without keeping it in the agent, something like the following may be done:</p> <pre><code class="language-js">http.get(options, (res) => { // Do stuff }).on('socket', (socket) => { socket.emit('agentRemove'); }); </code></pre> <p>An agent may also be used for an individual request. By providing <code>{agent: false}</code> as an option to the <code>http.get()</code> or <code>http.request()</code> functions, a one-time use <code>Agent</code> with default options will be used for the client connection.</p> <p><code>agent:false</code>:</p> <pre><code class="language-js">http.get({ hostname: 'localhost', port: 80, path: '/', agent: false // create a new agent just for this one request }, (res) => { // Do stuff with response }); </code></pre> <h3>new Agent([options])<span><a class="mark" href="#http_new_agent_options" id="http_new_agent_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.4</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Set of configurable options to set on the agent. Can have the following fields:</p> <ul> <li><code>keepAlive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with the <code>keep-alive</code> value of the <code>Connection</code> header. The <code>Connection: keep-alive</code> header is always sent when using an agent except when the <code>Connection</code> header is explicitly specified or when the <code>keepAlive</code> and <code>maxSockets</code> options are respectively set to <code>false</code> and <code>Infinity</code>, in which case <code>Connection: close</code> will be used. <strong>Default:</strong> <code>false</code>.</li> <li><code>keepAliveMsecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> When using the <code>keepAlive</code> option, specifies the <a href="#net_socket_setkeepalive_enable_initialdelay">initial delay</a> for TCP Keep-Alive packets. Ignored when the <code>keepAlive</code> option is <code>false</code> or <code>undefined</code>. <strong>Default:</strong> <code>1000</code>.</li> <li><code>maxSockets</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Maximum number of sockets to allow per host. Each request will use a new socket until the maximum is reached. <strong>Default:</strong> <code>Infinity</code>.</li> <li><code>maxFreeSockets</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Maximum number of sockets to leave open in a free state. Only relevant if <code>keepAlive</code> is set to <code>true</code>. <strong>Default:</strong> <code>256</code>.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Socket timeout in milliseconds. This will set the timeout when the socket is created.</li> </ul> </li> </ul> <p><code>options</code> in <a href="#net_socket_connect_options_connectlistener"><code>socket.connect()</code></a> are also supported.</p> <p>The default <a href="#http_http_globalagent"><code>http.globalAgent</code></a> that is used by <a href="#http_http_request_options_callback"><code>http.request()</code></a> has all of these values set to their respective defaults.</p> <p>To configure any of them, a custom <a href="#http_class_http_agent"><code>http.Agent</code></a> instance must be created.</p> <pre><code class="language-js">const http = require('http'); const keepAliveAgent = new http.Agent({ keepAlive: true }); options.agent = keepAliveAgent; http.request(options, onResponseCallback); </code></pre> <h3>agent.createConnection(options[, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/https.js#L91">[src]</a><span><a class="mark" href="#http_agent_createconnection_options_callback" id="http_agent_createconnection_options_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Options containing connection details. Check <a href="#net_net_createconnection_options_connectlistener"><code>net.createConnection()</code></a> for the format of the options</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback function that receives the created socket</li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>Produces a socket/stream to be used for HTTP requests.</p> <p>By default, this function is the same as <a href="#net_net_createconnection_options_connectlistener"><code>net.createConnection()</code></a>. However, custom agents may override this method in case greater flexibility is desired.</p> <p>A socket/stream can be supplied in one of two ways: by returning the socket/stream from this function, or by passing the socket/stream to <code>callback</code>.</p> <p><code>callback</code> has a signature of <code>(err, stream)</code>.</p> <h3>agent.keepSocketAlive(socket)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/_http_agent.js#L316">[src]</a><span><a class="mark" href="#http_agent_keepsocketalive_socket" id="http_agent_keepsocketalive_socket">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.1.0</span> </div> <ul> <li><code>socket</code> <a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>Called when <code>socket</code> is detached from a request and could be persisted by the <code>Agent</code>. Default behavior is to:</p> <pre><code class="language-js">socket.setKeepAlive(true, this.keepAliveMsecs); socket.unref(); return true; </code></pre> <p>This method can be overridden by a particular <code>Agent</code> subclass. If this method returns a falsy value, the socket will be destroyed instead of persisting it for use with the next request.</p> <h3>agent.reuseSocket(socket, request)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/_http_agent.js#L323">[src]</a><span><a class="mark" href="#http_agent_reusesocket_socket_request" id="http_agent_reusesocket_socket_request">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.1.0</span> </div> <ul> <li><code>socket</code> <a href="#net_class_net_socket" class="type"><net.Socket></a></li> <li><code>request</code> <a href="#http_class_http_clientrequest" class="type"><http.ClientRequest></a></li> </ul> <p>Called when <code>socket</code> is attached to <code>request</code> after being persisted because of the keep-alive options. Default behavior is to:</p> <pre><code class="language-js">socket.ref(); </code></pre> <p>This method can be overridden by a particular <code>Agent</code> subclass.</p> <h3>agent.destroy()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/_http_agent.js#L328">[src]</a><span><a class="mark" href="#http_agent_destroy" id="http_agent_destroy">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <p>Destroy any sockets that are currently in use by the agent.</p> <p>It is usually not necessary to do this. However, if using an agent with <code>keepAlive</code> enabled, then it is best to explicitly shut down the agent when it will no longer be used. Otherwise, sockets may hang open for quite a long time before the server terminates them.</p> <h3>agent.freeSockets<span><a class="mark" href="#http_agent_freesockets" id="http_agent_freesockets">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>An object which contains arrays of sockets currently awaiting use by the agent when <code>keepAlive</code> is enabled. Do not modify.</p> <h3>agent.getName(options)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/https.js#L156">[src]</a><span><a class="mark" href="#http_agent_getname_options" id="http_agent_getname_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A set of options providing information for name generation</p> <ul> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A domain name or IP address of the server to issue the request to</li> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port of remote server</li> <li><code>localAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Local interface to bind for network connections when issuing the request</li> <li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Must be 4 or 6 if this doesn't equal <code>undefined</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Get a unique name for a set of request options, to determine whether a connection can be reused. For an HTTP agent, this returns <code>host:port:localAddress</code> or <code>host:port:localAddress:family</code>. For an HTTPS agent, the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options that determine socket reusability.</p> <h3>agent.maxFreeSockets<span><a class="mark" href="#http_agent_maxfreesockets" id="http_agent_maxfreesockets">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.7</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>By default set to 256. For agents with <code>keepAlive</code> enabled, this sets the maximum number of sockets that will be left open in the free state.</p> <h3>agent.maxSockets<span><a class="mark" href="#http_agent_maxsockets" id="http_agent_maxsockets">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.6</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>By default set to <code>Infinity</code>. Determines how many concurrent sockets the agent can have open per origin. Origin is the returned value of <a href="#http_agent_getname_options"><code>agent.getName()</code></a>.</p> <h3>agent.requests<span><a class="mark" href="#http_agent_requests" id="http_agent_requests">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.</p> <h3>agent.sockets<span><a class="mark" href="#http_agent_sockets" id="http_agent_sockets">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.6</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>An object which contains arrays of sockets currently in use by the agent. Do not modify.</p> <h2>Class: http.ClientRequest<span><a class="mark" href="#http_class_http_clientrequest" id="http_class_http_clientrequest">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <p>This object is created internally and returned from <a href="#http_http_request_options_callback"><code>http.request()</code></a>. It represents an <em>in-progress</em> request whose header has already been queued. The header is still mutable using the <a href="#http_request_setheader_name_value"><code>setHeader(name, value)</code></a>, <a href="#http_request_getheader_name"><code>getHeader(name)</code></a>, <a href="#http_request_removeheader_name"><code>removeHeader(name)</code></a> API. The actual header will be sent along with the first data chunk or when calling <a href="#http_request_end_data_encoding_callback"><code>request.end()</code></a>.</p> <p>To get the response, add a listener for <a href="#http_event_response"><code>'response'</code></a> to the request object. <a href="#http_event_response"><code>'response'</code></a> will be emitted from the request object when the response headers have been received. The <a href="#http_event_response"><code>'response'</code></a> event is executed with one argument which is an instance of <a href="#http_class_http_incomingmessage"><code>http.IncomingMessage</code></a>.</p> <p>During the <a href="#http_event_response"><code>'response'</code></a> event, one can add listeners to the response object; particularly to listen for the <code>'data'</code> event.</p> <p>If no <a href="#http_event_response"><code>'response'</code></a> handler is added, then the response will be entirely discarded. However, if a <a href="#http_event_response"><code>'response'</code></a> event handler is added, then the data from the response object <strong>must</strong> be consumed, either by calling <code>response.read()</code> whenever there is a <code>'readable'</code> event, or by adding a <code>'data'</code> handler, or by calling the <code>.resume()</code> method. Until the data is consumed, the <code>'end'</code> event will not fire. Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error.</p> <p>Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not.</p> <p>The request inherits from <a href="#stream_stream">Stream</a>, and additionally implements the following:</p> <h3>Event: 'abort'<span><a class="mark" href="#http_event_abort" id="http_event_abort">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.4.1</span> </div> <p>Emitted when the request has been aborted by the client. This event is only emitted on the first call to <code>abort()</code>.</p> <h3>Event: 'connect'<span><a class="mark" href="#http_event_connect" id="http_event_connect">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>response</code> <a href="#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> <li><code>socket</code> <a href="#net_class_net_socket" class="type"><net.Socket></a></li> <li><code>head</code> <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Emitted each time a server responds to a request with a <code>CONNECT</code> method. If this event is not being listened for, clients receiving a <code>CONNECT</code> method will have their connections closed.</p> <p>A client and server pair demonstrating how to listen for the <code>'connect'</code> event:</p> <pre><code class="language-js">const http = require('http'); const net = require('net'); const url = require('url'); // Create an HTTP tunneling proxy const proxy = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('okay'); }); proxy.on('connect', (req, cltSocket, head) => { // connect to an origin server const srvUrl = url.parse(`http://${req.url}`); const srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => { cltSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-Proxy\r\n' + '\r\n'); srvSocket.write(head); srvSocket.pipe(cltSocket); cltSocket.pipe(srvSocket); }); }); // now that proxy is running proxy.listen(1337, '127.0.0.1', () => { // make a request to a tunneling proxy const options = { port: 1337, host: '127.0.0.1', method: 'CONNECT', path: 'www.google.com:80' }; const req = http.request(options); req.end(); req.on('connect', (res, socket, head) => { console.log('got connected!'); // make a request over an HTTP tunnel socket.write('GET / HTTP/1.1\r\n' + 'Host: www.google.com:80\r\n' + 'Connection: close\r\n' + '\r\n'); socket.on('data', (chunk) => { console.log(chunk.toString()); }); socket.on('end', () => { proxy.close(); }); }); }); </code></pre> <h3>Event: 'continue'<span><a class="mark" href="#http_event_continue" id="http_event_continue">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.2</span> </div> <p>Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.</p> <h3>Event: 'information'<span><a class="mark" href="#http_event_information" id="http_event_information">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>Emitted when the server sends a 1xx response (excluding 101 Upgrade). This event is emitted with a callback containing an object with a status code.</p> <pre><code class="language-js">const http = require('http'); const options = { host: '127.0.0.1', port: 8080, path: '/length_request' }; // Make a request const req = http.request(options); req.end(); req.on('information', (res) => { console.log(`Got information prior to main response: ${res.statusCode}`); }); </code></pre> <p>101 Upgrade statuses do not fire this event due to their break from the traditional HTTP request/response chain, such as web sockets, in-place TLS upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the <a href="#http_event_upgrade"><code>'upgrade'</code></a> event instead.</p> <h3>Event: 'response'<span><a class="mark" href="#http_event_response" id="http_event_response">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.0</span> </div> <ul> <li><code>response</code> <a href="#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> </ul> <p>Emitted when a response is received to this request. This event is emitted only once.</p> <h3>Event: 'socket'<span><a class="mark" href="#http_event_socket" id="http_event_socket">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.3</span> </div> <ul> <li><code>socket</code> <a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>Emitted after a socket is assigned to this request.</p> <h3>Event: 'timeout'<span><a class="mark" href="#http_event_timeout" id="http_event_timeout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.8</span> </div> <p>Emitted when the underlying socket times out from inactivity. This only notifies that the socket has been idle. The request must be aborted manually.</p> <p>See also: <a href="#http_request_settimeout_timeout_callback"><code>request.setTimeout()</code></a>.</p> <h3>Event: 'upgrade'<span><a class="mark" href="#http_event_upgrade" id="http_event_upgrade">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.94</span> </div> <ul> <li><code>response</code> <a href="#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> <li><code>socket</code> <a href="#net_class_net_socket" class="type"><net.Socket></a></li> <li><code>head</code> <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Emitted each time a server responds to a request with an upgrade. If this event is not being listened for and the response status code is 101 Switching Protocols, clients receiving an upgrade header will have their connections closed.</p> <p>A client server pair demonstrating how to listen for the <code>'upgrade'</code> event.</p> <pre><code class="language-js">const http = require('http'); // Create an HTTP server const srv = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('okay'); }); srv.on('upgrade', (req, socket, head) => { socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' + 'Upgrade: WebSocket\r\n' + 'Connection: Upgrade\r\n' + '\r\n'); socket.pipe(socket); // echo back }); // now that server is running srv.listen(1337, '127.0.0.1', () => { // make a request const options = { port: 1337, host: '127.0.0.1', headers: { 'Connection': 'Upgrade', 'Upgrade': 'websocket' } }; const req = http.request(options); req.end(); req.on('upgrade', (res, socket, upgradeHead) => { console.log('got upgraded!'); socket.end(); process.exit(0); }); }); </code></pre> <h3>request.abort()<span><a class="mark" href="#http_request_abort" id="http_request_abort">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.8</span> </div> <p>Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.</p> <h3>request.aborted<span><a class="mark" href="#http_request_aborted" id="http_request_aborted">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <p>If a request has been aborted, this value is the time when the request was aborted, in milliseconds since 1 January 1970 00:00:00 UTC.</p> <h3>request.connection<span><a class="mark" href="#http_request_connection" id="http_request_connection">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>See <a href="#http_request_socket"><code>request.socket</code></a>.</p> <h3>request.end([data[, encoding]][, callback])<span><a class="mark" href="#http_request_end_data_encoding_callback" id="http_request_end_data_encoding_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>This method now returns a reference to <code>ClientRequest</code>.</p></td></tr> <tr><td>v0.1.90</td> <td><p><span>Added in: v0.1.90</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream. If the request is chunked, this will send the terminating <code>'0\r\n\r\n'</code>.</p> <p>If <code>data</code> is specified, it is equivalent to calling <a href="#http_request_write_chunk_encoding_callback"><code>request.write(data, encoding)</code></a> followed by <code>request.end(callback)</code>.</p> <p>If <code>callback</code> is specified, it will be called when the request stream is finished.</p> <h3>request.finished<span><a class="mark" href="#http_request_finished" id="http_request_finished">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.0.1</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>request.finished</code> property will be <code>true</code> if <a href="#http_request_end_data_encoding_callback"><code>request.end()</code></a> has been called. <code>request.end()</code> will automatically be called if the request was initiated via <a href="#http_http_get_options_callback"><code>http.get()</code></a>.</p> <h3>request.flushHeaders()<span><a class="mark" href="#http_request_flushheaders" id="http_request_flushheaders">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.6.0</span> </div> <p>Flush the request headers.</p> <p>For efficiency reasons, Node.js normally buffers the request headers until <code>request.end()</code> is called or the first chunk of request data is written. It then tries to pack the request headers and data into a single TCP packet.</p> <p>That's usually desired (it saves a TCP round-trip), but not when the first data is not sent until possibly much later. <code>request.flushHeaders()</code> bypasses the optimization and kickstarts the request.</p> <h3>request.getHeader(name)<span><a class="mark" href="#http_request_getheader_name" id="http_request_getheader_name">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.6.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Reads out a header on the request. Note that the name is case insensitive. The type of the return value depends on the arguments provided to <a href="#http_request_setheader_name_value"><code>request.setHeader()</code></a>.</p> <pre><code class="language-js">request.setHeader('content-type', 'text/html'); request.setHeader('Content-Length', Buffer.byteLength(body)); request.setHeader('Cookie', ['type=ninja', 'language=javascript']); const contentType = request.getHeader('Content-Type'); // contentType is 'text/html' const contentLength = request.getHeader('Content-Length'); // contentLength is of type number const cookie = request.getHeader('Cookie'); // cookie is of type string[] </code></pre> <h3>request.maxHeadersCount<span><a class="mark" href="#http_request_maxheaderscount" id="http_request_maxheaderscount">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>2000</code></li> </ul> <p>Limits maximum response headers count. If set to 0, no limit will be applied.</p> <h3>request.removeHeader(name)<span><a class="mark" href="#http_request_removeheader_name" id="http_request_removeheader_name">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.6.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Removes a header that's already defined into headers object.</p> <pre><code class="language-js">request.removeHeader('Content-Type'); </code></pre> <h3>request.setHeader(name, value)<span><a class="mark" href="#http_request_setheader_name_value" id="http_request_setheader_name_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.6.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Sets a single header value for headers object. If this header already exists 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. Non-string values will be stored without modification. Therefore, <a href="#http_request_getheader_name"><code>request.getHeader()</code></a> may return non-string values. However, the non-string values will be converted to strings for network transmission.</p> <pre><code class="language-js">request.setHeader('Content-Type', 'application/json'); </code></pre> <p>or</p> <pre><code class="language-js">request.setHeader('Cookie', ['type=ninja', 'language=javascript']); </code></pre> <h3>request.setNoDelay([noDelay])<span><a class="mark" href="#http_request_setnodelay_nodelay" id="http_request_setnodelay_nodelay">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><code>noDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Once a socket is assigned to this request and is connected <a href="#net_socket_setnodelay_nodelay"><code>socket.setNoDelay()</code></a> will be called.</p> <h3>request.setSocketKeepAlive([enable][, initialdelay])<span><a class="mark" href="#http_request_setsocketkeepalive_enable_initialdelay" id="http_request_setsocketkeepalive_enable_initialdelay">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><code>enable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> <li><code>initialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Once a socket is assigned to this request and is connected <a href="#net_socket_setkeepalive_enable_initialdelay"><code>socket.setKeepAlive()</code></a> will be called.</p> <h3>request.setTimeout(timeout[, callback])<span><a class="mark" href="#http_request_settimeout_timeout_callback" id="http_request_settimeout_timeout_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Consistently set socket timeout only when the socket connects.</p></td></tr> <tr><td>v0.5.9</td> <td><p><span>Added in: v0.5.9</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Milliseconds before a request times out.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional function to be called when a timeout occurs. Same as binding to the <code>'timeout'</code> event.</li> <li>Returns: <a href="#http_class_http_clientrequest" class="type"><http.ClientRequest></a></li> </ul> <p>Once a socket is assigned to this request and is connected <a href="#net_socket_settimeout_timeout_callback"><code>socket.setTimeout()</code></a> will be called.</p> <h3>request.socket<span><a class="mark" href="#http_request_socket" id="http_request_socket">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>Reference to the underlying socket. Usually users will not want to access this property. In particular, the socket will not emit <code>'readable'</code> events because of how the protocol parser attaches to the socket. The <code>socket</code> may also be accessed via <code>request.connection</code>.</p> <pre><code class="language-js">const http = require('http'); const options = { host: 'www.google.com', }; const req = http.get(options); req.end(); req.once('response', (res) => { const ip = req.socket.localAddress; const port = req.socket.localPort; console.log(`Your IP address is ${ip} and your source port is ${port}.`); // consume response object }); </code></pre> <h3>request.write(chunk[, encoding][, callback])<span><a class="mark" href="#http_request_write_chunk_encoding_callback" id="http_request_write_chunk_encoding_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.29</span> </div> <ul> <li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Sends a chunk of the body. By calling this method many times, a request body can be sent to a server. In that case, it is suggested to use the <code>['Transfer-Encoding', 'chunked']</code> header line when creating the request.</p> <p>The <code>encoding</code> argument is optional and only applies when <code>chunk</code> is a string. Defaults to <code>'utf8'</code>.</p> <p>The <code>callback</code> argument is optional and will be called when this chunk of data is flushed, but only if the chunk is non-empty.</p> <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel buffer. Returns <code>false</code> if all or part of the data was queued in user memory. <code>'drain'</code> will be emitted when the buffer is free again.</p> <p>When <code>write</code> function is called with empty string or buffer, it does nothing and waits for more input.</p> <h2>Class: http.Server<span><a class="mark" href="#http_class_http_server" id="http_class_http_server">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <p>This class inherits from <a href="#net_class_net_server"><code>net.Server</code></a> and has the following additional events:</p> <h3>Event: 'checkContinue'<span><a class="mark" href="#http_event_checkcontinue" id="http_event_checkcontinue">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>request</code> <a href="#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> <li><code>response</code> <a href="#http_class_http_serverresponse" class="type"><http.ServerResponse></a></li> </ul> <p>Emitted each time a request with an HTTP <code>Expect: 100-continue</code> is received. If this event is not listened for, the server will automatically respond with a <code>100 Continue</code> as appropriate.</p> <p>Handling this event involves calling <a href="#http_response_writecontinue"><code>response.writeContinue()</code></a> if the client should continue to send the request body, or generating an appropriate HTTP response (e.g. 400 Bad Request) if the client should not continue to send the request body.</p> <p>Note that when this event is emitted and handled, the <a href="#http_event_request"><code>'request'</code></a> event will not be emitted.</p> <h3>Event: 'checkExpectation'<span><a class="mark" href="#http_event_checkexpectation" id="http_event_checkexpectation">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.5.0</span> </div> <ul> <li><code>request</code> <a href="#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> <li><code>response</code> <a href="#http_class_http_serverresponse" class="type"><http.ServerResponse></a></li> </ul> <p>Emitted each time a request with an HTTP <code>Expect</code> header is received, where the value is not <code>100-continue</code>. If this event is not listened for, the server will automatically respond with a <code>417 Expectation Failed</code> as appropriate.</p> <p>Note that when this event is emitted and handled, the <a href="#http_event_request"><code>'request'</code></a> event will not be emitted.</p> <h3>Event: 'clientError'<span><a class="mark" href="#http_event_clienterror" id="http_event_clienterror">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>rawPacket</code> is the current buffer that just parsed. Adding this buffer to the error object of <code>'clientError'</code> event is to make it possible that developers can log the broken packet.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The default action of calling <code>.destroy()</code> on the <code>socket</code> will no longer take place if there are listeners attached for <code>'clientError'</code>.</p></td></tr> <tr><td>v0.1.94</td> <td><p><span>Added in: v0.1.94</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>exception</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>socket</code> <a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>If a client connection emits an <code>'error'</code> event, it will be forwarded here. Listener of this event is responsible for closing/destroying the underlying socket. For example, one may wish to more gracefully close the socket with a custom HTTP response instead of abruptly severing the connection.</p> <p>Default behavior is to close the socket with an HTTP '400 Bad Request' response if possible, otherwise the socket is immediately destroyed.</p> <p><code>socket</code> is the <a href="#net_class_net_socket"><code>net.Socket</code></a> object that the error originated from.</p> <pre><code class="language-js">const http = require('http'); const server = http.createServer((req, res) => { res.end(); }); server.on('clientError', (err, socket) => { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); }); server.listen(8000); </code></pre> <p>When the <code>'clientError'</code> event occurs, there is no <code>request</code> or <code>response</code> object, so any HTTP response sent, including response headers and payload, <em>must</em> be written directly to the <code>socket</code> object. Care must be taken to ensure the response is a properly formatted HTTP response message.</p> <p><code>err</code> is an instance of <code>Error</code> with two extra columns:</p> <ul> <li><code>bytesParsed</code>: the bytes count of request packet that Node.js may have parsed correctly;</li> <li><code>rawPacket</code>: the raw packet of current request.</li> </ul> <h3>Event: 'close'<span><a class="mark" href="#http_event_close" id="http_event_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.4</span> </div> <p>Emitted when the server closes.</p> <h3>Event: 'connect'<span><a class="mark" href="#http_event_connect_1" id="http_event_connect_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>request</code> <a href="#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Arguments for the HTTP request, as it is in the <a href="#http_event_request"><code>'request'</code></a> event</li> <li><code>socket</code> <a href="#net_class_net_socket" class="type"><net.Socket></a> Network socket between the server and client</li> <li><code>head</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> The first packet of the tunneling stream (may be empty)</li> </ul> <p>Emitted each time a client requests an HTTP <code>CONNECT</code> method. If this event is not listened for, then clients requesting a <code>CONNECT</code> method will have their connections closed.</p> <p>After this event is emitted, the request's socket will not have a <code>'data'</code> event listener, meaning it will need to be bound in order to handle data sent to the server on that socket.</p> <h3>Event: 'connection'<span><a class="mark" href="#http_event_connection" id="http_event_connection">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.0</span> </div> <ul> <li><code>socket</code> <a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>This event is emitted when a new TCP stream is established. <code>socket</code> is typically an object of type <a href="#net_class_net_socket"><code>net.Socket</code></a>. Usually users will not want to access this event. In particular, the socket will not emit <code>'readable'</code> events because of how the protocol parser attaches to the socket. The <code>socket</code> can also be accessed at <code>request.connection</code>.</p> <p>This event can also be explicitly emitted by users to inject connections into the HTTP server. In that case, any <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream can be passed.</p> <h3>Event: 'request'<span><a class="mark" href="#http_event_request" id="http_event_request">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.0</span> </div> <ul> <li><code>request</code> <a href="#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> <li><code>response</code> <a href="#http_class_http_serverresponse" class="type"><http.ServerResponse></a></li> </ul> <p>Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of HTTP Keep-Alive connections).</p> <h3>Event: 'upgrade'<span><a class="mark" href="#http_event_upgrade_1" id="http_event_upgrade_1">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Not listening to this event no longer causes the socket to be destroyed if a client sends an Upgrade header.</p></td></tr> <tr><td>v0.1.94</td> <td><p><span>Added in: v0.1.94</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>request</code> <a href="#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Arguments for the HTTP request, as it is in the <a href="#http_event_request"><code>'request'</code></a> event</li> <li><code>socket</code> <a href="#net_class_net_socket" class="type"><net.Socket></a> Network socket between the server and client</li> <li><code>head</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> The first packet of the upgraded stream (may be empty)</li> </ul> <p>Emitted each time a client requests an HTTP upgrade. Listening to this event is optional and clients cannot insist on a protocol change.</p> <p>After this event is emitted, the request's socket will not have a <code>'data'</code> event listener, meaning it will need to be bound in order to handle data sent to the server on that socket.</p> <h3>server.close([callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1562">[src]</a><span><a class="mark" href="#http_server_close_callback" id="http_server_close_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Stops the server from accepting new connections. See <a href="#net_server_close_callback"><code>net.Server.close()</code></a>.</p> <h3><code>server.listen()</code><span><a class="mark" href="#http_server_listen" id="http_server_listen">#</a></span></h3> <p>Starts the HTTP server listening for connections. This method is identical to <a href="#net_server_listen"><code>server.listen()</code></a> from <a href="#net_class_net_server"><code>net.Server</code></a>.</p> <h3>server.listening<span><a class="mark" href="#http_server_listening" id="http_server_listening">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.7.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether or not the server is listening for connections.</li> </ul> <h3>server.maxHeadersCount<span><a class="mark" href="#http_server_maxheaderscount" id="http_server_maxheaderscount">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>2000</code></li> </ul> <p>Limits maximum incoming headers count. If set to 0, no limit will be applied.</p> <h3>server.headersTimeout<span><a class="mark" href="#http_server_headerstimeout" id="http_server_headerstimeout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.14.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>40000</code></li> </ul> <p>Limit the amount of time the parser will wait to receive the complete HTTP headers.</p> <p>In case of inactivity, the rules defined in [server.timeout][] apply. However, that inactivity based timeout would still allow the connection to be kept open if the headers are being sent very slowly (by default, up to a byte per 2 minutes). In order to prevent this, whenever header data arrives an additional check is made that more than <code>server.headersTimeout</code> milliseconds has not passed since the connection was established. If the check fails, a <code>'timeout'</code> event is emitted on the server object, and (by default) the socket is destroyed. See [server.timeout][] for more information on how timeout behaviour can be customised.</p> <p>A value of <code>0</code> will disable the HTTP headers timeout check.</p> <h3>server.setTimeout([msecs][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/_http_server.js#L323">[src]</a><span><a class="mark" href="#http_server_settimeout_msecs_callback" id="http_server_settimeout_msecs_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.12</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#http_class_http_server" class="type"><http.Server></a></li> </ul> <p>Sets the timeout value for sockets, and emits a <code>'timeout'</code> event on the Server object, passing the socket as an argument, if a timeout occurs.</p> <p>If there is a <code>'timeout'</code> event listener on the Server object, then it will be called with the timed-out socket as an argument.</p> <p>By default, the Server's timeout value is 2 minutes, and sockets are destroyed automatically if they time out. However, if a callback is assigned to the Server's <code>'timeout'</code> event, timeouts must be handled explicitly.</p> <h3>server.timeout<span><a class="mark" href="#http_server_timeout" id="http_server_timeout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.12</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Timeout in milliseconds. <strong>Default:</strong> <code>120000</code> (2 minutes).</li> </ul> <p>The number of milliseconds of inactivity before a socket is presumed to have timed out.</p> <p>A value of <code>0</code> will disable the timeout behavior on incoming connections.</p> <p>The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.</p> <h3>server.keepAliveTimeout<span><a class="mark" href="#http_server_keepalivetimeout" id="http_server_keepalivetimeout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Timeout in milliseconds. <strong>Default:</strong> <code>5000</code> (5 seconds).</li> </ul> <p>The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed. If the server receives new data before the keep-alive timeout has fired, it will reset the regular inactivity timeout, i.e., <a href="#http_server_timeout"><code>server.timeout</code></a>.</p> <p>A value of <code>0</code> will disable the keep-alive timeout behavior on incoming connections. A value of <code>0</code> makes the http server behave similarly to Node.js versions prior to 8.0.0, which did not have a keep-alive timeout.</p> <p>The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.</p> <h2>Class: http.ServerResponse<span><a class="mark" href="#http_class_http_serverresponse" id="http_class_http_serverresponse">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <p>This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the <a href="#http_event_request"><code>'request'</code></a> event.</p> <p>The response inherits from <a href="#stream_stream">Stream</a>, and additionally implements the following:</p> <h3>Event: 'close'<span><a class="mark" href="#http_event_close_1" id="http_event_close_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.6.7</span> </div> <p>Indicates that the underlying connection was terminated before <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> was called or able to flush.</p> <h3>Event: 'finish'<span><a class="mark" href="#http_event_finish" id="http_event_finish">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.6</span> </div> <p>Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the operating system for transmission over the network. It does not imply that the client has received anything yet.</p> <h3>response.addTrailers(headers)<span><a class="mark" href="#http_response_addtrailers_headers" id="http_response_addtrailers_headers">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>This method adds HTTP trailing headers (a header but at the end of the message) to the response.</p> <p>Trailers will <strong>only</strong> be emitted if chunked encoding is used for the response; if it is not (e.g. if the request was HTTP/1.0), they will be silently discarded.</p> <p>Note that HTTP requires the <code>Trailer</code> header to be sent in order to emit trailers, with a list of the header fields in its value. E.g.,</p> <pre><code class="language-js">response.writeHead(200, { 'Content-Type': 'text/plain', 'Trailer': 'Content-MD5' }); response.write(fileData); response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); response.end(); </code></pre> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <h3>response.connection<span><a class="mark" href="#http_response_connection" id="http_response_connection">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>See <a href="#http_response_socket"><code>response.socket</code></a>.</p> <h3>response.end([data][, encoding][, callback])<span><a class="mark" href="#http_response_end_data_encoding_callback" id="http_response_end_data_encoding_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>This method now returns a reference to <code>ServerResponse</code>.</p></td></tr> <tr><td>v0.1.90</td> <td><p><span>Added in: v0.1.90</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, <code>response.end()</code>, MUST be called on each response.</p> <p>If <code>data</code> is specified, it is similar in effect to calling <a href="#http_response_write_chunk_encoding_callback"><code>response.write(data, encoding)</code></a> followed by <code>response.end(callback)</code>.</p> <p>If <code>callback</code> is specified, it will be called when the response stream is finished.</p> <h3>response.finished<span><a class="mark" href="#http_response_finished" id="http_response_finished">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.0.2</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Boolean value that indicates whether the response has completed. Starts as <code>false</code>. After <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> executes, the value will be <code>true</code>.</p> <h3>response.getHeader(name)<span><a class="mark" href="#http_response_getheader_name" id="http_response_getheader_name">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive. The type of the return value depends on the arguments provided to <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a>.</p> <pre><code class="language-js">response.setHeader('Content-Type', 'text/html'); response.setHeader('Content-Length', Buffer.byteLength(body)); response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); const contentType = response.getHeader('content-type'); // contentType is 'text/html' const contentLength = response.getHeader('Content-Length'); // contentLength is of type number const setCookie = response.getHeader('set-cookie'); // setCookie is of type string[] </code></pre> <h3>response.getHeaderNames()<span><a class="mark" href="#http_response_getheadernames" id="http_response_getheadernames">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.7.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Returns an array containing the unique names of the current outgoing headers. All header names are lowercase.</p> <pre><code class="language-js">response.setHeader('Foo', 'bar'); response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); const headerNames = response.getHeaderNames(); // headerNames === ['foo', 'set-cookie'] </code></pre> <h3>response.getHeaders()<span><a class="mark" href="#http_response_getheaders" id="http_response_getheaders">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.7.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related http module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.</p> <p>The object returned by the <code>response.getHeaders()</code> method <em>does not</em> prototypically inherit from the JavaScript <code>Object</code>. This means that typical <code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others are not defined and <em>will not work</em>.</p> <pre><code class="language-js">response.setHeader('Foo', 'bar'); response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); const headers = response.getHeaders(); // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } </code></pre> <h3>response.hasHeader(name)<span><a class="mark" href="#http_response_hasheader_name" id="http_response_hasheader_name">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.7.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the header identified by <code>name</code> is currently set in the outgoing headers. Note that the header name matching is case-insensitive.</p> <pre><code class="language-js">const hasContentType = response.hasHeader('content-type'); </code></pre> <h3>response.headersSent<span><a class="mark" href="#http_response_headerssent" id="http_response_headerssent">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.3</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Boolean (read-only). True if headers were sent, false otherwise.</p> <h3>response.removeHeader(name)<span><a class="mark" href="#http_response_removeheader_name" id="http_response_removeheader_name">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Removes a header that's queued for implicit sending.</p> <pre><code class="language-js">response.removeHeader('Content-Encoding'); </code></pre> <h3>response.sendDate<span><a class="mark" href="#http_response_senddate" id="http_response_senddate">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.5</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.</p> <p>This should only be disabled for testing; HTTP requires the Date header in responses.</p> <h3>response.setHeader(name, value)<span><a class="mark" href="#http_response_setheader_name_value" id="http_response_setheader_name_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Sets a single header value for implicit headers. If this header already exists 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. Non-string values will be stored without modification. Therefore, <a href="#http_response_getheader_name"><code>response.getHeader()</code></a> may return non-string values. However, the non-string values will be converted to strings for network transmission.</p> <pre><code class="language-js">response.setHeader('Content-Type', 'text/html'); </code></pre> <p>or</p> <pre><code class="language-js">response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); </code></pre> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <p>When headers have been set with <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged with any headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p> <pre><code class="language-js">// returns content-type = text/plain const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); }); </code></pre> <p>If <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> method is called and this method has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the <a href="#http_response_getheader_name"><code>response.getHeader()</code></a> on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a> instead of <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>.</p> <h3>response.setTimeout(msecs[, callback])<span><a class="mark" href="#http_response_settimeout_msecs_callback" id="http_response_settimeout_msecs_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.12</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#http_class_http_serverresponse" class="type"><http.ServerResponse></a></li> </ul> <p>Sets the Socket's timeout value to <code>msecs</code>. If a callback is provided, then it is added as a listener on the <code>'timeout'</code> event on the response object.</p> <p>If no <code>'timeout'</code> listener is added to the request, the response, or the server, then sockets are destroyed when they time out. If a handler is assigned to the request, the response, or the server's <code>'timeout'</code> events, timed out sockets must be handled explicitly.</p> <h3>response.socket<span><a class="mark" href="#http_response_socket" id="http_response_socket">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>Reference to the underlying socket. Usually users will not want to access this property. In particular, the socket will not emit <code>'readable'</code> events because of how the protocol parser attaches to the socket. After <code>response.end()</code>, the property is nulled. The <code>socket</code> may also be accessed via <code>response.connection</code>.</p> <pre><code class="language-js">const http = require('http'); const server = http.createServer((req, res) => { const ip = res.socket.remoteAddress; const port = res.socket.remotePort; res.end(`Your IP address is ${ip} and your source port is ${port}.`); }).listen(3000); </code></pre> <h3>response.statusCode<span><a class="mark" href="#http_response_statuscode" id="http_response_statuscode">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>When using implicit headers (not calling <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> explicitly), this property controls the status code that will be sent to the client when the headers get flushed.</p> <pre><code class="language-js">response.statusCode = 404; </code></pre> <p>After response header was sent to the client, this property indicates the status code which was sent out.</p> <h3>response.statusMessage<span><a class="mark" href="#http_response_statusmessage" id="http_response_statusmessage">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.8</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>When using implicit headers (not calling <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> explicitly), this property controls the status message that will be sent to the client when the headers get flushed. If this is left as <code>undefined</code> then the standard message for the status code will be used.</p> <pre><code class="language-js">response.statusMessage = 'Not found'; </code></pre> <p>After response header was sent to the client, this property indicates the status message which was sent out.</p> <h3>response.write(chunk[, encoding][, callback])<span><a class="mark" href="#http_response_write_chunk_encoding_callback" id="http_response_write_chunk_encoding_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.29</span> </div> <ul> <li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <strong>Default:</strong> <code>'utf8'</code></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>If this method is called and <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> has not been called, it will switch to implicit header mode and flush the implicit headers.</p> <p>This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.</p> <p>Note that in the <code>http</code> module, the response body is omitted when the request is a HEAD request. Similarly, the <code>204</code> and <code>304</code> responses <em>must not</em> include a message body.</p> <p><code>chunk</code> can be a string or a buffer. If <code>chunk</code> is a string, the second parameter specifies how to encode it into a byte stream. <code>callback</code> will be called when this chunk of data is flushed.</p> <p>This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.</p> <p>The first time <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, it will send the buffered header information and the first chunk of the body to the client. The second time <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, Node.js assumes data will be streamed, and sends the new data separately. That is, the response is buffered up to the first chunk of the body.</p> <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel buffer. Returns <code>false</code> if all or part of the data was queued in user memory. <code>'drain'</code> will be emitted when the buffer is free again.</p> <h3>response.writeContinue()<span><a class="mark" href="#http_response_writecontinue" id="http_response_writecontinue">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <p>Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the <a href="#http_event_checkcontinue"><code>'checkContinue'</code></a> event on <code>Server</code>.</p> <h3>response.writeHead(statusCode[, statusMessage][, headers])<span><a class="mark" href="#http_response_writehead_statuscode_statusmessage_headers" id="http_response_writehead_statuscode_statusmessage_headers">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.17.0</td> <td><p>Return <code>this</code> from <code>writeHead()</code> to allow chaining with <code>end()</code>.</p></td></tr> <tr><td>v5.11.0, v4.4.5</td> <td><p>A <code>RangeError</code> is thrown if <code>statusCode</code> is not a number in the range <code>[100, 999]</code>.</p></td></tr> <tr><td>v0.1.30</td> <td><p><span>Added in: v0.1.30</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>statusMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li>Returns: <a href="#http_class_http_serverresponse" class="type"><http.ServerResponse></a></li> </ul> <p>Sends a response header to the request. The status code is a 3-digit HTTP status code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers. Optionally one can give a human-readable <code>statusMessage</code> as the second argument.</p> <p>Returns a reference to the <code>ServerResponse</code>, so that calls can be chained.</p> <pre><code class="language-js">const body = 'hello world'; response .writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/plain' }) .end(body); </code></pre> <p>This method must only be called once on a message and it must be called before <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> is called.</p> <p>If <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> or <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> are called before calling this, the implicit/mutable headers will be calculated and call this function.</p> <p>When headers have been set with <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged with any headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p> <p>If this method is called and <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a> has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the <a href="#http_response_getheader_name"><code>response.getHeader()</code></a> on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a> instead.</p> <pre><code class="language-js">// returns content-type = text/plain const server = http.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); }); </code></pre> <p>Note that Content-Length is given in bytes not characters. The above example works because the string <code>'hello world'</code> contains only single byte characters. If the body contains higher coded characters then <code>Buffer.byteLength()</code> should be used to determine the number of bytes in a given encoding. And Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not.</p> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <h3>response.writeProcessing()<span><a class="mark" href="#http_response_writeprocessing" id="http_response_writeprocessing">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent.</p> <h2>Class: http.IncomingMessage<span><a class="mark" href="#http_class_http_incomingmessage" id="http_class_http_incomingmessage">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <p>An <code>IncomingMessage</code> object is created by <a href="#http_class_http_server"><code>http.Server</code></a> or <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> and passed as the first argument to the <a href="#http_event_request"><code>'request'</code></a> and <a href="#http_event_response"><code>'response'</code></a> event respectively. It may be used to access response status, headers and data.</p> <p>It implements the <a href="#stream_class_stream_readable">Readable Stream</a> interface, as well as the following additional events, methods, and properties.</p> <h3>Event: 'aborted'<span><a class="mark" href="#http_event_aborted" id="http_event_aborted">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.8</span> </div> <p>Emitted when the request has been aborted.</p> <h3>Event: 'close'<span><a class="mark" href="#http_event_close_2" id="http_event_close_2">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.4.2</span> </div> <p>Indicates that the underlying connection was closed. Just like <code>'end'</code>, this event occurs only once per response.</p> <h3>message.aborted<span><a class="mark" href="#http_message_aborted" id="http_message_aborted">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.1.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>message.aborted</code> property will be <code>true</code> if the request has been aborted.</p> <h3>message.complete<span><a class="mark" href="#http_message_complete" id="http_message_complete">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>message.complete</code> property will be <code>true</code> if a complete HTTP message has been received and successfully parsed.</p> <p>This property is particularly useful as a means of determining if a client or server fully transmitted a message before a connection was terminated:</p> <pre><code class="language-js">const req = http.request({ host: '127.0.0.1', port: 8080, method: 'POST' }, (res) => { res.resume(); res.on('end', () => { if (!res.complete) console.error( 'The connection was terminated while the message was still being sent'); }); }); </code></pre> <h3>message.destroy([error])<span><a class="mark" href="#http_message_destroy_error" id="http_message_destroy_error">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Calls <code>destroy()</code> on the socket that received the <code>IncomingMessage</code>. If <code>error</code> is provided, an <code>'error'</code> event is emitted and <code>error</code> is passed as an argument to any listeners on the event.</p> <h3>message.headers<span><a class="mark" href="#http_message_headers" id="http_message_headers">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.5</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The request/response headers object.</p> <p>Key-value pairs of header names and values. Header names are lower-cased.</p> <pre><code class="language-js">// Prints something like: // // { 'user-agent': 'curl/7.22.0', // host: '127.0.0.1:8000', // accept: '*/*' } console.log(request.headers); </code></pre> <p>Duplicates in raw headers are handled in the following ways, depending on the header name:</p> <ul> <li>Duplicates of <code>age</code>, <code>authorization</code>, <code>content-length</code>, <code>content-type</code>, <code>etag</code>, <code>expires</code>, <code>from</code>, <code>host</code>, <code>if-modified-since</code>, <code>if-unmodified-since</code>, <code>last-modified</code>, <code>location</code>, <code>max-forwards</code>, <code>proxy-authorization</code>, <code>referer</code>, <code>retry-after</code>, or <code>user-agent</code> are discarded.</li> <li><code>set-cookie</code> is always an array. Duplicates are added to the array.</li> <li>For duplicate <code>cookie</code> headers, the values are joined together with '; '.</li> <li>For all other headers, the values are joined together with ', '.</li> </ul> <h3>message.httpVersion<span><a class="mark" href="#http_message_httpversion" id="http_message_httpversion">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.1</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Probably either <code>'1.1'</code> or <code>'1.0'</code>.</p> <p>Also <code>message.httpVersionMajor</code> is the first integer and <code>message.httpVersionMinor</code> is the second.</p> <h3>message.method<span><a class="mark" href="#http_message_method" id="http_message_method">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.1</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p><strong>Only valid for request obtained from <a href="#http_class_http_server"><code>http.Server</code></a>.</strong></p> <p>The request method as a string. Read only. Examples: <code>'GET'</code>, <code>'DELETE'</code>.</p> <h3>message.rawHeaders<span><a class="mark" href="#http_message_rawheaders" id="http_message_rawheaders">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.6</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The raw request/response headers list exactly as they were received.</p> <p>Note that the keys and values are in the same list. It is <em>not</em> a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.</p> <p>Header names are not lowercased, and duplicates are not merged.</p> <pre><code class="language-js">// Prints something like: // // [ 'user-agent', // 'this is invalid because there can be only one', // 'User-Agent', // 'curl/7.22.0', // 'Host', // '127.0.0.1:8000', // 'ACCEPT', // '*/*' ] console.log(request.rawHeaders); </code></pre> <h3>message.rawTrailers<span><a class="mark" href="#http_message_rawtrailers" id="http_message_rawtrailers">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.6</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The raw request/response trailer keys and values exactly as they were received. Only populated at the <code>'end'</code> event.</p> <h3>message.setTimeout(msecs, callback)<span><a class="mark" href="#http_message_settimeout_msecs_callback" id="http_message_settimeout_msecs_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li> </ul> <p>Calls <code>message.connection.setTimeout(msecs, callback)</code>.</p> <h3>message.socket<span><a class="mark" href="#http_message_socket" id="http_message_socket">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>The <a href="#net_class_net_socket"><code>net.Socket</code></a> object associated with the connection.</p> <p>With HTTPS support, use <a href="#tls_tlssocket_getpeercertificate_detailed"><code>request.socket.getPeerCertificate()</code></a> to obtain the client's authentication details.</p> <h3>message.statusCode<span><a class="mark" href="#http_message_statuscode" id="http_message_statuscode">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.1</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p><strong>Only valid for response obtained from <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a>.</strong></p> <p>The 3-digit HTTP response status code. E.G. <code>404</code>.</p> <h3>message.statusMessage<span><a class="mark" href="#http_message_statusmessage" id="http_message_statusmessage">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.10</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p><strong>Only valid for response obtained from <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a>.</strong></p> <p>The HTTP response status message (reason phrase). E.G. <code>OK</code> or <code>Internal Server Error</code>.</p> <h3>message.trailers<span><a class="mark" href="#http_message_trailers" id="http_message_trailers">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The request/response trailers object. Only populated at the <code>'end'</code> event.</p> <h3>message.url<span><a class="mark" href="#http_message_url" id="http_message_url">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p><strong>Only valid for request obtained from <a href="#http_class_http_server"><code>http.Server</code></a>.</strong></p> <p>Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:</p> <pre><code class="language-txt">GET /status?name=ryan HTTP/1.1\r\n Accept: text/plain\r\n \r\n </code></pre> <p>Then <code>request.url</code> will be:</p> <!-- eslint-disable semi --> <pre><code class="language-js">'/status?name=ryan' </code></pre> <p>To parse the url into its parts <code>require('url').parse(request.url)</code> can be used:</p> <pre><code class="language-txt">$ node > require('url').parse('/status?name=ryan') Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?name=ryan', query: 'name=ryan', pathname: '/status', path: '/status?name=ryan', href: '/status?name=ryan' } </code></pre> <p>To extract the parameters from the query string, the <code>require('querystring').parse</code> function can be used, or <code>true</code> can be passed as the second argument to <code>require('url').parse</code>:</p> <pre><code class="language-txt">$ node > require('url').parse('/status?name=ryan', true) Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?name=ryan', query: { name: 'ryan' }, pathname: '/status', path: '/status?name=ryan', href: '/status?name=ryan' } </code></pre> <h2>http.METHODS<span><a class="mark" href="#http_http_methods" id="http_http_methods">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.8</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>A list of the HTTP methods that are supported by the parser.</p> <h2>http.STATUS_CODES<span><a class="mark" href="#http_http_status_codes" id="http_http_status_codes">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.22</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>A collection of all the standard HTTP response status codes, and the short description of each. For example, <code>http.STATUS_CODES[404] === 'Not Found'</code>.</p> <h2>http.createServer([options][, requestlistener])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/http.js#L37">[src]</a><span><a class="mark" href="#http_http_createserver_options_requestlistener" id="http_http_createserver_options_requestlistener">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.19.0</td> <td><p>The <code>insecureHTTPParser</code> option is supported now.</p></td></tr> <tr><td>v9.6.0, v8.12.0</td> <td><p>The <code>options</code> argument is supported now.</p></td></tr> <tr><td>v0.1.13</td> <td><p><span>Added in: v0.1.13</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>IncomingMessage</code> <a href="#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Specifies the <code>IncomingMessage</code> class to be used. Useful for extending the original <code>IncomingMessage</code>. <strong>Default:</strong> <code>IncomingMessage</code>.</li> <li><code>ServerResponse</code> <a href="#http_class_http_serverresponse" class="type"><http.ServerResponse></a> Specifies the <code>ServerResponse</code> class to be used. Useful for extending the original <code>ServerResponse</code>. <strong>Default:</strong> <code>ServerResponse</code>.</li> <li><code>insecureHTTPParser</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Use an insecure HTTP parser that accepts invalid HTTP headers when <code>true</code>. Using the insecure parser should be avoided. See <a href="#cli_insecure_http_parser"><code>--insecure-http-parser</code></a> for more information. <strong>Default:</strong> <code>false</code></li> </ul> </li> <li> <p><code>requestListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> </li> <li> <p>Returns: <a href="#http_class_http_server" class="type"><http.Server></a></p> </li> </ul> <p>Returns a new instance of <a href="#http_class_http_server"><code>http.Server</code></a>.</p> <p>The <code>requestListener</code> is a function which is automatically added to the <a href="#http_event_request"><code>'request'</code></a> event.</p> <h2>http.get(options[, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/http.js#L45">[src]</a><span><a class="mark" href="#http_http_get_options_callback" id="http_http_get_options_callback">#</a></span></h2> <h2>http.get(url[, options][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/http.js#L45">[src]</a><span><a class="mark" href="#http_http_get_url_options_callback" id="http_http_get_url_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.9.0</td> <td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr> <tr><td>v7.5.0</td> <td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr> <tr><td>v0.3.6</td> <td><p><span>Added in: v0.3.6</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Accepts the same <code>options</code> as <a href="#http_http_request_options_callback"><code>http.request()</code></a>, with the <code>method</code> always set to <code>GET</code>. Properties that are inherited from the prototype are ignored.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#http_class_http_clientrequest" class="type"><http.ClientRequest></a></li> </ul> <p>Since most requests are GET requests without bodies, Node.js provides this convenience method. The only difference between this method and <a href="#http_http_request_options_callback"><code>http.request()</code></a> is that it sets the method to GET and calls <code>req.end()</code> automatically. Note that the callback must take care to consume the response data for reasons stated in <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> section.</p> <p>The <code>callback</code> is invoked with a single argument that is an instance of <a href="#http_class_http_incomingmessage"><code>http.IncomingMessage</code></a>.</p> <p>JSON fetching example:</p> <pre><code class="language-js">http.get('http://nodejs.org/dist/index.json', (res) => { const { statusCode } = res; const contentType = res.headers['content-type']; let error; if (statusCode !== 200) { error = new Error('Request Failed.\n' + `Status Code: ${statusCode}`); } else if (!/^application\/json/.test(contentType)) { error = new Error('Invalid content-type.\n' + `Expected application/json but received ${contentType}`); } if (error) { console.error(error.message); // consume response data to free up memory res.resume(); return; } res.setEncoding('utf8'); let rawData = ''; res.on('data', (chunk) => { rawData += chunk; }); res.on('end', () => { try { const parsedData = JSON.parse(rawData); console.log(parsedData); } catch (e) { console.error(e.message); } }); }).on('error', (e) => { console.error(`Got error: ${e.message}`); }); </code></pre> <h2>http.globalAgent<span><a class="mark" href="#http_http_globalagent" id="http_http_globalagent">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><a href="#http_class_http_agent" class="type"><http.Agent></a></li> </ul> <p>Global instance of <code>Agent</code> which is used as the default for all HTTP client requests.</p> <h2>http.maxHeaderSize<span><a class="mark" href="#http_http_maxheadersize" id="http_http_maxheadersize">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.15.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Read-only property specifying the maximum allowed size of HTTP headers in bytes. Defaults to 8KB. Configurable using the <a href="#cli_max_http_header_size_size"><code>--max-http-header-size</code></a> CLI option.</p> <h2>http.request(options[, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/http.js#L41">[src]</a><span><a class="mark" href="#http_http_request_options_callback" id="http_http_request_options_callback">#</a></span></h2> <h2>http.request(url[, options][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/http.js#L41">[src]</a><span><a class="mark" href="#http_http_request_url_options_callback" id="http_http_request_url_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.19.0</td> <td><p>The <code>insecureHTTPParser</code> option is supported now.</p></td></tr> <tr><td>v10.9.0</td> <td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr> <tr><td>v7.5.0</td> <td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr> <tr><td>v0.3.6</td> <td><p><span>Added in: v0.3.6</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>protocol</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Protocol to use. <strong>Default:</strong> <code>'http:'</code>.</li> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A domain name or IP address of the server to issue the request to. <strong>Default:</strong> <code>'localhost'</code>.</li> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Alias for <code>host</code>. To support <a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>, <code>hostname</code> will be used if both <code>host</code> and <code>hostname</code> are specified.</li> <li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> IP address family to use when resolving <code>host</code> or <code>hostname</code>. Valid values are <code>4</code> or <code>6</code>. When unspecified, both IP v4 and v6 will be used.</li> <li><code>insecureHTTPParser</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Use an insecure HTTP parser that accepts invalid HTTP headers when <code>true</code>. Using the insecure parser should be avoided. See <a href="#cli_insecure_http_parser"><code>--insecure-http-parser</code></a> for more information. <strong>Default:</strong> <code>false</code></li> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port of remote server. <strong>Default:</strong> <code>80</code>.</li> <li><code>localAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Local interface to bind for network connections.</li> <li><code>socketPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Unix Domain Socket (cannot be used if one of <code>host</code> or <code>port</code> is specified, those specify a TCP Socket).</li> <li><code>method</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string specifying the HTTP request method. <strong>Default:</strong> <code>'GET'</code>.</li> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Request path. Should include query string if any. E.G. <code>'/index.html?page=12'</code>. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. <strong>Default:</strong> <code>'/'</code>.</li> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing request headers.</li> <li><code>auth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Basic authentication i.e. <code>'user:password'</code> to compute an Authorization header.</li> <li> <p><code>agent</code> <a href="#http_class_http_agent" class="type"><http.Agent></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Controls <a href="#http_class_http_agent"><code>Agent</code></a> behavior. Possible values:</p> <ul> <li><code>undefined</code> (default): use <a href="#http_http_globalagent"><code>http.globalAgent</code></a> for this host and port.</li> <li><code>Agent</code> object: explicitly use the passed in <code>Agent</code>.</li> <li><code>false</code>: causes a new <code>Agent</code> with default values to be used.</li> </ul> </li> <li><code>createConnection</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A function that produces a socket/stream to use for the request when the <code>agent</code> option is not used. This can be used to avoid creating a custom <code>Agent</code> class just to override the default <code>createConnection</code> function. See <a href="#http_agent_createconnection_options_callback"><code>agent.createConnection()</code></a> for more details. Any <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream is a valid return value.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a>: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.</li> <li><code>setHost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a>: Specifies whether or not to automatically add the <code>Host</code> header. Defaults to <code>true</code>.</li> </ul> </li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#http_class_http_clientrequest" class="type"><http.ClientRequest></a></li> </ul> <p>Node.js maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.</p> <p><code>url</code> can be a string or a <a href="#url_the_whatwg_url_api"><code>URL</code></a> object. If <code>url</code> is a string, it is automatically parsed with <a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>. If it is a <a href="#url_the_whatwg_url_api"><code>URL</code></a> object, it will be automatically converted to an ordinary <code>options</code> object.</p> <p>If both <code>url</code> and <code>options</code> are specified, the objects are merged, with the <code>options</code> properties taking precedence.</p> <p>The optional <code>callback</code> parameter will be added as a one-time listener for the <a href="#http_event_response"><code>'response'</code></a> event.</p> <p><code>http.request()</code> returns an instance of the <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> class. The <code>ClientRequest</code> instance is a writable stream. If one needs to upload a file with a POST request, then write to the <code>ClientRequest</code> object.</p> <pre><code class="language-js">const postData = querystring.stringify({ 'msg': 'Hello World!' }); const options = { hostname: 'www.google.com', port: 80, path: '/upload', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) } }; const req = http.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { console.log('No more data in response.'); }); }); req.on('error', (e) => { console.error(`problem with request: ${e.message}`); }); // write data to request body req.write(postData); req.end(); </code></pre> <p>Note that in the example <code>req.end()</code> was called. With <code>http.request()</code> one must always call <code>req.end()</code> to signify the end of the request - even if there is no data being written to the request body.</p> <p>If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an <code>'error'</code> event is emitted on the returned request object. As with all <code>'error'</code> events, if no listeners are registered the error will be thrown.</p> <p>There are a few special headers that should be noted.</p> <ul> <li> <p>Sending a 'Connection: keep-alive' will notify Node.js that the connection to the server should be persisted until the next request.</p> </li> <li> <p>Sending a 'Content-Length' header will disable the default chunked encoding.</p> </li> <li> <p>Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 100-continue', both a timeout and a listener for the <code>'continue'</code> event should be set. See RFC2616 Section 8.2.3 for more information.</p> </li> <li> <p>Sending an Authorization header will override using the <code>auth</code> option to compute basic authentication.</p> </li> </ul> <p>Example using a <a href="#url_the_whatwg_url_api"><code>URL</code></a> as <code>options</code>:</p> <pre><code class="language-js">const options = new URL('http://abc:xyz@example.com'); const req = http.request(options, (res) => { // ... }); </code></pre> <p>In a successful request, the following events will be emitted in the following order:</p> <ul> <li><code>'socket'</code></li> <li> <p><code>'response'</code></p> <ul> <li><code>'data'</code> any number of times, on the <code>res</code> object (<code>'data'</code> will not be emitted at all if the response body is empty, for instance, in most redirects)</li> <li><code>'end'</code> on the <code>res</code> object</li> </ul> </li> <li><code>'close'</code></li> </ul> <p>In the case of a connection error, the following events will be emitted:</p> <ul> <li><code>'socket'</code></li> <li><code>'error'</code></li> <li><code>'close'</code></li> </ul> <p>If <code>req.abort()</code> is called before the connection succeeds, the following events will be emitted in the following order:</p> <ul> <li><code>'socket'</code></li> <li>(<code>req.abort()</code> called here)</li> <li><code>'abort'</code></li> <li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code <code>'ECONNRESET'</code></li> <li><code>'close'</code></li> </ul> <p>If <code>req.abort()</code> is called after the response is received, the following events will be emitted in the following order:</p> <ul> <li><code>'socket'</code></li> <li> <p><code>'response'</code></p> <ul> <li><code>'data'</code> any number of times, on the <code>res</code> object</li> </ul> </li> <li>(<code>req.abort()</code> called here)</li> <li><code>'abort'</code></li> <li><code>'aborted'</code> on the <code>res</code> object</li> <li><code>'close'</code></li> <li><code>'end'</code> on the <code>res</code> object</li> <li><code>'close'</code> on the <code>res</code> object</li> </ul> <p>Note that setting the <code>timeout</code> option or using the <code>setTimeout()</code> function will not abort the request or do anything besides add a <code>'timeout'</code> event.</p> <h1>HTTP/2<span><a class="mark" href="#http2_http_2" id="http2_http_2">#</a></span></h1> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.10.0</td> <td><p>HTTP/2 is now Stable. Previously, it had been Experimental.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>http2</code> module provides an implementation of the <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> protocol. It can be accessed using:</p> <pre><code class="language-js">const http2 = require('http2'); </code></pre> <h2>Core API<span><a class="mark" href="#http2_core_api" id="http2_core_api">#</a></span></h2> <p>The Core API provides a low-level interface designed specifically around support for HTTP/2 protocol features. It is specifically <em>not</em> designed for compatibility with the existing <a href="http.html">HTTP/1</a> module API. However, the <a href="#http2_compatibility_api">Compatibility API</a> is.</p> <p>The <code>http2</code> Core API is much more symmetric between client and server than the <code>http</code> API. For instance, most events, like <code>'error'</code>, <code>'connect'</code> and <code>'stream'</code>, can be emitted either by client-side code or server-side code.</p> <h3>Server-side example<span><a class="mark" href="#http2_server_side_example" id="http2_server_side_example">#</a></span></h3> <p>The following illustrates a simple HTTP/2 server using the Core API. Since there are no browsers known that support <a href="https://http2.github.io/faq/#does-http2-require-encryption">unencrypted HTTP/2</a>, the use of <a href="#http2_http2_createsecureserver_options_onrequesthandler"><code>http2.createSecureServer()</code></a> is necessary when communicating with browser clients.</p> <pre><code class="language-js">const http2 = require('http2'); const fs = require('fs'); const server = http2.createSecureServer({ key: fs.readFileSync('localhost-privkey.pem'), cert: fs.readFileSync('localhost-cert.pem') }); server.on('error', (err) => console.error(err)); server.on('stream', (stream, headers) => { // stream is a Duplex stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.end('<h1>Hello World</h1>'); }); server.listen(8443); </code></pre> <p>To generate the certificate and key for this example, run:</p> <pre><code class="language-bash">openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \ -keyout localhost-privkey.pem -out localhost-cert.pem </code></pre> <h3>Client-side example<span><a class="mark" href="#http2_client_side_example" id="http2_client_side_example">#</a></span></h3> <p>The following illustrates an HTTP/2 client:</p> <pre><code class="language-js">const http2 = require('http2'); const fs = require('fs'); const client = http2.connect('https://localhost:8443', { ca: fs.readFileSync('localhost-cert.pem') }); client.on('error', (err) => console.error(err)); const req = client.request({ ':path': '/' }); req.on('response', (headers, flags) => { for (const name in headers) { console.log(`${name}: ${headers[name]}`); } }); req.setEncoding('utf8'); let data = ''; req.on('data', (chunk) => { data += chunk; }); req.on('end', () => { console.log(`\n${data}`); client.close(); }); req.end(); </code></pre> <h3>Class: Http2Session<span><a class="mark" href="#http2_class_http2session" id="http2_class_http2session">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends: <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Instances of the <code>http2.Http2Session</code> class represent an active communications session between an HTTP/2 client and server. Instances of this class are <em>not</em> intended to be constructed directly by user code.</p> <p>Each <code>Http2Session</code> instance will exhibit slightly different behaviors depending on whether it is operating as a server or a client. The <code>http2session.type</code> property can be used to determine the mode in which an <code>Http2Session</code> is operating. On the server side, user code should rarely have occasion to work with the <code>Http2Session</code> object directly, with most actions typically taken through interactions with either the <code>Http2Server</code> or <code>Http2Stream</code> objects.</p> <p>User code will not create <code>Http2Session</code> instances directly. Server-side <code>Http2Session</code> instances are created by the <code>Http2Server</code> instance when a new HTTP/2 connection is received. Client-side <code>Http2Session</code> instances are created using the <code>http2.connect()</code> method.</p> <h4>Http2Session and Sockets<span><a class="mark" href="#http2_http2session_and_sockets" id="http2_http2session_and_sockets">#</a></span></h4> <p>Every <code>Http2Session</code> instance is associated with exactly one <a href="#net_class_net_socket"><code>net.Socket</code></a> or <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> when it is created. When either the <code>Socket</code> or the <code>Http2Session</code> are destroyed, both will be destroyed.</p> <p>Because of the specific serialization and processing requirements imposed by the HTTP/2 protocol, it is not recommended for user code to read data from or write data to a <code>Socket</code> instance bound to a <code>Http2Session</code>. Doing so can put the HTTP/2 session into an indeterminate state causing the session and the socket to become unusable.</p> <p>Once a <code>Socket</code> has been bound to an <code>Http2Session</code>, user code should rely solely on the API of the <code>Http2Session</code>.</p> <h4>Event: 'close'<span><a class="mark" href="#http2_event_close" id="http2_event_close">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'close'</code> event is emitted once the <code>Http2Session</code> has been destroyed. Its listener does not expect any arguments.</p> <h4>Event: 'connect'<span><a class="mark" href="#http2_event_connect" id="http2_event_connect">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>session</code> <a href="#http2_class_http2session" class="type"><Http2Session></a></li> <li><code>socket</code> <a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>The <code>'connect'</code> event is emitted once the <code>Http2Session</code> has been successfully connected to the remote peer and communication may begin.</p> <p>User code will typically not listen for this event directly.</p> <h4>Event: 'error'<span><a class="mark" href="#http2_event_error" id="http2_event_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>The <code>'error'</code> event is emitted when an error occurs during the processing of an <code>Http2Session</code>.</p> <h4>Event: 'frameError'<span><a class="mark" href="#http2_event_frameerror" id="http2_event_frameerror">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The frame type.</li> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The error code.</li> <li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The stream id (or <code>0</code> if the frame isn't associated with a stream).</li> </ul> <p>The <code>'frameError'</code> event is emitted when an error occurs while attempting to send a frame on the session. If the frame that could not be sent is associated with a specific <code>Http2Stream</code>, an attempt to emit <code>'frameError'</code> event on the <code>Http2Stream</code> is made.</p> <p>If the <code>'frameError'</code> event is associated with a stream, the stream will be closed and destroyed immediately following the <code>'frameError'</code> event. If the event is not associated with a stream, the <code>Http2Session</code> will be shut down immediately following the <code>'frameError'</code> event.</p> <h4>Event: 'goaway'<span><a class="mark" href="#http2_event_goaway" id="http2_event_goaway">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>errorCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The HTTP/2 error code specified in the <code>GOAWAY</code> frame.</li> <li><code>lastStreamID</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The ID of the last stream the remote peer successfully processed (or <code>0</code> if no ID is specified).</li> <li><code>opaqueData</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> If additional opaque data was included in the <code>GOAWAY</code> frame, a <code>Buffer</code> instance will be passed containing that data.</li> </ul> <p>The <code>'goaway'</code> event is emitted when a <code>GOAWAY</code> frame is received.</p> <p>The <code>Http2Session</code> instance will be shut down automatically when the <code>'goaway'</code> event is emitted.</p> <h4>Event: 'localSettings'<span><a class="mark" href="#http2_event_localsettings" id="http2_event_localsettings">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>settings</code> <a href="#http2_settings_object" class="type"><HTTP/2 Settings Object></a> A copy of the <code>SETTINGS</code> frame received.</li> </ul> <p>The <code>'localSettings'</code> event is emitted when an acknowledgment <code>SETTINGS</code> frame has been received.</p> <p>When using <code>http2session.settings()</code> to submit new settings, the modified settings do not take effect until the <code>'localSettings'</code> event is emitted.</p> <pre><code class="language-js">session.settings({ enablePush: false }); session.on('localSettings', (settings) => { /* Use the new settings */ }); </code></pre> <h4>Event: 'ping'<span><a class="mark" href="#http2_event_ping" id="http2_event_ping">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>payload</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> The <code>PING</code> frame 8-byte payload</li> </ul> <p>The <code>'ping'</code> event is emitted whenever a <code>PING</code> frame is received from the connected peer.</p> <h4>Event: 'remoteSettings'<span><a class="mark" href="#http2_event_remotesettings" id="http2_event_remotesettings">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>settings</code> <a href="#http2_settings_object" class="type"><HTTP/2 Settings Object></a> A copy of the <code>SETTINGS</code> frame received.</li> </ul> <p>The <code>'remoteSettings'</code> event is emitted when a new <code>SETTINGS</code> frame is received from the connected peer.</p> <pre><code class="language-js">session.on('remoteSettings', (settings) => { /* Use the new settings */ }); </code></pre> <h4>Event: 'stream'<span><a class="mark" href="#http2_event_stream" id="http2_event_stream">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>stream</code> <a href="#http2_class_http2stream" class="type"><Http2Stream></a> A reference to the stream</li> <li><code>headers</code> <a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a> An object describing the headers</li> <li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The associated numeric flags</li> <li><code>rawHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> An array containing the raw header names followed by their respective values.</li> </ul> <p>The <code>'stream'</code> event is emitted when a new <code>Http2Stream</code> is created.</p> <pre><code class="language-js">const http2 = require('http2'); session.on('stream', (stream, headers, flags) => { const method = headers[':method']; const path = headers[':path']; // ... stream.respond({ ':status': 200, 'content-type': 'text/plain' }); stream.write('hello '); stream.end('world'); }); </code></pre> <p>On the server side, user code will typically not listen for this event directly, and would instead register a handler for the <code>'stream'</code> event emitted by the <code>net.Server</code> or <code>tls.Server</code> instances returned by <code>http2.createServer()</code> and <code>http2.createSecureServer()</code>, respectively, as in the example below:</p> <pre><code class="language-js">const http2 = require('http2'); // Create an unencrypted HTTP/2 server const server = http2.createServer(); server.on('stream', (stream, headers) => { stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.on('error', (error) => console.error(error)); stream.end('<h1>Hello World</h1>'); }); server.listen(80); </code></pre> <p>Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence, a network error will destroy each individual stream and must be handled on the stream level, as shown above.</p> <h4>Event: 'timeout'<span><a class="mark" href="#http2_event_timeout" id="http2_event_timeout">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>After the <code>http2session.setTimeout()</code> method is used to set the timeout period for this <code>Http2Session</code>, the <code>'timeout'</code> event is emitted if there is no activity on the <code>Http2Session</code> after the configured number of milliseconds.</p> <pre><code class="language-js">session.setTimeout(2000); session.on('timeout', () => { /* .. */ }); </code></pre> <h4>http2session.alpnProtocol<span><a class="mark" href="#http2_http2session_alpnprotocol" id="http2_http2session_alpnprotocol">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> </ul> <p>Value will be <code>undefined</code> if the <code>Http2Session</code> is not yet connected to a socket, <code>h2c</code> if the <code>Http2Session</code> is not connected to a <code>TLSSocket</code>, or will return the value of the connected <code>TLSSocket</code>'s own <code>alpnProtocol</code> property.</p> <h4>http2session.close([callback])<span><a class="mark" href="#http2_http2session_close_callback" id="http2_http2session_close_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Gracefully closes the <code>Http2Session</code>, allowing any existing streams to complete on their own and preventing new <code>Http2Stream</code> instances from being created. Once closed, <code>http2session.destroy()</code> <em>might</em> be called if there are no open <code>Http2Stream</code> instances.</p> <p>If specified, the <code>callback</code> function is registered as a handler for the <code>'close'</code> event.</p> <h4>http2session.closed<span><a class="mark" href="#http2_http2session_closed" id="http2_http2session_closed">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Will be <code>true</code> if this <code>Http2Session</code> instance has been closed, otherwise <code>false</code>.</p> <h4>http2session.connecting<span><a class="mark" href="#http2_http2session_connecting" id="http2_http2session_connecting">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Will be <code>true</code> if this <code>Http2Session</code> instance is still connecting, will be set to <code>false</code> before emitting <code>connect</code> event and/or calling the <code>http2.connect</code> callback.</p> <h4>http2session.destroy([error][, code])<span><a class="mark" href="#http2_http2session_destroy_error_code" id="http2_http2session_destroy_error_code">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> An <code>Error</code> object if the <code>Http2Session</code> is being destroyed due to an error.</li> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The HTTP/2 error code to send in the final <code>GOAWAY</code> frame. If unspecified, and <code>error</code> is not undefined, the default is <code>INTERNAL_ERROR</code>, otherwise defaults to <code>NO_ERROR</code>.</li> </ul> <p>Immediately terminates the <code>Http2Session</code> and the associated <code>net.Socket</code> or <code>tls.TLSSocket</code>.</p> <p>Once destroyed, the <code>Http2Session</code> will emit the <code>'close'</code> event. If <code>error</code> is not undefined, an <code>'error'</code> event will be emitted immediately before the <code>'close'</code> event.</p> <p>If there are any remaining open <code>Http2Streams</code> associated with the <code>Http2Session</code>, those will also be destroyed.</p> <h4>http2session.destroyed<span><a class="mark" href="#http2_http2session_destroyed" id="http2_http2session_destroyed">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Will be <code>true</code> if this <code>Http2Session</code> instance has been destroyed and must no longer be used, otherwise <code>false</code>.</p> <h4>http2session.encrypted<span><a class="mark" href="#http2_http2session_encrypted" id="http2_http2session_encrypted">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> </ul> <p>Value is <code>undefined</code> if the <code>Http2Session</code> session socket has not yet been connected, <code>true</code> if the <code>Http2Session</code> is connected with a <code>TLSSocket</code>, and <code>false</code> if the <code>Http2Session</code> is connected to any other kind of socket or stream.</p> <h4>http2session.goaway([code[, lastStreamID[, opaqueData]]])<span><a class="mark" href="#http2_http2session_goaway_code_laststreamid_opaquedata" id="http2_http2session_goaway_code_laststreamid_opaquedata">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> An HTTP/2 error code</li> <li><code>lastStreamID</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The numeric ID of the last processed <code>Http2Stream</code></li> <li><code>opaqueData</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> A <code>TypedArray</code> or <code>DataView</code> instance containing additional data to be carried within the <code>GOAWAY</code> frame.</li> </ul> <p>Transmits a <code>GOAWAY</code> frame to the connected peer <em>without</em> shutting down the <code>Http2Session</code>.</p> <h4>http2session.localSettings<span><a class="mark" href="#http2_http2session_localsettings" id="http2_http2session_localsettings">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> </ul> <p>A prototype-less object describing the current local settings of this <code>Http2Session</code>. The local settings are local to <em>this</em> <code>Http2Session</code> instance.</p> <h4>http2session.originSet<span><a class="mark" href="#http2_http2session_originset" id="http2_http2session_originset">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> </ul> <p>If the <code>Http2Session</code> is connected to a <code>TLSSocket</code>, the <code>originSet</code> property will return an <code>Array</code> of origins for which the <code>Http2Session</code> may be considered authoritative.</p> <p>The <code>originSet</code> property is only available when using a secure TLS connection.</p> <h4>http2session.pendingSettingsAck<span><a class="mark" href="#http2_http2session_pendingsettingsack" id="http2_http2session_pendingsettingsack">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Indicates whether or not the <code>Http2Session</code> is currently waiting for an acknowledgment for a sent <code>SETTINGS</code> frame. Will be <code>true</code> after calling the <code>http2session.settings()</code> method. Will be <code>false</code> once all sent SETTINGS frames have been acknowledged.</p> <h4>http2session.ping([payload, ]callback)<span><a class="mark" href="#http2_http2session_ping_payload_callback" id="http2_http2session_ping_payload_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.9.3</span> </div> <ul> <li><code>payload</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> Optional ping payload.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Sends a <code>PING</code> frame to the connected HTTP/2 peer. A <code>callback</code> function must be provided. The method will return <code>true</code> if the <code>PING</code> was sent, <code>false</code> otherwise.</p> <p>The maximum number of outstanding (unacknowledged) pings is determined by the <code>maxOutstandingPings</code> configuration option. The default maximum is 10.</p> <p>If provided, the <code>payload</code> must be a <code>Buffer</code>, <code>TypedArray</code>, or <code>DataView</code> containing 8 bytes of data that will be transmitted with the <code>PING</code> and returned with the ping acknowledgment.</p> <p>The callback will be invoked with three arguments: an error argument that will be <code>null</code> if the <code>PING</code> was successfully acknowledged, a <code>duration</code> argument that reports the number of milliseconds elapsed since the ping was sent and the acknowledgment was received, and a <code>Buffer</code> containing the 8-byte <code>PING</code> payload.</p> <pre><code class="language-js">session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { if (!err) { console.log(`Ping acknowledged in ${duration} milliseconds`); console.log(`With payload '${payload.toString()}'`); } }); </code></pre> <p>If the <code>payload</code> argument is not specified, the default payload will be the 64-bit timestamp (little endian) marking the start of the <code>PING</code> duration.</p> <h4>http2session.ref()<span><a class="mark" href="#http2_http2session_ref" id="http2_http2session_ref">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <p>Calls <a href="#net_socket_ref"><code>ref()</code></a> on this <code>Http2Session</code> instance's underlying <a href="#net_class_net_socket"><code>net.Socket</code></a>.</p> <h4>http2session.remoteSettings<span><a class="mark" href="#http2_http2session_remotesettings" id="http2_http2session_remotesettings">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> </ul> <p>A prototype-less object describing the current remote settings of this <code>Http2Session</code>. The remote settings are set by the <em>connected</em> HTTP/2 peer.</p> <h4>http2session.setTimeout(msecs, callback)<span><a class="mark" href="#http2_http2session_settimeout_msecs_callback" id="http2_http2session_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Used to set a callback function that is called when there is no activity on the <code>Http2Session</code> after <code>msecs</code> milliseconds. The given <code>callback</code> is registered as a listener on the <code>'timeout'</code> event.</p> <h4>http2session.socket<span><a class="mark" href="#http2_http2session_socket" id="http2_http2session_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="#net_class_net_socket" class="type"><net.Socket></a> | <a href="#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li> </ul> <p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but limits available methods to ones safe to use with HTTP/2.</p> <p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw an error with code <code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href="#http2_http2session_and_sockets"><code>Http2Session</code> and Sockets</a> for more information.</p> <p><code>setTimeout</code> method will be called on this <code>Http2Session</code>.</p> <p>All other interactions will be routed directly to the socket.</p> <h4>http2session.state<span><a class="mark" href="#http2_http2session_state" id="http2_http2session_state">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Provides miscellaneous information about the current state of the <code>Http2Session</code>.</p> <ul> <li> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>effectiveLocalWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The current local (receive) flow control window size for the <code>Http2Session</code>.</li> <li><code>effectiveRecvDataLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The current number of bytes that have been received since the last flow control <code>WINDOW_UPDATE</code>.</li> <li><code>nextStreamID</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The numeric identifier to be used the next time a new <code>Http2Stream</code> is created by this <code>Http2Session</code>.</li> <li><code>localWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes that the remote peer can send without receiving a <code>WINDOW_UPDATE</code>.</li> <li><code>lastProcStreamID</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The numeric id of the <code>Http2Stream</code> for which a <code>HEADERS</code> or <code>DATA</code> frame was most recently received.</li> <li><code>remoteWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes that this <code>Http2Session</code> may send without receiving a <code>WINDOW_UPDATE</code>.</li> <li><code>outboundQueueSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of frames currently within the outbound queue for this <code>Http2Session</code>.</li> <li><code>deflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The current size in bytes of the outbound header compression state table.</li> <li><code>inflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The current size in bytes of the inbound header compression state table.</li> </ul> </li> </ul> <p>An object describing the current status of this <code>Http2Session</code>.</p> <h4>http2session.settings(settings)<span><a class="mark" href="#http2_http2session_settings_settings" id="http2_http2session_settings_settings">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>settings</code> <a href="#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> </ul> <p>Updates the current local settings for this <code>Http2Session</code> and sends a new <code>SETTINGS</code> frame to the connected HTTP/2 peer.</p> <p>Once called, the <code>http2session.pendingSettingsAck</code> property will be <code>true</code> while the session is waiting for the remote peer to acknowledge the new settings.</p> <p>The new settings will not become effective until the <code>SETTINGS</code> acknowledgment is received and the <code>'localSettings'</code> event is emitted. It is possible to send multiple <code>SETTINGS</code> frames while acknowledgment is still pending.</p> <h4>http2session.type<span><a class="mark" href="#http2_http2session_type" id="http2_http2session_type">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <code>http2session.type</code> will be equal to <code>http2.constants.NGHTTP2_SESSION_SERVER</code> if this <code>Http2Session</code> instance is a server, and <code>http2.constants.NGHTTP2_SESSION_CLIENT</code> if the instance is a client.</p> <h4>http2session.unref()<span><a class="mark" href="#http2_http2session_unref" id="http2_http2session_unref">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <p>Calls <a href="#net_socket_unref"><code>unref()</code></a> on this <code>Http2Session</code> instance's underlying <a href="#net_class_net_socket"><code>net.Socket</code></a>.</p> <h3>Class: ServerHttp2Session<span><a class="mark" href="#http2_class_serverhttp2session" id="http2_class_serverhttp2session">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <h4>serverhttp2session.altsvc(alt, originOrStream)<span><a class="mark" href="#http2_serverhttp2session_altsvc_alt_originorstream" id="http2_serverhttp2session_altsvc_alt_originorstream">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><code>alt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A description of the alternative service configuration as defined by <a href="https://tools.ietf.org/html/rfc7838">RFC 7838</a>.</li> <li><code>originOrStream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Either a URL string specifying the origin (or an <code>Object</code> with an <code>origin</code> property) or the numeric identifier of an active <code>Http2Stream</code> as given by the <code>http2stream.id</code> property.</li> </ul> <p>Submits an <code>ALTSVC</code> frame (as defined by <a href="https://tools.ietf.org/html/rfc7838">RFC 7838</a>) to the connected client.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('session', (session) => { // Set altsvc for origin https://example.org:80 session.altsvc('h2=":8000"', 'https://example.org:80'); }); server.on('stream', (stream) => { // Set altsvc for a specific stream stream.session.altsvc('h2=":8000"', stream.id); }); </code></pre> <p>Sending an <code>ALTSVC</code> frame with a specific stream ID indicates that the alternate service is associated with the origin of the given <code>Http2Stream</code>.</p> <p>The <code>alt</code> and origin string <em>must</em> contain only ASCII bytes and are strictly interpreted as a sequence of ASCII bytes. The special value <code>'clear'</code> may be passed to clear any previously set alternative service for a given domain.</p> <p>When a string is passed for the <code>originOrStream</code> argument, it will be parsed as a URL and the origin will be derived. For instance, the origin for the HTTP URL <code>'https://example.org/foo/bar'</code> is the ASCII string <code>'https://example.org'</code>. An error will be thrown if either the given string cannot be parsed as a URL or if a valid origin cannot be derived.</p> <p>A <code>URL</code> object, or any object with an <code>origin</code> property, may be passed as <code>originOrStream</code>, in which case the value of the <code>origin</code> property will be used. The value of the <code>origin</code> property <em>must</em> be a properly serialized ASCII origin.</p> <h4>Specifying alternative services<span><a class="mark" href="#http2_specifying_alternative_services" id="http2_specifying_alternative_services">#</a></span></h4> <p>The format of the <code>alt</code> parameter is strictly defined by <a href="https://tools.ietf.org/html/rfc7838">RFC 7838</a> as an ASCII string containing a comma-delimited list of "alternative" protocols associated with a specific host and port.</p> <p>For example, the value <code>'h2="example.org:81"'</code> indicates that the HTTP/2 protocol is available on the host <code>'example.org'</code> on TCP/IP port 81. The host and port <em>must</em> be contained within the quote (<code>"</code>) characters.</p> <p>Multiple alternatives may be specified, for instance: <code>'h2="example.org:81", h2=":82"'</code>.</p> <p>The protocol identifier (<code>'h2'</code> in the examples) may be any valid <a href="https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids">ALPN Protocol ID</a>.</p> <p>The syntax of these values is not validated by the Node.js implementation and are passed through as provided by the user or received from the peer.</p> <h4>serverhttp2session.origin(...origins)<span><a class="mark" href="#http2_serverhttp2session_origin_origins" id="http2_serverhttp2session_origin_origins">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> One or more URL Strings passed as separate arguments.</li> </ul> <p>Submits an <code>ORIGIN</code> frame (as defined by <a href="https://tools.ietf.org/html/rfc8336">RFC 8336</a>) to the connected client to advertise the set of origins for which the server is capable of providing authoritative responses.</p> <pre><code class="language-js">const http2 = require('http2'); const options = getSecureOptionsSomehow(); const server = http2.createSecureServer(options); server.on('stream', (stream) => { stream.respond(); stream.end('ok'); }); server.on('session', (session) => { session.origin('https://example.com', 'https://example.org'); }); </code></pre> <p>When a string is passed as an <code>origin</code>, it will be parsed as a URL and the origin will be derived. For instance, the origin for the HTTP URL <code>'https://example.org/foo/bar'</code> is the ASCII string <code>'https://example.org'</code>. An error will be thrown if either the given string cannot be parsed as a URL or if a valid origin cannot be derived.</p> <p>A <code>URL</code> object, or any object with an <code>origin</code> property, may be passed as an <code>origin</code>, in which case the value of the <code>origin</code> property will be used. The value of the <code>origin</code> property <em>must</em> be a properly serialized ASCII origin.</p> <p>Alternatively, the <code>origins</code> option may be used when creating a new HTTP/2 server using the <code>http2.createSecureServer()</code> method:</p> <pre><code class="language-js">const http2 = require('http2'); const options = getSecureOptionsSomehow(); options.origins = ['https://example.com', 'https://example.org']; const server = http2.createSecureServer(options); server.on('stream', (stream) => { stream.respond(); stream.end('ok'); }); </code></pre> <h3>Class: ClientHttp2Session<span><a class="mark" href="#http2_class_clienthttp2session" id="http2_class_clienthttp2session">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <h4>Event: 'altsvc'<span><a class="mark" href="#http2_event_altsvc" id="http2_event_altsvc">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><code>alt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>origin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>streamId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <code>'altsvc'</code> event is emitted whenever an <code>ALTSVC</code> frame is received by the client. The event is emitted with the <code>ALTSVC</code> value, origin, and stream ID. If no <code>origin</code> is provided in the <code>ALTSVC</code> frame, <code>origin</code> will be an empty string.</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('https://example.org'); client.on('altsvc', (alt, origin, streamId) => { console.log(alt); console.log(origin); console.log(streamId); }); </code></pre> <h4>Event: 'origin'<span><a class="mark" href="#http2_event_origin" id="http2_event_origin">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The <code>'origin'</code> event is emitted whenever an <code>ORIGIN</code> frame is received by the client. The event is emitted with an array of <code>origin</code> strings. The <code>http2session.originSet</code> will be updated to include the received origins.</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('https://example.org'); client.on('origin', (origins) => { for (let n = 0; n < origins.length; n++) console.log(origins[n]); }); </code></pre> <p>The <code>'origin'</code> event is only emitted when using a secure TLS connection.</p> <h4>clienthttp2session.request(headers[, options])<span><a class="mark" href="#http2_clienthttp2session_request_headers_options" id="http2_clienthttp2session_request_headers_options">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li> <p><code>headers</code> <a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a></p> </li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>endStream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the <code>Http2Stream</code> <em>writable</em> side should be closed initially, such as when sending a <code>GET</code> request that should not expect a payload body.</li> <li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and <code>parent</code> identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. <strong>Default:</strong> <code>false</code>.</li> <li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the numeric identifier of a stream the newly created stream is dependent on.</li> <li><code>weight</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the relative dependency of a stream in relation to other streams with the same <code>parent</code>. The value is a number between <code>1</code> and <code>256</code> (inclusive).</li> <li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the <code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li> </ul> </li> <li> <p>Returns: <a href="#http2_class_clienthttp2stream" class="type"><ClientHttp2Stream></a></p> </li> </ul> <p>For HTTP/2 Client <code>Http2Session</code> instances only, the <code>http2session.request()</code> creates and returns an <code>Http2Stream</code> instance that can be used to send an HTTP/2 request to the connected server.</p> <p>This method is only available if <code>http2session.type</code> is equal to <code>http2.constants.NGHTTP2_SESSION_CLIENT</code>.</p> <pre><code class="language-js">const http2 = require('http2'); const clientSession = http2.connect('https://localhost:1234'); const { HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = http2.constants; const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); req.on('response', (headers) => { console.log(headers[HTTP2_HEADER_STATUS]); req.on('data', (chunk) => { /* .. */ }); req.on('end', () => { /* .. */ }); }); </code></pre> <p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event is emitted immediately after queuing the last chunk of payload data to be sent. The <code>http2stream.sendTrailers()</code> method can then be called to send trailing headers to the peer.</p> <p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically close when the final <code>DATA</code> frame is transmitted. User code must call either <code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the <code>Http2Stream</code>.</p> <p>The <code>:method</code> and <code>:path</code> pseudo-headers are not specified within <code>headers</code>, they respectively default to:</p> <ul> <li><code>:method</code> = <code>'GET'</code></li> <li><code>:path</code> = <code>/</code></li> </ul> <h3>Class: Http2Stream<span><a class="mark" href="#http2_class_http2stream" id="http2_class_http2stream">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends: <a href="#stream_class_stream_duplex" class="type"><stream.Duplex></a></li> </ul> <p>Each instance of the <code>Http2Stream</code> class represents a bidirectional HTTP/2 communications stream over an <code>Http2Session</code> instance. Any single <code>Http2Session</code> may have up to 2<sup>31</sup>-1 <code>Http2Stream</code> instances over its lifetime.</p> <p>User code will not construct <code>Http2Stream</code> instances directly. Rather, these are created, managed, and provided to user code through the <code>Http2Session</code> instance. On the server, <code>Http2Stream</code> instances are created either in response to an incoming HTTP request (and handed off to user code via the <code>'stream'</code> event), or in response to a call to the <code>http2stream.pushStream()</code> method. On the client, <code>Http2Stream</code> instances are created and returned when either the <code>http2session.request()</code> method is called, or in response to an incoming <code>'push'</code> event.</p> <p>The <code>Http2Stream</code> class is a base for the <a href="#http2_class_serverhttp2stream"><code>ServerHttp2Stream</code></a> and <a href="#http2_class_clienthttp2stream"><code>ClientHttp2Stream</code></a> classes, each of which is used specifically by either the Server or Client side, respectively.</p> <p>All <code>Http2Stream</code> instances are <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams. The <code>Writable</code> side of the <code>Duplex</code> is used to send data to the connected peer, while the <code>Readable</code> side is used to receive data sent by the connected peer.</p> <h4>Http2Stream Lifecycle<span><a class="mark" href="#http2_http2stream_lifecycle" id="http2_http2stream_lifecycle">#</a></span></h4> <h5>Creation<span><a class="mark" href="#http2_creation" id="http2_creation">#</a></span></h5> <p>On the server side, instances of <a href="#http2_class_serverhttp2stream"><code>ServerHttp2Stream</code></a> are created either when:</p> <ul> <li>A new HTTP/2 <code>HEADERS</code> frame with a previously unused stream ID is received;</li> <li>The <code>http2stream.pushStream()</code> method is called.</li> </ul> <p>On the client side, instances of <a href="#http2_class_clienthttp2stream"><code>ClientHttp2Stream</code></a> are created when the <code>http2session.request()</code> method is called.</p> <p>On the client, the <code>Http2Stream</code> instance returned by <code>http2session.request()</code> may not be immediately ready for use if the parent <code>Http2Session</code> has not yet been fully established. In such cases, operations called on the <code>Http2Stream</code> will be buffered until the <code>'ready'</code> event is emitted. User code should rarely, if ever, need to handle the <code>'ready'</code> event directly. The ready status of an <code>Http2Stream</code> can be determined by checking the value of <code>http2stream.id</code>. If the value is <code>undefined</code>, the stream is not yet ready for use.</p> <h5>Destruction<span><a class="mark" href="#http2_destruction" id="http2_destruction">#</a></span></h5> <p>All <a href="#http2_class_http2stream"><code>Http2Stream</code></a> instances are destroyed either when:</p> <ul> <li>An <code>RST_STREAM</code> frame for the stream is received by the connected peer, and (for client streams only) pending data has been read.</li> <li>The <code>http2stream.close()</code> method is called, and (for client streams only) pending data has been read.</li> <li>The <code>http2stream.destroy()</code> or <code>http2session.destroy()</code> methods are called.</li> </ul> <p>When an <code>Http2Stream</code> instance is destroyed, an attempt will be made to send an <code>RST_STREAM</code> frame will be sent to the connected peer.</p> <p>When the <code>Http2Stream</code> instance is destroyed, the <code>'close'</code> event will be emitted. Because <code>Http2Stream</code> is an instance of <code>stream.Duplex</code>, the <code>'end'</code> event will also be emitted if the stream data is currently flowing. The <code>'error'</code> event may also be emitted if <code>http2stream.destroy()</code> was called with an <code>Error</code> passed as the first argument.</p> <p>After the <code>Http2Stream</code> has been destroyed, the <code>http2stream.destroyed</code> property will be <code>true</code> and the <code>http2stream.rstCode</code> property will specify the <code>RST_STREAM</code> error code. The <code>Http2Stream</code> instance is no longer usable once destroyed.</p> <h4>Event: 'aborted'<span><a class="mark" href="#http2_event_aborted" id="http2_event_aborted">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'aborted'</code> event is emitted whenever a <code>Http2Stream</code> instance is abnormally aborted in mid-communication.</p> <p>The <code>'aborted'</code> event will only be emitted if the <code>Http2Stream</code> writable side has not been ended.</p> <h4>Event: 'close'<span><a class="mark" href="#http2_event_close_1" id="http2_event_close_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'close'</code> event is emitted when the <code>Http2Stream</code> is destroyed. Once this event is emitted, the <code>Http2Stream</code> instance is no longer usable.</p> <p>The HTTP/2 error code used when closing the stream can be retrieved using the <code>http2stream.rstCode</code> property. If the code is any value other than <code>NGHTTP2_NO_ERROR</code> (<code>0</code>), an <code>'error'</code> event will have also been emitted.</p> <h4>Event: 'error'<span><a class="mark" href="#http2_event_error_1" id="http2_event_error_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>The <code>'error'</code> event is emitted when an error occurs during the processing of an <code>Http2Stream</code>.</p> <h4>Event: 'frameError'<span><a class="mark" href="#http2_event_frameerror_1" id="http2_event_frameerror_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'frameError'</code> event is emitted when an error occurs while attempting to send a frame. When invoked, the handler function will receive an integer argument identifying the frame type, and an integer argument identifying the error code. The <code>Http2Stream</code> instance will be destroyed immediately after the <code>'frameError'</code> event is emitted.</p> <h4>Event: 'timeout'<span><a class="mark" href="#http2_event_timeout_1" id="http2_event_timeout_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'timeout'</code> event is emitted after no activity is received for this <code>Http2Stream</code> within the number of milliseconds set using <code>http2stream.setTimeout()</code>.</p> <h4>Event: 'trailers'<span><a class="mark" href="#http2_event_trailers" id="http2_event_trailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'trailers'</code> event is emitted when a block of headers associated with trailing header fields is received. The listener callback is passed the <a href="#http2_headers_object">HTTP/2 Headers Object</a> and flags associated with the headers.</p> <p>Note that this event might not be emitted if <code>http2stream.end()</code> is called before trailers are received and the incoming data is not being read or listened for.</p> <pre><code class="language-js">stream.on('trailers', (headers, flags) => { console.log(headers); }); </code></pre> <h4>Event: 'wantTrailers'<span><a class="mark" href="#http2_event_wanttrailers" id="http2_event_wanttrailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>The <code>'wantTrailers'</code> event is emitted when the <code>Http2Stream</code> has queued the final <code>DATA</code> frame to be sent on a frame and the <code>Http2Stream</code> is ready to send trailing headers. When initiating a request or response, the <code>waitForTrailers</code> option must be set for this event to be emitted.</p> <h4>http2stream.aborted<span><a class="mark" href="#http2_http2stream_aborted" id="http2_http2stream_aborted">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Set to <code>true</code> if the <code>Http2Stream</code> instance was aborted abnormally. When set, the <code>'aborted'</code> event will have been emitted.</p> <h4>http2stream.bufferSize<span><a class="mark" href="#http2_http2stream_buffersize" id="http2_http2stream_buffersize">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>This property shows the number of characters currently buffered to be written. See <a href="#net_socket_buffersize"><code>net.Socket.bufferSize</code></a> for details.</p> <h4>http2stream.close(code[, callback])<span><a class="mark" href="#http2_http2stream_close_code_callback" id="http2_http2stream_close_code_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Unsigned 32-bit integer identifying the error code. <strong>Default:</strong> <code>http2.constants.NGHTTP2_NO_ERROR</code> (<code>0x00</code>).</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An optional function registered to listen for the <code>'close'</code> event.</li> </ul> <p>Closes the <code>Http2Stream</code> instance by sending an <code>RST_STREAM</code> frame to the connected HTTP/2 peer.</p> <h4>http2stream.closed<span><a class="mark" href="#http2_http2stream_closed" id="http2_http2stream_closed">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Set to <code>true</code> if the <code>Http2Stream</code> instance has been closed.</p> <h4>http2stream.destroyed<span><a class="mark" href="#http2_http2stream_destroyed" id="http2_http2stream_destroyed">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Set to <code>true</code> if the <code>Http2Stream</code> instance has been destroyed and is no longer usable.</p> <h4>http2stream.endAfterHeaders<span><a class="mark" href="#http2_http2stream_endafterheaders" id="http2_http2stream_endafterheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.11.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Set the <code>true</code> if the <code>END_STREAM</code> flag was set in the request or response HEADERS frame received, indicating that no additional data should be received and the readable side of the <code>Http2Stream</code> will be closed.</p> <h4>http2stream.pending<span><a class="mark" href="#http2_http2stream_pending" id="http2_http2stream_pending">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Set to <code>true</code> if the <code>Http2Stream</code> instance has not yet been assigned a numeric stream identifier.</p> <h4>http2stream.priority(options)<span><a class="mark" href="#http2_http2stream_priority_options" id="http2_http2stream_priority_options">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and <code>parent</code> identifies a parent Stream, this stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of this stream. <strong>Default:</strong> <code>false</code>.</li> <li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the numeric identifier of a stream this stream is dependent on.</li> <li><code>weight</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the relative dependency of a stream in relation to other streams with the same <code>parent</code>. The value is a number between <code>1</code> and <code>256</code> (inclusive).</li> <li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, changes the priority locally without sending a <code>PRIORITY</code> frame to the connected peer.</li> </ul> </li> </ul> <p>Updates the priority for this <code>Http2Stream</code> instance.</p> <h4>http2stream.rstCode<span><a class="mark" href="#http2_http2stream_rstcode" id="http2_http2stream_rstcode">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Set to the <code>RST_STREAM</code> <a href="#error_codes">error code</a> reported when the <code>Http2Stream</code> is destroyed after either receiving an <code>RST_STREAM</code> frame from the connected peer, calling <code>http2stream.close()</code>, or <code>http2stream.destroy()</code>. Will be <code>undefined</code> if the <code>Http2Stream</code> has not been closed.</p> <h4>http2stream.sentHeaders<span><a class="mark" href="#http2_http2stream_sentheaders" id="http2_http2stream_sentheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.5.0</span> </div> <ul> <li><a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> </ul> <p>An object containing the outbound headers sent for this <code>Http2Stream</code>.</p> <h4>http2stream.sentInfoHeaders<span><a class="mark" href="#http2_http2stream_sentinfoheaders" id="http2_http2stream_sentinfoheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.5.0</span> </div> <ul> <li><a href="#http2_headers_object" class="type"><HTTP/2 Headers Object[]></a></li> </ul> <p>An array of objects containing the outbound informational (additional) headers sent for this <code>Http2Stream</code>.</p> <h4>http2stream.sentTrailers<span><a class="mark" href="#http2_http2stream_senttrailers" id="http2_http2stream_senttrailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v9.5.0</span> </div> <ul> <li><a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> </ul> <p>An object containing the outbound trailers sent for this <code>HttpStream</code>.</p> <h4>http2stream.session<span><a class="mark" href="#http2_http2stream_session" id="http2_http2stream_session">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="#http2_class_http2session" class="type"><Http2Session></a></li> </ul> <p>A reference to the <code>Http2Session</code> instance that owns this <code>Http2Stream</code>. The value will be <code>undefined</code> after the <code>Http2Stream</code> instance is destroyed.</p> <h4>http2stream.setTimeout(msecs, callback)<span><a class="mark" href="#http2_http2stream_settimeout_msecs_callback" id="http2_http2stream_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('http://example.org:8000'); const { NGHTTP2_CANCEL } = http2.constants; const req = client.request({ ':path': '/' }); // Cancel the stream if there's no activity after 5 seconds req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); </code></pre> <h4>http2stream.state<span><a class="mark" href="#http2_http2stream_state" id="http2_http2stream_state">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Provides miscellaneous information about the current state of the <code>Http2Stream</code>.</p> <ul> <li> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>localWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes the connected peer may send for this <code>Http2Stream</code> without receiving a <code>WINDOW_UPDATE</code>.</li> <li><code>state</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A flag indicating the low-level current state of the <code>Http2Stream</code> as determined by <code>nghttp2</code>.</li> <li><code>localClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <code>true</code> if this <code>Http2Stream</code> has been closed locally.</li> <li><code>remoteClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <code>true</code> if this <code>Http2Stream</code> has been closed remotely.</li> <li><code>sumDependencyWeight</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The sum weight of all <code>Http2Stream</code> instances that depend on this <code>Http2Stream</code> as specified using <code>PRIORITY</code> frames.</li> <li><code>weight</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The priority weight of this <code>Http2Stream</code>.</li> </ul> </li> </ul> <p>A current state of this <code>Http2Stream</code>.</p> <h4>http2stream.sendTrailers(headers)<span><a class="mark" href="#http2_http2stream_sendtrailers_headers" id="http2_http2stream_sendtrailers_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>headers</code> <a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> </ul> <p>Sends a trailing <code>HEADERS</code> frame to the connected HTTP/2 peer. This method will cause the <code>Http2Stream</code> to be immediately closed and must only be called after the <code>'wantTrailers'</code> event has been emitted. When sending a request or sending a response, the <code>options.waitForTrailers</code> option must be set in order to keep the <code>Http2Stream</code> open after the final <code>DATA</code> frame so that trailers can be sent.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond(undefined, { waitForTrailers: true }); stream.on('wantTrailers', () => { stream.sendTrailers({ xyz: 'abc' }); }); stream.end('Hello World'); }); </code></pre> <p>The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header fields (e.g. <code>':method'</code>, <code>':path'</code>, etc).</p> <h3>Class: ClientHttp2Stream<span><a class="mark" href="#http2_class_clienthttp2stream" id="http2_class_clienthttp2stream">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends <a href="#http2_class_http2stream" class="type"><Http2Stream></a></li> </ul> <p>The <code>ClientHttp2Stream</code> class is an extension of <code>Http2Stream</code> that is used exclusively on HTTP/2 Clients. <code>Http2Stream</code> instances on the client provide events such as <code>'response'</code> and <code>'push'</code> that are only relevant on the client.</p> <h4>Event: 'continue'<span><a class="mark" href="#http2_event_continue" id="http2_event_continue">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <p>Emitted when the server sends a <code>100 Continue</code> status, usually because the request contained <code>Expect: 100-continue</code>. This is an instruction that the client should send the request body.</p> <h4>Event: 'headers'<span><a class="mark" href="#http2_event_headers" id="http2_event_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'headers'</code> event is emitted when an additional block of headers is received for a stream, such as when a block of <code>1xx</code> informational headers is received. The listener callback is passed the <a href="#http2_headers_object">HTTP/2 Headers Object</a> and flags associated with the headers.</p> <pre><code class="language-js">stream.on('headers', (headers, flags) => { console.log(headers); }); </code></pre> <h4>Event: 'push'<span><a class="mark" href="#http2_event_push" id="http2_event_push">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'push'</code> event is emitted when response headers for a Server Push stream are received. The listener callback is passed the <a href="#http2_headers_object">HTTP/2 Headers Object</a> and flags associated with the headers.</p> <pre><code class="language-js">stream.on('push', (headers, flags) => { console.log(headers); }); </code></pre> <h4>Event: 'response'<span><a class="mark" href="#http2_event_response" id="http2_event_response">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'response'</code> event is emitted when a response <code>HEADERS</code> frame has been received for this stream from the connected HTTP/2 server. The listener is invoked with two arguments: an <code>Object</code> containing the received <a href="#http2_headers_object">HTTP/2 Headers Object</a>, and flags associated with the headers.</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('https://localhost'); const req = client.request({ ':path': '/' }); req.on('response', (headers, flags) => { console.log(headers[':status']); }); </code></pre> <h3>Class: ServerHttp2Stream<span><a class="mark" href="#http2_class_serverhttp2stream" id="http2_class_serverhttp2stream">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends: <a href="#http2_class_http2stream" class="type"><Http2Stream></a></li> </ul> <p>The <code>ServerHttp2Stream</code> class is an extension of <a href="#http2_class_http2stream"><code>Http2Stream</code></a> that is used exclusively on HTTP/2 Servers. <code>Http2Stream</code> instances on the server provide additional methods such as <code>http2stream.pushStream()</code> and <code>http2stream.respond()</code> that are only relevant on the server.</p> <h4>http2stream.additionalHeaders(headers)<span><a class="mark" href="#http2_http2stream_additionalheaders_headers" id="http2_http2stream_additionalheaders_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>headers</code> <a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> </ul> <p>Sends an additional informational <code>HEADERS</code> frame to the connected HTTP/2 peer.</p> <h4>http2stream.headersSent<span><a class="mark" href="#http2_http2stream_headerssent" id="http2_http2stream_headerssent">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>True if headers were sent, false otherwise (read-only).</p> <h4>http2stream.pushAllowed<span><a class="mark" href="#http2_http2stream_pushallowed" id="http2_http2stream_pushallowed">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Read-only property mapped to the <code>SETTINGS_ENABLE_PUSH</code> flag of the remote client's most recent <code>SETTINGS</code> frame. Will be <code>true</code> if the remote peer accepts push streams, <code>false</code> otherwise. Settings are the same for every <code>Http2Stream</code> in the same <code>Http2Session</code>.</p> <h4>http2stream.pushStream(headers[, options], callback)<span><a class="mark" href="#http2_http2stream_pushstream_headers_options_callback" id="http2_http2stream_pushstream_headers_options_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>headers</code> <a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and <code>parent</code> identifies a parent Stream, the created stream is made the sole direct dependency of the parent, with all other existing dependents made a dependent of the newly created stream. <strong>Default:</strong> <code>false</code>.</li> <li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the numeric identifier of a stream the newly created stream is dependent on.</li> </ul> </li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback that is called once the push stream has been initiated.</p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>pushStream</code> <a href="#http2_class_serverhttp2stream" class="type"><ServerHttp2Stream></a> The returned <code>pushStream</code> object.</li> <li><code>headers</code> <a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a> Headers object the <code>pushStream</code> was initiated with.</li> </ul> </li> </ul> <p>Initiates a push stream. The callback is invoked with the new <code>Http2Stream</code> instance created for the push stream passed as the second argument, or an <code>Error</code> passed as the first argument.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond({ ':status': 200 }); stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { if (err) throw err; pushStream.respond({ ':status': 200 }); pushStream.end('some pushed data'); }); stream.end('some data'); }); </code></pre> <p>Setting the weight of a push stream is not allowed in the <code>HEADERS</code> frame. Pass a <code>weight</code> value to <code>http2stream.priority</code> with the <code>silent</code> option set to <code>true</code> to enable server-side bandwidth balancing between concurrent streams.</p> <p>Calling <code>http2stream.pushStream()</code> from within a pushed stream is not permitted and will throw an error.</p> <h4>http2stream.respond([headers[, options]])<span><a class="mark" href="#http2_http2stream_respond_headers_options" id="http2_http2stream_respond_headers_options">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>headers</code> <a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>endStream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Set to <code>true</code> to indicate that the response will not include payload data.</li> <li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the <code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li> </ul> </li> </ul> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond({ ':status': 200 }); stream.end('some data'); }); </code></pre> <p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event will be emitted immediately after queuing the last chunk of payload data to be sent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing header fields to the peer.</p> <p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically close when the final <code>DATA</code> frame is transmitted. User code must call either <code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the <code>Http2Stream</code>.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respond({ ':status': 200 }, { waitForTrailers: true }); stream.on('wantTrailers', () => { stream.sendTrailers({ ABC: 'some value to send' }); }); stream.end('some data'); }); </code></pre> <h4>http2stream.respondWithFD(fd[, headers[, options]])<span><a class="mark" href="#http2_http2stream_respondwithfd_fd_headers_options" id="http2_http2stream_respondwithfd_fd_headers_options">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Any readable file descriptor, not necessarily for a regular file, is supported now.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A readable file descriptor.</li> <li><code>headers</code> <a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>statCheck</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the <code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The offset position at which to begin reading.</li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The amount of data from the fd to send.</li> </ul> </li> </ul> <p>Initiates a response whose data is read from the given file descriptor. No validation is performed on the given file descriptor. If an error occurs while attempting to read data using the file descriptor, the <code>Http2Stream</code> will be closed using an <code>RST_STREAM</code> frame using the standard <code>INTERNAL_ERROR</code> code.</p> <p>When used, the <code>Http2Stream</code> object's <code>Duplex</code> interface will be closed automatically.</p> <pre><code class="language-js">const http2 = require('http2'); const fs = require('fs'); const server = http2.createServer(); server.on('stream', (stream) => { const fd = fs.openSync('/some/file', 'r'); const stat = fs.fstatSync(fd); const headers = { 'content-length': stat.size, 'last-modified': stat.mtime.toUTCString(), 'content-type': 'text/plain' }; stream.respondWithFD(fd, headers); stream.on('close', () => fs.closeSync(fd)); }); </code></pre> <p>The optional <code>options.statCheck</code> function may be specified to give user code an opportunity to set additional content headers based on the <code>fs.Stat</code> details of the given fd. If the <code>statCheck</code> function is provided, the <code>http2stream.respondWithFD()</code> method will perform an <code>fs.fstat()</code> call to collect details on the provided file descriptor.</p> <p>The <code>offset</code> and <code>length</code> options may be used to limit the response to a specific range subset. This can be used, for instance, to support HTTP Range requests.</p> <p>The file descriptor is not closed when the stream is closed, so it will need to be closed manually once it is no longer needed. Note that using the same file descriptor concurrently for multiple streams is not supported and may result in data loss. Re-using a file descriptor after a stream has finished is supported.</p> <p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event will be emitted immediately after queuing the last chunk of payload data to be sent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing header fields to the peer.</p> <p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically close when the final <code>DATA</code> frame is transmitted. User code <em>must</em> call either <code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the <code>Http2Stream</code>.</p> <pre><code class="language-js">const http2 = require('http2'); const fs = require('fs'); const server = http2.createServer(); server.on('stream', (stream) => { const fd = fs.openSync('/some/file', 'r'); const stat = fs.fstatSync(fd); const headers = { 'content-length': stat.size, 'last-modified': stat.mtime.toUTCString(), 'content-type': 'text/plain' }; stream.respondWithFD(fd, headers, { waitForTrailers: true }); stream.on('wantTrailers', () => { stream.sendTrailers({ ABC: 'some value to send' }); }); stream.on('close', () => fs.closeSync(fd)); }); </code></pre> <h4>http2stream.respondWithFile(path[, headers[, options]])<span><a class="mark" href="#http2_http2stream_respondwithfile_path_headers_options" id="http2_http2stream_respondwithfile_path_headers_options">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Any readable file, not necessarily a regular file, is supported now.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>headers</code> <a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>statCheck</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li><code>onError</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback function invoked in the case of an error before send.</li> <li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the <code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The offset position at which to begin reading.</li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The amount of data from the fd to send.</li> </ul> </li> </ul> <p>Sends a regular file as the response. The <code>path</code> must specify a regular file or an <code>'error'</code> event will be emitted on the <code>Http2Stream</code> object.</p> <p>When used, the <code>Http2Stream</code> object's <code>Duplex</code> interface will be closed automatically.</p> <p>The optional <code>options.statCheck</code> function may be specified to give user code an opportunity to set additional content headers based on the <code>fs.Stat</code> details of the given file:</p> <p>If an error occurs while attempting to read the file data, the <code>Http2Stream</code> will be closed using an <code>RST_STREAM</code> frame using the standard <code>INTERNAL_ERROR</code> code. If the <code>onError</code> callback is defined, then it will be called. Otherwise the stream will be destroyed.</p> <p>Example using a file path:</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { function statCheck(stat, headers) { headers['last-modified'] = stat.mtime.toUTCString(); } function onError(err) { if (err.code === 'ENOENT') { stream.respond({ ':status': 404 }); } else { stream.respond({ ':status': 500 }); } stream.end(); } stream.respondWithFile('/some/file', { 'content-type': 'text/plain' }, { statCheck, onError }); }); </code></pre> <p>The <code>options.statCheck</code> function may also be used to cancel the send operation by returning <code>false</code>. For instance, a conditional request may check the stat results to determine if the file has been modified to return an appropriate <code>304</code> response:</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { function statCheck(stat, headers) { // Check the stat here... stream.respond({ ':status': 304 }); return false; // Cancel the send operation } stream.respondWithFile('/some/file', { 'content-type': 'text/plain' }, { statCheck }); }); </code></pre> <p>The <code>content-length</code> header field will be automatically set.</p> <p>The <code>offset</code> and <code>length</code> options may be used to limit the response to a specific range subset. This can be used, for instance, to support HTTP Range requests.</p> <p>The <code>options.onError</code> function may also be used to handle all the errors that could happen before the delivery of the file is initiated. The default behavior is to destroy the stream.</p> <p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event will be emitted immediately after queuing the last chunk of payload data to be sent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing header fields to the peer.</p> <p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically close when the final <code>DATA</code> frame is transmitted. User code must call either <code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the <code>Http2Stream</code>.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream) => { stream.respondWithFile('/some/file', { 'content-type': 'text/plain' }, { waitForTrailers: true }); stream.on('wantTrailers', () => { stream.sendTrailers({ ABC: 'some value to send' }); }); }); </code></pre> <h3>Class: Http2Server<span><a class="mark" href="#http2_class_http2server" id="http2_class_http2server">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends: <a href="#net_class_net_server" class="type"><net.Server></a></li> </ul> <p>Instances of <code>Http2Server</code> are created using the <code>http2.createServer()</code> function. The <code>Http2Server</code> class is not exported directly by the <code>http2</code> module.</p> <h4>Event: 'checkContinue'<span><a class="mark" href="#http2_event_checkcontinue" id="http2_event_checkcontinue">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>request</code> <a href="#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li> <li><code>response</code> <a href="#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <p>If a <a href="#http2_event_request"><code>'request'</code></a> listener is registered or <a href="#http2_http2_createserver_options_onrequesthandler"><code>http2.createServer()</code></a> is supplied a callback function, the <code>'checkContinue'</code> event is emitted each time a request with an HTTP <code>Expect: 100-continue</code> is received. If this event is not listened for, the server will automatically respond with a status <code>100 Continue</code> as appropriate.</p> <p>Handling this event involves calling <a href="#http2_response_writecontinue"><code>response.writeContinue()</code></a> if the client should continue to send the request body, or generating an appropriate HTTP response (e.g. 400 Bad Request) if the client should not continue to send the request body.</p> <p>Note that when this event is emitted and handled, the <a href="#http2_event_request"><code>'request'</code></a> event will not be emitted.</p> <h4>Event: 'request'<span><a class="mark" href="#http2_event_request" id="http2_event_request">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>request</code> <a href="#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li> <li><code>response</code> <a href="#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <p>Emitted each time there is a request. Note that there may be multiple requests per session. See the <a href="#http2_compatibility_api">Compatibility API</a>.</p> <h4>Event: 'session'<span><a class="mark" href="#http2_event_session" id="http2_event_session">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'session'</code> event is emitted when a new <code>Http2Session</code> is created by the <code>Http2Server</code>.</p> <h4>Event: 'sessionError'<span><a class="mark" href="#http2_event_sessionerror" id="http2_event_sessionerror">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'sessionError'</code> event is emitted when an <code>'error'</code> event is emitted by an <code>Http2Session</code> object associated with the <code>Http2Server</code>.</p> <h4>Event: 'stream'<span><a class="mark" href="#http2_event_stream_1" id="http2_event_stream_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'stream'</code> event is emitted when a <code>'stream'</code> event has been emitted by an <code>Http2Session</code> associated with the server.</p> <pre><code class="language-js">const http2 = require('http2'); const { HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE } = http2.constants; const server = http2.createServer(); server.on('stream', (stream, headers, flags) => { const method = headers[HTTP2_HEADER_METHOD]; const path = headers[HTTP2_HEADER_PATH]; // ... stream.respond({ [HTTP2_HEADER_STATUS]: 200, [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' }); stream.write('hello '); stream.end('world'); }); </code></pre> <h4>Event: 'timeout'<span><a class="mark" href="#http2_event_timeout_2" id="http2_event_timeout_2">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for a given number of milliseconds set using <code>http2server.setTimeout()</code>. <strong>Default:</strong> 2 minutes.</p> <h4>server.close([callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1562">[src]</a><span><a class="mark" href="#http2_server_close_callback" id="http2_server_close_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Stops the server from accepting new connections. See <a href="#net_server_close_callback"><code>net.Server.close()</code></a>.</p> <p>Note that this is not analogous to restricting new requests since HTTP/2 connections are persistent. To achieve a similar graceful shutdown behavior, consider also using <a href="#http2_http2session_close_callback"><code>http2session.close()</code></a> on active sessions.</p> <h4>server.setTimeout([msecs][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/_http_server.js#L323">[src]</a><span><a class="mark" href="#http2_server_settimeout_msecs_callback" id="http2_server_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#http2_class_http2server" class="type"><Http2Server></a></li> </ul> <p>Used to set the timeout value for http2 server requests, and sets a callback function that is called when there is no activity on the <code>Http2Server</code> after <code>msecs</code> milliseconds.</p> <p>The given callback is registered as a listener on the <code>'timeout'</code> event.</p> <p>In case of no callback function were assigned, a new <code>ERR_INVALID_CALLBACK</code> error will be thrown.</p> <h3>Class: Http2SecureServer<span><a class="mark" href="#http2_class_http2secureserver" id="http2_class_http2secureserver">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Extends: <a href="#tls_class_tls_server" class="type"><tls.Server></a></li> </ul> <p>Instances of <code>Http2SecureServer</code> are created using the <code>http2.createSecureServer()</code> function. The <code>Http2SecureServer</code> class is not exported directly by the <code>http2</code> module.</p> <h4>Event: 'checkContinue'<span><a class="mark" href="#http2_event_checkcontinue_1" id="http2_event_checkcontinue_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>request</code> <a href="#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li> <li><code>response</code> <a href="#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <p>If a <a href="#http2_event_request"><code>'request'</code></a> listener is registered or <a href="#http2_http2_createsecureserver_options_onrequesthandler"><code>http2.createSecureServer()</code></a> is supplied a callback function, the <code>'checkContinue'</code> event is emitted each time a request with an HTTP <code>Expect: 100-continue</code> is received. If this event is not listened for, the server will automatically respond with a status <code>100 Continue</code> as appropriate.</p> <p>Handling this event involves calling <a href="#http2_response_writecontinue"><code>response.writeContinue()</code></a> if the client should continue to send the request body, or generating an appropriate HTTP response (e.g. 400 Bad Request) if the client should not continue to send the request body.</p> <p>Note that when this event is emitted and handled, the <a href="#http2_event_request"><code>'request'</code></a> event will not be emitted.</p> <h4>Event: 'request'<span><a class="mark" href="#http2_event_request_1" id="http2_event_request_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>request</code> <a href="#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li> <li><code>response</code> <a href="#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <p>Emitted each time there is a request. Note that there may be multiple requests per session. See the <a href="#http2_compatibility_api">Compatibility API</a>.</p> <h4>Event: 'session'<span><a class="mark" href="#http2_event_session_1" id="http2_event_session_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'session'</code> event is emitted when a new <code>Http2Session</code> is created by the <code>Http2SecureServer</code>.</p> <h4>Event: 'sessionError'<span><a class="mark" href="#http2_event_sessionerror_1" id="http2_event_sessionerror_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'sessionError'</code> event is emitted when an <code>'error'</code> event is emitted by an <code>Http2Session</code> object associated with the <code>Http2SecureServer</code>.</p> <h4>Event: 'stream'<span><a class="mark" href="#http2_event_stream_2" id="http2_event_stream_2">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'stream'</code> event is emitted when a <code>'stream'</code> event has been emitted by an <code>Http2Session</code> associated with the server.</p> <pre><code class="language-js">const http2 = require('http2'); const { HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS, HTTP2_HEADER_CONTENT_TYPE } = http2.constants; const options = getOptionsSomehow(); const server = http2.createSecureServer(options); server.on('stream', (stream, headers, flags) => { const method = headers[HTTP2_HEADER_METHOD]; const path = headers[HTTP2_HEADER_PATH]; // ... stream.respond({ [HTTP2_HEADER_STATUS]: 200, [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain' }); stream.write('hello '); stream.end('world'); }); </code></pre> <h4>Event: 'timeout'<span><a class="mark" href="#http2_event_timeout_3" id="http2_event_timeout_3">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for a given number of milliseconds set using <code>http2secureServer.setTimeout()</code>. <strong>Default:</strong> 2 minutes.</p> <h4>Event: 'unknownProtocol'<span><a class="mark" href="#http2_event_unknownprotocol" id="http2_event_unknownprotocol">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'unknownProtocol'</code> event is emitted when a connecting client fails to negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler receives the socket for handling. If no listener is registered for this event, the connection is terminated. A timeout may be specified using the <code>'unknownProtocolTimeout'</code> option passed to <a href="#http2_http2_createsecureserver_options_onrequesthandler"><code>http2.createSecureServer()</code></a>. See the <a href="#http2_compatibility_api">Compatibility API</a>.</p> <h4>server.close([callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1562">[src]</a><span><a class="mark" href="#http2_server_close_callback_1" id="http2_server_close_callback_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Stops the server from accepting new connections. See <a href="#tls_server_close_callback"><code>tls.Server.close()</code></a>.</p> <p>Note that this is not analogous to restricting new requests since HTTP/2 connections are persistent. To achieve a similar graceful shutdown behavior, consider also using <a href="#http2_http2session_close_callback"><code>http2session.close()</code></a> on active sessions.</p> <h4>server.setTimeout([msecs][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/_http_server.js#L323">[src]</a><span><a class="mark" href="#http2_server_settimeout_msecs_callback_1" id="http2_server_settimeout_msecs_callback_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#http2_class_http2secureserver" class="type"><Http2SecureServer></a></li> </ul> <p>Used to set the timeout value for http2 secure server requests, and sets a callback function that is called when there is no activity on the <code>Http2SecureServer</code> after <code>msecs</code> milliseconds.</p> <p>The given callback is registered as a listener on the <code>'timeout'</code> event.</p> <p>In case of no callback function were assigned, a new <code>ERR_INVALID_CALLBACK</code> error will be thrown.</p> <h3>http2.createServer(options[, onRequestHandler])<span><a class="mark" href="#http2_http2_createserver_options_onrequesthandler" id="http2_http2_createserver_options_onrequesthandler">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.24.0</td> <td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr> <tr><td>v10.21.0</td> <td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr> <tr><td>v9.6.0</td> <td><p>Added the <code>Http1IncomingMessage</code> and <code>Http1ServerResponse</code> option.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum dynamic table size for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li> <li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of settings entries per <code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li> <li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum memory that the <code>Http2Session</code> is permitted to use. The value is expressed in terms of number of megabytes, e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>. This is a credit based limit, existing <code>Http2Stream</code>s may cause this limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected while this limit is exceeded. The current number of <code>Http2Stream</code> sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of header entries. The minimum value is <code>4</code>. <strong>Default:</strong> <code>128</code>.</li> <li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of outstanding, unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a <code>'frameError'</code> event being emitted and the stream being closed and destroyed.</li> <li> <p><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Identifies the strategy used for determining the amount of padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong> <code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:</p> <ul> <li><code>http2.constants.PADDING_STRATEGY_NONE</code> - Specifies that no padding is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_MAX</code> - Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_CALLBACK</code> - Specifies that the user provided <code>options.selectPadding()</code> callback is to be used to determine the amount of padding.</li> <li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code> - Will <em>attempt</em> to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will <em>not</em> necessarily be aligned at 8 bytes.</li> </ul> </li> <li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of concurrent streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will be overridden if the remote peer sets its own value for <code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li> <li><code>selectPadding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> When <code>options.paddingStrategy</code> is equal to <code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, provides the callback function used to determine the padding. See <a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a>.</li> <li><code>settings</code> <a href="#http2_settings_object" class="type"><HTTP/2 Settings Object></a> The initial settings to send to the remote peer upon connection.</li> <li><code>Http1IncomingMessage</code> <a href="#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Specifies the <code>IncomingMessage</code> class to used for HTTP/1 fallback. Useful for extending the original <code>http.IncomingMessage</code>. <strong>Default:</strong> <code>http.IncomingMessage</code>.</li> <li><code>Http1ServerResponse</code> <a href="#http_class_http_serverresponse" class="type"><http.ServerResponse></a> Specifies the <code>ServerResponse</code> class to used for HTTP/1 fallback. Useful for extending the original <code>http.ServerResponse</code>. <strong>Default:</strong> <code>http.ServerResponse</code>.</li> <li><code>Http2ServerRequest</code> <a href="#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a> Specifies the <code>Http2ServerRequest</code> class to use. Useful for extending the original <code>Http2ServerRequest</code>. <strong>Default:</strong> <code>Http2ServerRequest</code>.</li> <li><code>Http2ServerResponse</code> <a href="#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a> Specifies the <code>Http2ServerResponse</code> class to use. Useful for extending the original <code>Http2ServerResponse</code>. <strong>Default:</strong> <code>Http2ServerResponse</code>.</li> <li><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies a timeout in milliseconds that a server should wait when an <a href="#http2_event_unknownprotocol"><code>'unknownProtocol'</code></a> is emitted. If the socket has not been destroyed by that time the server will destroy it. <strong>Default:</strong> <code>10000</code>.</li> </ul> </li> <li><code>onRequestHandler</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> See <a href="#http2_compatibility_api">Compatibility API</a></li> <li>Returns: <a href="#http2_class_http2server" class="type"><Http2Server></a></li> </ul> <p>Returns a <code>net.Server</code> instance that creates and manages <code>Http2Session</code> instances.</p> <p>Since there are no browsers known that support <a href="https://http2.github.io/faq/#does-http2-require-encryption">unencrypted HTTP/2</a>, the use of <a href="#http2_http2_createsecureserver_options_onrequesthandler"><code>http2.createSecureServer()</code></a> is necessary when communicating with browser clients.</p> <pre><code class="language-js">const http2 = require('http2'); // Create an unencrypted HTTP/2 server. // Since there are no browsers known that support // unencrypted HTTP/2, the use of `http2.createSecureServer()` // is necessary when communicating with browser clients. const server = http2.createServer(); server.on('stream', (stream, headers) => { stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.end('<h1>Hello World</h1>'); }); server.listen(80); </code></pre> <h3>http2.createSecureServer(options[, onRequestHandler])<span><a class="mark" href="#http2_http2_createsecureserver_options_onrequesthandler" id="http2_http2_createsecureserver_options_onrequesthandler">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.24.0</td> <td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr> <tr><td>v10.21.0</td> <td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr> <tr><td>v10.12.0</td> <td><p>Added the <code>origins</code> option to automatically send an <code>ORIGIN</code> frame on <code>Http2Session</code> startup.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>allowHTTP1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to <code>true</code>. See the <a href="#http2_event_unknownprotocol"><code>'unknownProtocol'</code></a> event. See <a href="#http2_alpn_negotiation">ALPN negotiation</a>. <strong>Default:</strong> <code>false</code>.</li> <li><code>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum dynamic table size for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li> <li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of settings entries per <code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li> <li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum memory that the <code>Http2Session</code> is permitted to use. The value is expressed in terms of number of megabytes, e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>. This is a credit based limit, existing <code>Http2Stream</code>s may cause this limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected while this limit is exceeded. The current number of <code>Http2Stream</code> sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of header entries. The minimum value is <code>4</code>. <strong>Default:</strong> <code>128</code>.</li> <li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of outstanding, unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a <code>'frameError'</code> event being emitted and the stream being closed and destroyed.</li> <li> <p><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Identifies the strategy used for determining the amount of padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong> <code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:</p> <ul> <li><code>http2.constants.PADDING_STRATEGY_NONE</code> - Specifies that no padding is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_MAX</code> - Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_CALLBACK</code> - Specifies that the user provided <code>options.selectPadding()</code> callback is to be used to determine the amount of padding.</li> <li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code> - Will <em>attempt</em> to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will <em>not</em> necessarily be aligned at 8 bytes.</li> </ul> </li> <li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of concurrent streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will be overridden if the remote peer sets its own value for <code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li> <li><code>selectPadding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> When <code>options.paddingStrategy</code> is equal to <code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, provides the callback function used to determine the padding. See <a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a>.</li> <li><code>settings</code> <a href="#http2_settings_object" class="type"><HTTP/2 Settings Object></a> The initial settings to send to the remote peer upon connection.</li> <li>...: Any <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a> options can be provided. For servers, the identity options (<code>pfx</code> or <code>key</code>/<code>cert</code>) are usually required.</li> <li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array of origin strings to send within an <code>ORIGIN</code> frame immediately following creation of a new server <code>Http2Session</code>.</li> <li><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies a timeout in milliseconds that a server should wait when an <a href="#http2_event_unknownprotocol"><code>'unknownProtocol'</code></a> event is emitted. If the socket has not been destroyed by that time the server will destroy it. <strong>Default:</strong> <code>10000</code>.</li> </ul> </li> <li><code>onRequestHandler</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> See <a href="#http2_compatibility_api">Compatibility API</a></li> <li>Returns: <a href="#http2_class_http2secureserver" class="type"><Http2SecureServer></a></li> </ul> <p>Returns a <code>tls.Server</code> instance that creates and manages <code>Http2Session</code> instances.</p> <pre><code class="language-js">const http2 = require('http2'); const fs = require('fs'); const options = { key: fs.readFileSync('server-key.pem'), cert: fs.readFileSync('server-cert.pem') }; // Create a secure HTTP/2 server const server = http2.createSecureServer(options); server.on('stream', (stream, headers) => { stream.respond({ 'content-type': 'text/html', ':status': 200 }); stream.end('<h1>Hello World</h1>'); }); server.listen(80); </code></pre> <h3>http2.connect(authority[, options][, listener])<span><a class="mark" href="#http2_http2_connect_authority_options_listener" id="http2_http2_connect_authority_options_listener">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.24.0</td> <td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr> <tr><td>v10.21.0</td> <td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr> <tr><td>v8.9.3</td> <td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>authority</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum dynamic table size for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li> <li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of settings entries per <code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li> <li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum memory that the <code>Http2Session</code> is permitted to use. The value is expressed in terms of number of megabytes, e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>. This is a credit based limit, existing <code>Http2Stream</code>s may cause this limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected while this limit is exceeded. The current number of <code>Http2Stream</code> sessions, the current memory use of the header compression tables, current data queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of header entries. The minimum value is <code>1</code>. <strong>Default:</strong> <code>128</code>.</li> <li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of outstanding, unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li> <li><code>maxReservedRemoteStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of reserved push streams the client will accept at any given time. Once the current number of currently reserved push streams exceeds reaches this limit, new push streams sent by the server will be automatically rejected.</li> <li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum allowed size for a serialized, compressed block of headers. Attempts to send headers that exceed this limit will result in a <code>'frameError'</code> event being emitted and the stream being closed and destroyed.</li> <li> <p><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Identifies the strategy used for determining the amount of padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong> <code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:</p> <ul> <li><code>http2.constants.PADDING_STRATEGY_NONE</code> - Specifies that no padding is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_MAX</code> - Specifies that the maximum amount of padding, as determined by the internal implementation, is to be applied.</li> <li><code>http2.constants.PADDING_STRATEGY_CALLBACK</code> - Specifies that the user provided <code>options.selectPadding()</code> callback is to be used to determine the amount of padding.</li> <li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code> - Will <em>attempt</em> to apply enough padding to ensure that the total frame length, including the 9-byte header, is a multiple of 8. For each frame, however, there is a maximum allowed number of padding bytes that is determined by current flow control state and settings. If this maximum is less than the calculated amount needed to ensure alignment, the maximum will be used and the total frame length will <em>not</em> necessarily be aligned at 8 bytes.</li> </ul> </li> <li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets the maximum number of concurrent streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will be overridden if the remote peer sets its own value for <code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li> <li><code>selectPadding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> When <code>options.paddingStrategy</code> is equal to <code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, provides the callback function used to determine the padding. See <a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a>.</li> <li><code>settings</code> <a href="#http2_settings_object" class="type"><HTTP/2 Settings Object></a> The initial settings to send to the remote peer upon connection.</li> <li><code>createConnection</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An optional callback that receives the <code>URL</code> instance passed to <code>connect</code> and the <code>options</code> object, and returns any <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream that is to be used as the connection for this session.</li> <li>...: Any <a href="#net_net_connect"><code>net.connect()</code></a> or <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> options can be provided.</li> <li><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies a timeout in milliseconds that a server should wait when an <a href="#http2_event_unknownprotocol"><code>'unknownProtocol'</code></a> event is emitted. If the socket has not been destroyed by that time the server will destroy it. <strong>Default:</strong> <code>10000</code>.</li> </ul> </li> <li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#http2_class_clienthttp2session" class="type"><ClientHttp2Session></a></li> </ul> <p>Returns a <code>ClientHttp2Session</code> instance.</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('https://localhost:1234'); /* Use the client */ client.close(); </code></pre> <h3>http2.constants<span><a class="mark" href="#http2_http2_constants" id="http2_http2_constants">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <h4>Error Codes for RST_STREAM and GOAWAY<span><a class="mark" href="#http2_error_codes_for_rst_stream_and_goaway" id="http2_error_codes_for_rst_stream_and_goaway">#</a></span></h4> <p><a id="error_codes"></a></p> <table><thead><tr><th>Value</th><th>Name</th><th>Constant</th></tr></thead><tbody><tr><td><code>0x00</code></td><td>No Error</td><td><code>http2.constants.NGHTTP2_NO_ERROR</code></td></tr><tr><td><code>0x01</code></td><td>Protocol Error</td><td><code>http2.constants.NGHTTP2_PROTOCOL_ERROR</code></td></tr><tr><td><code>0x02</code></td><td>Internal Error</td><td><code>http2.constants.NGHTTP2_INTERNAL_ERROR</code></td></tr><tr><td><code>0x03</code></td><td>Flow Control Error</td><td><code>http2.constants.NGHTTP2_FLOW_CONTROL_ERROR</code></td></tr><tr><td><code>0x04</code></td><td>Settings Timeout</td><td><code>http2.constants.NGHTTP2_SETTINGS_TIMEOUT</code></td></tr><tr><td><code>0x05</code></td><td>Stream Closed</td><td><code>http2.constants.NGHTTP2_STREAM_CLOSED</code></td></tr><tr><td><code>0x06</code></td><td>Frame Size Error</td><td><code>http2.constants.NGHTTP2_FRAME_SIZE_ERROR</code></td></tr><tr><td><code>0x07</code></td><td>Refused Stream</td><td><code>http2.constants.NGHTTP2_REFUSED_STREAM</code></td></tr><tr><td><code>0x08</code></td><td>Cancel</td><td><code>http2.constants.NGHTTP2_CANCEL</code></td></tr><tr><td><code>0x09</code></td><td>Compression Error</td><td><code>http2.constants.NGHTTP2_COMPRESSION_ERROR</code></td></tr><tr><td><code>0x0a</code></td><td>Connect Error</td><td><code>http2.constants.NGHTTP2_CONNECT_ERROR</code></td></tr><tr><td><code>0x0b</code></td><td>Enhance Your Calm</td><td><code>http2.constants.NGHTTP2_ENHANCE_YOUR_CALM</code></td></tr><tr><td><code>0x0c</code></td><td>Inadequate Security</td><td><code>http2.constants.NGHTTP2_INADEQUATE_SECURITY</code></td></tr><tr><td><code>0x0d</code></td><td>HTTP/1.1 Required</td><td><code>http2.constants.NGHTTP2_HTTP_1_1_REQUIRED</code></td></tr></tbody></table> <p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for a given number of milliseconds set using <code>http2server.setTimeout()</code>.</p> <h3>http2.getDefaultSettings()<span><a class="mark" href="#http2_http2_getdefaultsettings" id="http2_http2_getdefaultsettings">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Returns: <a href="#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> </ul> <p>Returns an object containing the default settings for an <code>Http2Session</code> instance. This method returns a new object instance every time it is called so instances returned may be safely modified for use.</p> <h3>http2.getPackedSettings(settings)<span><a class="mark" href="#http2_http2_getpackedsettings_settings" id="http2_http2_getpackedsettings_settings">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>settings</code> <a href="#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Returns a <code>Buffer</code> instance containing serialized representation of the given HTTP/2 settings as specified in the <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> specification. This is intended for use with the <code>HTTP2-Settings</code> header field.</p> <pre><code class="language-js">const http2 = require('http2'); const packed = http2.getPackedSettings({ enablePush: false }); console.log(packed.toString('base64')); // Prints: AAIAAAAA </code></pre> <h3>http2.getUnpackedSettings(buf)<span><a class="mark" href="#http2_http2_getunpackedsettings_buf" id="http2_http2_getunpackedsettings_buf">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>buf</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> The packed settings.</li> <li>Returns: <a href="#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li> </ul> <p>Returns a <a href="#http2_settings_object">HTTP/2 Settings Object</a> containing the deserialized settings from the given <code>Buffer</code> as generated by <code>http2.getPackedSettings()</code>.</p> <h3>Headers Object<span><a class="mark" href="#http2_headers_object" id="http2_headers_object">#</a></span></h3> <p>Headers are represented as own-properties on JavaScript objects. The property keys will be serialized to lower-case. Property values should be strings (if they are not they will be coerced to strings) or an <code>Array</code> of strings (in order to send more than one value per header field).</p> <pre><code class="language-js">const headers = { ':status': '200', 'content-type': 'text-plain', 'ABC': ['has', 'more', 'than', 'one', 'value'] }; stream.respond(headers); </code></pre> <p>Header objects passed to callback functions will have a <code>null</code> prototype. This means that normal JavaScript object methods such as <code>Object.prototype.toString()</code> and <code>Object.prototype.hasOwnProperty()</code> will not work.</p> <p>For incoming headers:</p> <ul> <li>The <code>:status</code> header is converted to <code>number</code>.</li> <li>Duplicates of <code>:status</code>, <code>:method</code>, <code>:authority</code>, <code>:scheme</code>, <code>:path</code>, <code>:protocol</code>, <code>age</code>, <code>authorization</code>, <code>access-control-allow-credentials</code>, <code>access-control-max-age</code>, <code>access-control-request-method</code>, <code>content-encoding</code>, <code>content-language</code>, <code>content-length</code>, <code>content-location</code>, <code>content-md5</code>, <code>content-range</code>, <code>content-type</code>, <code>date</code>, <code>dnt</code>, <code>etag</code>, <code>expires</code>, <code>from</code>, <code>if-match</code>, <code>if-modified-since</code>, <code>if-none-match</code>, <code>if-range</code>, <code>if-unmodified-since</code>, <code>last-modified</code>, <code>location</code>, <code>max-forwards</code>, <code>proxy-authorization</code>, <code>range</code>, <code>referer</code>,<code>retry-after</code>, <code>tk</code>, <code>upgrade-insecure-requests</code>, <code>user-agent</code> or <code>x-content-type-options</code> are discarded.</li> <li><code>set-cookie</code> is always an array. Duplicates are added to the array.</li> <li>For duplicate <code>cookie</code> headers, the values are joined together with '; '.</li> <li>For all other headers, the values are joined together with ', '.</li> </ul> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer(); server.on('stream', (stream, headers) => { console.log(headers[':path']); console.log(headers.ABC); }); </code></pre> <h3>Settings Object<span><a class="mark" href="#http2_settings_object" id="http2_settings_object">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.9.3</td> <td><p>The <code>maxHeaderListSize</code> setting is now strictly enforced.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <p>The <code>http2.getDefaultSettings()</code>, <code>http2.getPackedSettings()</code>, <code>http2.createServer()</code>, <code>http2.createSecureServer()</code>, <code>http2session.settings()</code>, <code>http2session.localSettings</code>, and <code>http2session.remoteSettings</code> APIs either return or receive as input an object that defines configuration settings for an <code>Http2Session</code> object. These objects are ordinary JavaScript objects containing the following properties.</p> <ul> <li><code>headerTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the maximum number of bytes used for header compression. The minimum allowed value is 0. The maximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>4,096 octets</code>.</li> <li><code>enablePush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Specifies <code>true</code> if HTTP/2 Push Streams are to be permitted on the <code>Http2Session</code> instances.</li> <li><code>initialWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the <em>senders</em> initial window size for stream-level flow control. The minimum allowed value is 0. The maximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>65,535 bytes</code>.</li> <li><code>maxFrameSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the size of the largest frame payload. The minimum allowed value is 16,384. The maximum allowed value is 2<sup>24</sup>-1. <strong>Default:</strong> <code>16,384 bytes</code>.</li> <li><code>maxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the maximum number of concurrent streams permitted on an <code>Http2Session</code>. There is no default value which implies, at least theoretically, 2<sup>31</sup>-1 streams may be open concurrently at any given time in an <code>Http2Session</code>. The minimum value is 0. The maximum allowed value is 2<sup>31</sup>-1.</li> <li><code>maxHeaderListSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the maximum size (uncompressed octets) of header list that will be accepted. The minimum allowed value is 0. The maximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>65535</code>.</li> <li><code>enableConnectProtocol</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Specifies <code>true</code> if the "Extended Connect Protocol" defined by <a href="https://tools.ietf.org/html/rfc8441">RFC 8441</a> is to be enabled. This setting is only meaningful if sent by the server. Once the <code>enableConnectProtocol</code> setting has been enabled for a given <code>Http2Session</code>, it cannot be disabled.</li> </ul> <p>All additional properties on the settings object are ignored.</p> <h3>Using <code>options.selectPadding()</code><span><a class="mark" href="#http2_using_options_selectpadding" id="http2_using_options_selectpadding">#</a></span></h3> <p>When <code>options.paddingStrategy</code> is equal to <code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, the HTTP/2 implementation will consult the <code>options.selectPadding()</code> callback function, if provided, to determine the specific amount of padding to use per <code>HEADERS</code> and <code>DATA</code> frame.</p> <p>The <code>options.selectPadding()</code> function receives two numeric arguments, <code>frameLen</code> and <code>maxFrameLen</code> and must return a number <code>N</code> such that <code>frameLen <= N <= maxFrameLen</code>.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer({ paddingStrategy: http2.constants.PADDING_STRATEGY_CALLBACK, selectPadding(frameLen, maxFrameLen) { return maxFrameLen; } }); </code></pre> <p>The <code>options.selectPadding()</code> function is invoked once for <em>every</em> <code>HEADERS</code> and <code>DATA</code> frame. This has a definite noticeable impact on performance.</p> <h3>Error Handling<span><a class="mark" href="#http2_error_handling" id="http2_error_handling">#</a></span></h3> <p>There are several types of error conditions that may arise when using the <code>http2</code> module:</p> <p>Validation errors occur when an incorrect argument, option, or setting value is passed in. These will always be reported by a synchronous <code>throw</code>.</p> <p>State errors occur when an action is attempted at an incorrect time (for instance, attempting to send data on a stream after it has closed). These will be reported using either a synchronous <code>throw</code> or via an <code>'error'</code> event on the <code>Http2Stream</code>, <code>Http2Session</code> or HTTP/2 Server objects, depending on where and when the error occurs.</p> <p>Internal errors occur when an HTTP/2 session fails unexpectedly. These will be reported via an <code>'error'</code> event on the <code>Http2Session</code> or HTTP/2 Server objects.</p> <p>Protocol errors occur when various HTTP/2 protocol constraints are violated. These will be reported using either a synchronous <code>throw</code> or via an <code>'error'</code> event on the <code>Http2Stream</code>, <code>Http2Session</code> or HTTP/2 Server objects, depending on where and when the error occurs.</p> <h3>Invalid character handling in header names and values<span><a class="mark" href="#http2_invalid_character_handling_in_header_names_and_values" id="http2_invalid_character_handling_in_header_names_and_values">#</a></span></h3> <p>The HTTP/2 implementation applies stricter handling of invalid characters in HTTP header names and values than the HTTP/1 implementation.</p> <p>Header field names are <em>case-insensitive</em> and are transmitted over the wire strictly as lower-case strings. The API provided by Node.js allows header names to be set as mixed-case strings (e.g. <code>Content-Type</code>) but will convert those to lower-case (e.g. <code>content-type</code>) upon transmission.</p> <p>Header field-names <em>must only</em> contain one or more of the following ASCII characters: <code>a</code>-<code>z</code>, <code>A</code>-<code>Z</code>, <code>0</code>-<code>9</code>, <code>!</code>, <code>#</code>, <code>$</code>, <code>%</code>, <code>&</code>, <code>'</code>, <code>*</code>, <code>+</code>, <code>-</code>, <code>.</code>, <code>^</code>, <code>_</code>, <code>`</code> (backtick), <code>|</code>, and <code>~</code>.</p> <p>Using invalid characters within an HTTP header field name will cause the stream to be closed with a protocol error being reported.</p> <p>Header field values are handled with more leniency but <em>should</em> not contain new-line or carriage return characters and <em>should</em> be limited to US-ASCII characters, per the requirements of the HTTP specification.</p> <h3>Push streams on the client<span><a class="mark" href="#http2_push_streams_on_the_client" id="http2_push_streams_on_the_client">#</a></span></h3> <p>To receive pushed streams on the client, set a listener for the <code>'stream'</code> event on the <code>ClientHttp2Session</code>:</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('http://localhost'); client.on('stream', (pushedStream, requestHeaders) => { pushedStream.on('push', (responseHeaders) => { // process response headers }); pushedStream.on('data', (chunk) => { /* handle pushed data */ }); }); const req = client.request({ ':path': '/' }); </code></pre> <h3>Supporting the CONNECT method<span><a class="mark" href="#http2_supporting_the_connect_method" id="http2_supporting_the_connect_method">#</a></span></h3> <p>The <code>CONNECT</code> method is used to allow an HTTP/2 server to be used as a proxy for TCP/IP connections.</p> <p>A simple TCP Server:</p> <pre><code class="language-js">const net = require('net'); const server = net.createServer((socket) => { let name = ''; socket.setEncoding('utf8'); socket.on('data', (chunk) => name += chunk); socket.on('end', () => socket.end(`hello ${name}`)); }); server.listen(8000); </code></pre> <p>An HTTP/2 CONNECT proxy:</p> <pre><code class="language-js">const http2 = require('http2'); const { NGHTTP2_REFUSED_STREAM } = http2.constants; const net = require('net'); const proxy = http2.createServer(); proxy.on('stream', (stream, headers) => { if (headers[':method'] !== 'CONNECT') { // Only accept CONNECT requests stream.close(NGHTTP2_REFUSED_STREAM); return; } const auth = new URL(`tcp://${headers[':authority']}`); // It's a very good idea to verify that hostname and port are // things this proxy should be connecting to. const socket = net.connect(auth.port, auth.hostname, () => { stream.respond(); socket.pipe(stream); stream.pipe(socket); }); socket.on('error', (error) => { stream.close(http2.constants.NGHTTP2_CONNECT_ERROR); }); }); proxy.listen(8001); </code></pre> <p>An HTTP/2 CONNECT client:</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('http://localhost:8001'); // Must not specify the ':path' and ':scheme' headers // for CONNECT requests or an error will be thrown. const req = client.request({ ':method': 'CONNECT', ':authority': `localhost:${port}` }); req.on('response', (headers) => { console.log(headers[http2.constants.HTTP2_HEADER_STATUS]); }); let data = ''; req.setEncoding('utf8'); req.on('data', (chunk) => data += chunk); req.on('end', () => { console.log(`The server says: ${data}`); client.close(); }); req.end('Jane'); </code></pre> <h3>The Extended CONNECT Protocol<span><a class="mark" href="#http2_the_extended_connect_protocol" id="http2_the_extended_connect_protocol">#</a></span></h3> <p><a href="https://tools.ietf.org/html/rfc8441">RFC 8441</a> defines an "Extended CONNECT Protocol" extension to HTTP/2 that may be used to bootstrap the use of an <code>Http2Stream</code> using the <code>CONNECT</code> method as a tunnel for other communication protocols (such as WebSockets).</p> <p>The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using the <code>enableConnectProtocol</code> setting:</p> <pre><code class="language-js">const http2 = require('http2'); const settings = { enableConnectProtocol: true }; const server = http2.createServer({ settings }); </code></pre> <p>Once the client receives the <code>SETTINGS</code> frame from the server indicating that the extended CONNECT may be used, it may send <code>CONNECT</code> requests that use the <code>':protocol'</code> HTTP/2 pseudo-header:</p> <pre><code class="language-js">const http2 = require('http2'); const client = http2.connect('http://localhost:8080'); client.on('remoteSettings', (settings) => { if (settings.enableConnectProtocol) { const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' }); // ... } }); </code></pre> <h2>Compatibility API<span><a class="mark" href="#http2_compatibility_api" id="http2_compatibility_api">#</a></span></h2> <p>The Compatibility API has the goal of providing a similar developer experience of HTTP/1 when using HTTP/2, making it possible to develop applications that support both <a href="http.html">HTTP/1</a> and HTTP/2. This API targets only the <strong>public API</strong> of the <a href="http.html">HTTP/1</a>. However many modules use internal methods or state, and those <em>are not supported</em> as it is a completely different implementation.</p> <p>The following example creates an HTTP/2 server using the compatibility API:</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); }); </code></pre> <p>In order to create a mixed <a href="https.html">HTTPS</a> and HTTP/2 server, refer to the <a href="#http2_alpn_negotiation">ALPN negotiation</a> section. Upgrading from non-tls HTTP/1 servers is not supported.</p> <p>The HTTP/2 compatibility API is composed of <a href=""><code>Http2ServerRequest</code></a> and <a href=""><code>Http2ServerResponse</code></a>. They aim at API compatibility with HTTP/1, but they do not hide the differences between the protocols. As an example, the status message for HTTP codes is ignored.</p> <h3>ALPN negotiation<span><a class="mark" href="#http2_alpn_negotiation" id="http2_alpn_negotiation">#</a></span></h3> <p>ALPN negotiation allows supporting both <a href="https.html">HTTPS</a> and HTTP/2 over the same socket. The <code>req</code> and <code>res</code> objects can be either HTTP/1 or HTTP/2, and an application <strong>must</strong> restrict itself to the public API of <a href="http.html">HTTP/1</a>, and detect if it is possible to use the more advanced features of HTTP/2.</p> <p>The following example creates a server that supports both protocols:</p> <pre><code class="language-js">const { createSecureServer } = require('http2'); const { readFileSync } = require('fs'); const cert = readFileSync('./cert.pem'); const key = readFileSync('./key.pem'); const server = createSecureServer( { cert, key, allowHTTP1: true }, onRequest ).listen(4443); function onRequest(req, res) { // detects if it is a HTTPS request or HTTP/2 const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ? req.stream.session : req; res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ alpnProtocol, httpVersion: req.httpVersion })); } </code></pre> <p>The <code>'request'</code> event works identically on both <a href="https.html">HTTPS</a> and HTTP/2.</p> <h3>Class: http2.Http2ServerRequest<span><a class="mark" href="#http2_class_http2_http2serverrequest" id="http2_class_http2_http2serverrequest">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>A <code>Http2ServerRequest</code> object is created by <a href="#http2_class_http2server"><code>http2.Server</code></a> or <a href="#http2_class_http2secureserver"><code>http2.SecureServer</code></a> and passed as the first argument to the <a href="#http2_event_request"><code>'request'</code></a> event. It may be used to access a request status, headers, and data.</p> <p>It implements the <a href="#stream_class_stream_readable">Readable Stream</a> interface, as well as the following additional events, methods, and properties.</p> <h4>Event: 'aborted'<span><a class="mark" href="#http2_event_aborted_1" id="http2_event_aborted_1">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>The <code>'aborted'</code> event is emitted whenever a <code>Http2ServerRequest</code> instance is abnormally aborted in mid-communication.</p> <p>The <code>'aborted'</code> event will only be emitted if the <code>Http2ServerRequest</code> writable side has not been ended.</p> <h4>Event: 'close'<span><a class="mark" href="#http2_event_close_2" id="http2_event_close_2">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Indicates that the underlying <a href="#http2_class_http2stream"><code>Http2Stream</code></a> was closed. Just like <code>'end'</code>, this event occurs only once per response.</p> <h4>request.aborted<span><a class="mark" href="#http2_request_aborted" id="http2_request_aborted">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.1.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>request.aborted</code> property will be <code>true</code> if the request has been aborted.</p> <h4>request.authority<span><a class="mark" href="#http2_request_authority" id="http2_request_authority">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The request authority pseudo header field. It can also be accessed via <code>req.headers[':authority']</code>.</p> <h4>request.destroy([error])<span><a class="mark" href="#http2_request_destroy_error" id="http2_request_destroy_error">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Calls <code>destroy()</code> on the <a href="#http2_class_http2stream"><code>Http2Stream</code></a> that received the <a href="#http2_class_http2_http2serverrequest"><code>Http2ServerRequest</code></a>. If <code>error</code> is provided, an <code>'error'</code> event is emitted and <code>error</code> is passed as an argument to any listeners on the event.</p> <p>It does nothing if the stream was already destroyed.</p> <h4>request.headers<span><a class="mark" href="#http2_request_headers" id="http2_request_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The request/response headers object.</p> <p>Key-value pairs of header names and values. Header names are lower-cased.</p> <pre><code class="language-js">// Prints something like: // // { 'user-agent': 'curl/7.22.0', // host: '127.0.0.1:8000', // accept: '*/*' } console.log(request.headers); </code></pre> <p>See <a href="#http2_headers_object">HTTP/2 Headers Object</a>.</p> <p>In HTTP/2, the request path, hostname, protocol, and method are represented as special headers prefixed with the <code>:</code> character (e.g. <code>':path'</code>). These special headers will be included in the <code>request.headers</code> object. Care must be taken not to inadvertently modify these special headers or errors may occur. For instance, removing all headers from the request will cause errors to occur:</p> <pre><code class="language-js">removeAllHeaders(request.headers); assert(request.url); // Fails because the :path header has been removed </code></pre> <h4>request.httpVersion<span><a class="mark" href="#http2_request_httpversion" id="http2_request_httpversion">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server. Returns <code>'2.0'</code>.</p> <p>Also <code>message.httpVersionMajor</code> is the first integer and <code>message.httpVersionMinor</code> is the second.</p> <h4>request.method<span><a class="mark" href="#http2_request_method" id="http2_request_method">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The request method as a string. Read-only. Examples: <code>'GET'</code>, <code>'DELETE'</code>.</p> <h4>request.rawHeaders<span><a class="mark" href="#http2_request_rawheaders" id="http2_request_rawheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The raw request/response headers list exactly as they were received.</p> <p>Note that the keys and values are in the same list. It is <em>not</em> a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.</p> <p>Header names are not lowercased, and duplicates are not merged.</p> <pre><code class="language-js">// Prints something like: // // [ 'user-agent', // 'this is invalid because there can be only one', // 'User-Agent', // 'curl/7.22.0', // 'Host', // '127.0.0.1:8000', // 'ACCEPT', // '*/*' ] console.log(request.rawHeaders); </code></pre> <h4>request.rawTrailers<span><a class="mark" href="#http2_request_rawtrailers" id="http2_request_rawtrailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The raw request/response trailer keys and values exactly as they were received. Only populated at the <code>'end'</code> event.</p> <h4>request.scheme<span><a class="mark" href="#http2_request_scheme" id="http2_request_scheme">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The request scheme pseudo header field indicating the scheme portion of the target URL.</p> <h4>request.setTimeout(msecs, callback)<span><a class="mark" href="#http2_request_settimeout_msecs_callback" id="http2_request_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li> </ul> <p>Sets the <a href=""><code>Http2Stream</code></a>'s timeout value to <code>msecs</code>. If a callback is provided, then it is added as a listener on the <code>'timeout'</code> event on the response object.</p> <p>If no <code>'timeout'</code> listener is added to the request, the response, or the server, then <a href=""><code>Http2Stream</code></a>s are destroyed when they time out. If a handler is assigned to the request, the response, or the server's <code>'timeout'</code> events, timed out sockets must be handled explicitly.</p> <h4>request.socket<span><a class="mark" href="#http2_request_socket" id="http2_request_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="#net_class_net_socket" class="type"><net.Socket></a> | <a href="#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li> </ul> <p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but applies getters, setters, and methods based on HTTP/2 logic.</p> <p><code>destroyed</code>, <code>readable</code>, and <code>writable</code> properties will be retrieved from and set on <code>request.stream</code>.</p> <p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>on</code> and <code>once</code> methods will be called on <code>request.stream</code>.</p> <p><code>setTimeout</code> method will be called on <code>request.stream.session</code>.</p> <p><code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw an error with code <code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href="#http2_http2session_and_sockets"><code>Http2Session</code> and Sockets</a> for more information.</p> <p>All other interactions will be routed directly to the socket. With TLS support, use <a href="#tls_tlssocket_getpeercertificate_detailed"><code>request.socket.getPeerCertificate()</code></a> to obtain the client's authentication details.</p> <h4>request.stream<span><a class="mark" href="#http2_request_stream" id="http2_request_stream">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="#http2_class_http2stream" class="type"><Http2Stream></a></li> </ul> <p>The <a href="#http2_class_http2stream"><code>Http2Stream</code></a> object backing the request.</p> <h4>request.trailers<span><a class="mark" href="#http2_request_trailers" id="http2_request_trailers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The request/response trailers object. Only populated at the <code>'end'</code> event.</p> <h4>request.url<span><a class="mark" href="#http2_request_url" id="http2_request_url">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:</p> <pre><code class="language-txt">GET /status?name=ryan HTTP/1.1\r\n Accept: text/plain\r\n \r\n </code></pre> <p>Then <code>request.url</code> will be:</p> <!-- eslint-disable semi --> <pre><code class="language-js">'/status?name=ryan' </code></pre> <p>To parse the url into its parts <code>require('url').parse(request.url)</code> can be used:</p> <pre><code class="language-txt">$ node > require('url').parse('/status?name=ryan') Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?name=ryan', query: 'name=ryan', pathname: '/status', path: '/status?name=ryan', href: '/status?name=ryan' } </code></pre> <p>To extract the parameters from the query string, the <code>require('querystring').parse</code> function can be used, or <code>true</code> can be passed as the second argument to <code>require('url').parse</code>.</p> <pre><code class="language-txt">$ node > require('url').parse('/status?name=ryan', true) Url { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: '?name=ryan', query: { name: 'ryan' }, pathname: '/status', path: '/status?name=ryan', href: '/status?name=ryan' } </code></pre> <h3>Class: http2.Http2ServerResponse<span><a class="mark" href="#http2_class_http2_http2serverresponse" id="http2_class_http2_http2serverresponse">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the <a href="#http2_event_request"><code>'request'</code></a> event.</p> <p>The response inherits from <a href="#stream_stream">Stream</a>, and additionally implements the following:</p> <h4>Event: 'close'<span><a class="mark" href="#http2_event_close_3" id="http2_event_close_3">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Indicates that the underlying <a href=""><code>Http2Stream</code></a> was terminated before <a href="#http2_response_end_data_encoding_callback"><code>response.end()</code></a> was called or able to flush.</p> <h4>Event: 'finish'<span><a class="mark" href="#http2_event_finish" id="http2_event_finish">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Emitted when the response has been sent. More specifically, this event is emitted when the last segment of the response headers and body have been handed off to the HTTP/2 multiplexing for transmission over the network. It does not imply that the client has received anything yet.</p> <p>After this event, no more events will be emitted on the response object.</p> <h4>response.addTrailers(headers)<span><a class="mark" href="#http2_response_addtrailers_headers" id="http2_response_addtrailers_headers">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>This method adds HTTP trailing headers (a header but at the end of the message) to the response.</p> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <h4>response.connection<span><a class="mark" href="#http2_response_connection" id="http2_response_connection">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="#net_class_net_socket" class="type"><net.Socket></a> | <a href="#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li> </ul> <p>See <a href="#http2_response_socket"><code>response.socket</code></a>.</p> <h4>response.end([data][, encoding][, callback])<span><a class="mark" href="#http2_response_end_data_encoding_callback" id="http2_response_end_data_encoding_callback">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>This method now returns a reference to <code>ServerResponse</code>.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, <code>response.end()</code>, MUST be called on each response.</p> <p>If <code>data</code> is specified, it is equivalent to calling <a href="#http_response_write_chunk_encoding_callback"><code>response.write(data, encoding)</code></a> followed by <code>response.end(callback)</code>.</p> <p>If <code>callback</code> is specified, it will be called when the response stream is finished.</p> <h4>response.finished<span><a class="mark" href="#http2_response_finished" id="http2_response_finished">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Boolean value that indicates whether the response has completed. Starts as <code>false</code>. After <a href="#http2_response_end_data_encoding_callback"><code>response.end()</code></a> executes, the value will be <code>true</code>.</p> <h4>response.getHeader(name)<span><a class="mark" href="#http2_response_getheader_name" id="http2_response_getheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Reads out a header that has already been queued but not sent to the client. Note that the name is case insensitive.</p> <pre><code class="language-js">const contentType = response.getHeader('content-type'); </code></pre> <h4>response.getHeaderNames()<span><a class="mark" href="#http2_response_getheadernames" id="http2_response_getheadernames">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Returns an array containing the unique names of the current outgoing headers. All header names are lowercase.</p> <pre><code class="language-js">response.setHeader('Foo', 'bar'); response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); const headerNames = response.getHeaderNames(); // headerNames === ['foo', 'set-cookie'] </code></pre> <h4>response.getHeaders()<span><a class="mark" href="#http2_response_getheaders" id="http2_response_getheaders">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related http module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.</p> <p>The object returned by the <code>response.getHeaders()</code> method <em>does not</em> prototypically inherit from the JavaScript <code>Object</code>. This means that typical <code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others are not defined and <em>will not work</em>.</p> <pre><code class="language-js">response.setHeader('Foo', 'bar'); response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); const headers = response.getHeaders(); // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } </code></pre> <h4>response.hasHeader(name)<span><a class="mark" href="#http2_response_hasheader_name" id="http2_response_hasheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the header identified by <code>name</code> is currently set in the outgoing headers. Note that the header name matching is case-insensitive.</p> <pre><code class="language-js">const hasContentType = response.hasHeader('content-type'); </code></pre> <h4>response.headersSent<span><a class="mark" href="#http2_response_headerssent" id="http2_response_headerssent">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>True if headers were sent, false otherwise (read-only).</p> <h4>response.removeHeader(name)<span><a class="mark" href="#http2_response_removeheader_name" id="http2_response_removeheader_name">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Removes a header that has been queued for implicit sending.</p> <pre><code class="language-js">response.removeHeader('Content-Encoding'); </code></pre> <h4>response.sendDate<span><a class="mark" href="#http2_response_senddate" id="http2_response_senddate">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.</p> <p>This should only be disabled for testing; HTTP requires the Date header in responses.</p> <h4>response.setHeader(name, value)<span><a class="mark" href="#http2_response_setheader_name_value" id="http2_response_setheader_name_value">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Sets a single header value for implicit headers. If this header already exists 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.</p> <pre><code class="language-js">response.setHeader('Content-Type', 'text/html'); </code></pre> <p>or</p> <pre><code class="language-js">response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); </code></pre> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <p>When headers have been set with <a href="#http2_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged with any headers passed to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p> <pre><code class="language-js">// returns content-type = text/plain const server = http2.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); }); </code></pre> <h4>response.setTimeout(msecs[, callback])<span><a class="mark" href="#http2_response_settimeout_msecs_callback" id="http2_response_settimeout_msecs_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <p>Sets the <a href=""><code>Http2Stream</code></a>'s timeout value to <code>msecs</code>. If a callback is provided, then it is added as a listener on the <code>'timeout'</code> event on the response object.</p> <p>If no <code>'timeout'</code> listener is added to the request, the response, or the server, then <a href=""><code>Http2Stream</code></a>s are destroyed when they time out. If a handler is assigned to the request, the response, or the server's <code>'timeout'</code> events, timed out sockets must be handled explicitly.</p> <h4>response.socket<span><a class="mark" href="#http2_response_socket" id="http2_response_socket">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="#net_class_net_socket" class="type"><net.Socket></a> | <a href="#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li> </ul> <p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but applies getters, setters, and methods based on HTTP/2 logic.</p> <p><code>destroyed</code>, <code>readable</code>, and <code>writable</code> properties will be retrieved from and set on <code>response.stream</code>.</p> <p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>on</code> and <code>once</code> methods will be called on <code>response.stream</code>.</p> <p><code>setTimeout</code> method will be called on <code>response.stream.session</code>.</p> <p><code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw an error with code <code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href="#http2_http2session_and_sockets"><code>Http2Session</code> and Sockets</a> for more information.</p> <p>All other interactions will be routed directly to the socket.</p> <pre><code class="language-js">const http2 = require('http2'); const server = http2.createServer((req, res) => { const ip = req.socket.remoteAddress; const port = req.socket.remotePort; res.end(`Your IP address is ${ip} and your source port is ${port}.`); }).listen(3000); </code></pre> <h4>response.statusCode<span><a class="mark" href="#http2_response_statuscode" id="http2_response_statuscode">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>When using implicit headers (not calling <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> explicitly), this property controls the status code that will be sent to the client when the headers get flushed.</p> <pre><code class="language-js">response.statusCode = 404; </code></pre> <p>After response header was sent to the client, this property indicates the status code which was sent out.</p> <h4>response.statusMessage<span><a class="mark" href="#http2_response_statusmessage" id="http2_response_statusmessage">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Status message is not supported by HTTP/2 (RFC7540 8.1.2.4). It returns an empty string.</p> <h4>response.stream<span><a class="mark" href="#http2_response_stream" id="http2_response_stream">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><a href="#http2_class_http2stream" class="type"><Http2Stream></a></li> </ul> <p>The <a href="#http2_class_http2stream"><code>Http2Stream</code></a> object backing the response.</p> <h4>response.write(chunk[, encoding][, callback])<span><a class="mark" href="#http2_response_write_chunk_encoding_callback" id="http2_response_write_chunk_encoding_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>If this method is called and <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> has not been called, it will switch to implicit header mode and flush the implicit headers.</p> <p>This sends a chunk of the response body. This method may be called multiple times to provide successive parts of the body.</p> <p>Note that in the <code>http</code> module, the response body is omitted when the request is a HEAD request. Similarly, the <code>204</code> and <code>304</code> responses <em>must not</em> include a message body.</p> <p><code>chunk</code> can be a string or a buffer. If <code>chunk</code> is a string, the second parameter specifies how to encode it into a byte stream. By default the <code>encoding</code> is <code>'utf8'</code>. <code>callback</code> will be called when this chunk of data is flushed.</p> <p>This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.</p> <p>The first time <a href="#http2_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, it will send the buffered header information and the first chunk of the body to the client. The second time <a href="#http2_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, Node.js assumes data will be streamed, and sends the new data separately. That is, the response is buffered up to the first chunk of the body.</p> <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel buffer. Returns <code>false</code> if all or part of the data was queued in user memory. <code>'drain'</code> will be emitted when the buffer is free again.</p> <h4>response.writeContinue()<span><a class="mark" href="#http2_response_writecontinue" id="http2_response_writecontinue">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Sends a status <code>100 Continue</code> to the client, indicating that the request body should be sent. See the <a href="#http2_event_checkcontinue"><code>'checkContinue'</code></a> event on <code>Http2Server</code> and <code>Http2SecureServer</code>.</p> <h4>response.writeHead(statusCode[, statusMessage][, headers])<span><a class="mark" href="#http2_response_writehead_statuscode_statusmessage_headers" id="http2_response_writehead_statuscode_statusmessage_headers">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.17.0</td> <td><p>Return <code>this</code> from <code>writeHead()</code> to allow chaining with <code>end()</code>.</p></td></tr> <tr><td>v8.4.0</td> <td><p><span>Added in: v8.4.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>statusMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li>Returns: <a href="#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a></li> </ul> <p>Sends a response header to the request. The status code is a 3-digit HTTP status code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers.</p> <p>Returns a reference to the <code>Http2ServerResponse</code>, so that calls can be chained.</p> <p>For compatibility with <a href="http.html">HTTP/1</a>, a human-readable <code>statusMessage</code> may be passed as the second argument. However, because the <code>statusMessage</code> has no meaning within HTTP/2, the argument will have no effect and a process warning will be emitted.</p> <pre><code class="language-js">const body = 'hello world'; response.writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/plain' }); </code></pre> <p>Note that Content-Length is given in bytes not characters. The <code>Buffer.byteLength()</code> API may be used to determine the number of bytes in a given encoding. On outbound messages, Node.js does not check if Content-Length and the length of the body being transmitted are equal or not. However, when receiving messages, Node.js will automatically reject messages when the Content-Length does not match the actual payload size.</p> <p>This method may be called at most one time on a message before <a href="#http2_response_end_data_encoding_callback"><code>response.end()</code></a> is called.</p> <p>If <a href="#http2_response_write_chunk_encoding_callback"><code>response.write()</code></a> or <a href="#http2_response_end_data_encoding_callback"><code>response.end()</code></a> are called before calling this, the implicit/mutable headers will be calculated and call this function.</p> <p>When headers have been set with <a href="#http2_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged with any headers passed to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p> <pre><code class="language-js">// returns content-type = text/plain const server = http2.createServer((req, res) => { res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Foo', 'bar'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); }); </code></pre> <p>Attempting to set a header field name or value that contains invalid characters will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p> <h4>response.createPushResponse(headers, callback)<span><a class="mark" href="#http2_response_createpushresponse_headers_callback" id="http2_response_createpushresponse_headers_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <ul> <li><code>headers</code> <a href="#http2_headers_object" class="type"><HTTP/2 Headers Object></a> An object describing the headers</li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called once <code>http2stream.pushStream()</code> is finished, or either when the attempt to create the pushed <code>Http2Stream</code> has failed or has been rejected, or the state of <code>Http2ServerRequest</code> is closed prior to calling the <code>http2stream.pushStream()</code> method</p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>stream</code> <a href="#http2_class_serverhttp2stream" class="type"><ServerHttp2Stream></a> The newly-created <code>ServerHttp2Stream</code> object</li> </ul> </li> </ul> <p>Call <a href="#http2_http2stream_pushstream_headers_options_callback"><code>http2stream.pushStream()</code></a> with the given headers, and wrap the given <a href="#http2_class_http2stream"><code>Http2Stream</code></a> on a newly created <code>Http2ServerResponse</code> as the callback parameter if successful. When <code>Http2ServerRequest</code> is closed, the callback is called with an error <code>ERR_HTTP2_INVALID_STREAM</code>.</p> <h2>Collecting HTTP/2 Performance Metrics<span><a class="mark" href="#http2_collecting_http_2_performance_metrics" id="http2_collecting_http_2_performance_metrics">#</a></span></h2> <p>The <a href="perf_hooks.html">Performance Observer</a> API can be used to collect basic performance metrics for each <code>Http2Session</code> and <code>Http2Stream</code> instance.</p> <pre><code class="language-js">const { PerformanceObserver } = require('perf_hooks'); const obs = new PerformanceObserver((items) => { const entry = items.getEntries()[0]; console.log(entry.entryType); // prints 'http2' if (entry.name === 'Http2Session') { // entry contains statistics about the Http2Session } else if (entry.name === 'Http2Stream') { // entry contains statistics about the Http2Stream } }); obs.observe({ entryTypes: ['http2'] }); </code></pre> <p>The <code>entryType</code> property of the <code>PerformanceEntry</code> will be equal to <code>'http2'</code>.</p> <p>The <code>name</code> property of the <code>PerformanceEntry</code> will be equal to either <code>'Http2Stream'</code> or <code>'Http2Session'</code>.</p> <p>If <code>name</code> is equal to <code>Http2Stream</code>, the <code>PerformanceEntry</code> will contain the following additional properties:</p> <ul> <li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of <code>DATA</code> frame bytes received for this <code>Http2Stream</code>.</li> <li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of <code>DATA</code> frame bytes sent for this <code>Http2Stream</code>.</li> <li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The identifier of the associated <code>Http2Stream</code></li> <li><code>timeToFirstByte</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed between the <code>PerformanceEntry</code> <code>startTime</code> and the reception of the first <code>DATA</code> frame.</li> <li><code>timeToFirstByteSent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed between the <code>PerformanceEntry</code> <code>startTime</code> and sending of the first <code>DATA</code> frame.</li> <li><code>timeToFirstHeader</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed between the <code>PerformanceEntry</code> <code>startTime</code> and the reception of the first header.</li> </ul> <p>If <code>name</code> is equal to <code>Http2Session</code>, the <code>PerformanceEntry</code> will contain the following additional properties:</p> <ul> <li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes received for this <code>Http2Session</code>.</li> <li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of bytes sent for this <code>Http2Session</code>.</li> <li><code>framesReceived</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of HTTP/2 frames received by the <code>Http2Session</code>.</li> <li><code>framesSent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of HTTP/2 frames sent by the <code>Http2Session</code>.</li> <li><code>maxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum number of streams concurrently open during the lifetime of the <code>Http2Session</code>.</li> <li><code>pingRTT</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds elapsed since the transmission of a <code>PING</code> frame and the reception of its acknowledgment. Only present if a <code>PING</code> frame has been sent on the <code>Http2Session</code>.</li> <li><code>streamAverageDuration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The average duration (in milliseconds) for all <code>Http2Stream</code> instances.</li> <li><code>streamCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of <code>Http2Stream</code> instances processed by the <code>Http2Session</code>.</li> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>'server'</code> or <code>'client'</code> to identify the type of <code>Http2Session</code>.</li> </ul> <h1>HTTPS<span><a class="mark" href="#https_https" id="https_https">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a separate module.</p> <h2>Class: https.Agent<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/https.js#L137">[src]</a><span><a class="mark" href="#https_class_https_agent" id="https_class_https_agent">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.4.5</span> </div> <p>An <a href="#https_class_https_agent"><code>Agent</code></a> object for HTTPS similar to <a href="#http_class_http_agent"><code>http.Agent</code></a>. See <a href="#https_https_request_options_callback"><code>https.request()</code></a> for more information.</p> <h2>Class: https.Server<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/https.js#L43">[src]</a><span><a class="mark" href="#https_class_https_server" id="https_class_https_server">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.4</span> </div> <p>This class is a subclass of <code>tls.Server</code> and emits events same as <a href="#http_class_http_server"><code>http.Server</code></a>. See <a href="#http_class_http_server"><code>http.Server</code></a> for more information.</p> <h3>server.close([callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1562">[src]</a><span><a class="mark" href="#https_server_close_callback" id="https_server_close_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#https_class_https_server" class="type"><https.Server></a></li> </ul> <p>See <a href="#http_server_close_callback"><code>server.close()</code></a> from the HTTP module for details.</p> <h3>server.listen()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1360">[src]</a><span><a class="mark" href="#https_server_listen" id="https_server_listen">#</a></span></h3> <p>Starts the HTTPS server listening for encrypted connections. This method is identical to <a href="#net_server_listen"><code>server.listen()</code></a> from <a href="#net_class_net_server"><code>net.Server</code></a>.</p> <h3>server.maxHeadersCount<span><a class="mark" href="#https_server_maxheaderscount" id="https_server_maxheaderscount">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>2000</code></li> </ul> <p>See <a href="#http_server_maxheaderscount"><code>http.Server#maxHeadersCount</code></a>.</p> <h3>server.headersTimeout<span><a class="mark" href="#https_server_headerstimeout" id="https_server_headerstimeout">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>40000</code></li> </ul> <p>See <a href="#http_server_headerstimeout"><code>http.Server#headersTimeout</code></a>.</p> <h3>server.setTimeout([msecs][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/_http_server.js#L323">[src]</a><span><a class="mark" href="#https_server_settimeout_msecs_callback" id="https_server_settimeout_msecs_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.2</span> </div> <ul> <li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#https_class_https_server" class="type"><https.Server></a></li> </ul> <p>See <a href="#http_server_settimeout_msecs_callback"><code>http.Server#setTimeout()</code></a>.</p> <h3>server.timeout<span><a class="mark" href="#https_server_timeout" id="https_server_timeout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.2</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li> </ul> <p>See <a href="#http_server_timeout"><code>http.Server#timeout</code></a>.</p> <h3>server.keepAliveTimeout<span><a class="mark" href="#https_server_keepalivetimeout" id="https_server_keepalivetimeout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>5000</code> (5 seconds)</li> </ul> <p>See <a href="#http_server_keepalivetimeout"><code>http.Server#keepAliveTimeout</code></a>.</p> <h2>https.createServer([options][, requestlistener])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/https.js#L84">[src]</a><span><a class="mark" href="#https_https_createserver_options_requestlistener" id="https_https_createserver_options_requestlistener">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.4</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Accepts <code>options</code> from <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>, <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> and <a href="#http_http_createserver_options_requestlistener"><code>http.createServer()</code></a>.</li> <li><code>requestListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A listener to be added to the <code>'request'</code> event.</li> <li>Returns: <a href="#https_class_https_server" class="type"><https.Server></a></li> </ul> <pre><code class="language-js">// curl -k https://localhost:8000/ const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') }; https.createServer(options, (req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000); </code></pre> <p>Or</p> <pre><code class="language-js">const https = require('https'); const fs = require('fs'); const options = { pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), passphrase: 'sample' }; https.createServer(options, (req, res) => { res.writeHead(200); res.end('hello world\n'); }).listen(8000); </code></pre> <h2>https.get(options[, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/https.js#L292">[src]</a><span><a class="mark" href="#https_https_get_options_callback" id="https_https_get_options_callback">#</a></span></h2> <h2>https.get(url[, options][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/https.js#L292">[src]</a><span><a class="mark" href="#https_https_get_url_options_callback" id="https_https_get_url_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.9.0</td> <td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr> <tr><td>v7.5.0</td> <td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr> <tr><td>v0.3.6</td> <td><p><span>Added in: v0.3.6</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> Accepts the same <code>options</code> as <a href="#https_https_request_options_callback"><code>https.request()</code></a>, with the <code>method</code> always set to <code>GET</code>.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Like <a href="#http_http_get_options_callback"><code>http.get()</code></a> but for HTTPS.</p> <p><code>options</code> can be an object, a string, or a <a href="#url_the_whatwg_url_api"><code>URL</code></a> object. If <code>options</code> is a string, it is automatically parsed with <a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>. If it is a <a href="#url_the_whatwg_url_api"><code>URL</code></a> object, it will be automatically converted to an ordinary <code>options</code> object.</p> <pre><code class="language-js">const https = require('https'); https.get('https://encrypted.google.com/', (res) => { console.log('statusCode:', res.statusCode); console.log('headers:', res.headers); res.on('data', (d) => { process.stdout.write(d); }); }).on('error', (e) => { console.error(e); }); </code></pre> <h2>https.globalAgent<span><a class="mark" href="#https_https_globalagent" id="https_https_globalagent">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <p>Global instance of <a href="#https_class_https_agent"><code>https.Agent</code></a> for all HTTPS client requests.</p> <h2>https.request(options[, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/https.js#L267">[src]</a><span><a class="mark" href="#https_https_request_options_callback" id="https_https_request_options_callback">#</a></span></h2> <h2>https.request(url[, options][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/https.js#L267">[src]</a><span><a class="mark" href="#https_https_request_url_options_callback" id="https_https_request_url_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.9.0</td> <td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr> <tr><td>v9.3.0</td> <td><p>The <code>options</code> parameter can now include <code>clientCertEngine</code>.</p></td></tr> <tr><td>v7.5.0</td> <td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr> <tr><td>v0.3.6</td> <td><p><span>Added in: v0.3.6</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> Accepts all <code>options</code> from <a href="#http_http_request_options_callback"><code>http.request()</code></a>, with some differences in default values:</p> <ul> <li><code>protocol</code> <strong>Default:</strong> <code>'https:'</code></li> <li><code>port</code> <strong>Default:</strong> <code>443</code></li> <li><code>agent</code> <strong>Default:</strong> <code>https.globalAgent</code></li> </ul> </li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Makes a request to a secure web server.</p> <p>The following additional <code>options</code> from <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> are also accepted: <code>ca</code>, <code>cert</code>, <code>ciphers</code>, <code>clientCertEngine</code>, <code>crl</code>, <code>dhparam</code>, <code>ecdhCurve</code>, <code>honorCipherOrder</code>, <code>key</code>, <code>passphrase</code>, <code>pfx</code>, <code>rejectUnauthorized</code>, <code>secureOptions</code>, <code>secureProtocol</code>, <code>servername</code>, <code>sessionIdContext</code>.</p> <p><code>options</code> can be an object, a string, or a <a href="#url_the_whatwg_url_api"><code>URL</code></a> object. If <code>options</code> is a string, it is automatically parsed with <a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>. If it is a <a href="#url_the_whatwg_url_api"><code>URL</code></a> object, it will be automatically converted to an ordinary <code>options</code> object.</p> <pre><code class="language-js">const https = require('https'); const options = { hostname: 'encrypted.google.com', port: 443, path: '/', method: 'GET' }; const req = https.request(options, (res) => { console.log('statusCode:', res.statusCode); console.log('headers:', res.headers); res.on('data', (d) => { process.stdout.write(d); }); }); req.on('error', (e) => { console.error(e); }); req.end(); </code></pre> <p>Example using options from <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>:</p> <pre><code class="language-js">const options = { hostname: 'encrypted.google.com', port: 443, path: '/', method: 'GET', key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') }; options.agent = new https.Agent(options); const req = https.request(options, (res) => { // ... }); </code></pre> <p>Alternatively, opt out of connection pooling by not using an <a href="#https_class_https_agent"><code>Agent</code></a>.</p> <pre><code class="language-js">const options = { hostname: 'encrypted.google.com', port: 443, path: '/', method: 'GET', key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), agent: false }; const req = https.request(options, (res) => { // ... }); </code></pre> <p>Example using a <a href="#url_the_whatwg_url_api"><code>URL</code></a> as <code>options</code>:</p> <pre><code class="language-js">const options = new URL('https://abc:xyz@example.com'); const req = https.request(options, (res) => { // ... }); </code></pre> <p>Example pinning on certificate fingerprint, or the public key (similar to <code>pin-sha256</code>):</p> <pre><code class="language-js">const tls = require('tls'); const https = require('https'); const crypto = require('crypto'); function sha256(s) { return crypto.createHash('sha256').update(s).digest('base64'); } const options = { hostname: 'github.com', port: 443, path: '/', method: 'GET', checkServerIdentity: function(host, cert) { // Make sure the certificate is issued to the host we are connected to const err = tls.checkServerIdentity(host, cert); if (err) { return err; } // Pin the public key, similar to HPKP pin-sha25 pinning const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; if (sha256(cert.pubkey) !== pubkey256) { const msg = 'Certificate verification error: ' + `The public key of '${cert.subject.CN}' ` + 'does not match our pinned fingerprint'; return new Error(msg); } // Pin the exact certificate, rather then the pub key const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; if (cert.fingerprint256 !== cert256) { const msg = 'Certificate verification error: ' + `The certificate of '${cert.subject.CN}' ` + 'does not match our pinned fingerprint'; return new Error(msg); } // This loop is informational only. // Print the certificate and public key fingerprints of all certs in the // chain. Its common to pin the public key of the issuer on the public // internet, while pinning the public key of the service in sensitive // environments. do { console.log('Subject Common Name:', cert.subject.CN); console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); hash = crypto.createHash('sha256'); console.log(' Public key ping-sha256:', sha256(cert.pubkey)); lastprint256 = cert.fingerprint256; cert = cert.issuerCertificate; } while (cert.fingerprint256 !== lastprint256); }, }; options.agent = new https.Agent(options); const req = https.request(options, (res) => { console.log('All OK. Server matched our pinned cert or public key'); console.log('statusCode:', res.statusCode); // Print the HPKP values console.log('headers:', res.headers['public-key-pins']); res.on('data', (d) => {}); }); req.on('error', (e) => { console.error(e.message); }); req.end(); </code></pre> <p>Outputs for example:</p> <pre><code class="language-text">Subject Common Name: github.com Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= Subject Common Name: DigiCert SHA2 Extended Validation Server CA Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= Subject Common Name: DigiCert High Assurance EV Root CA Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= All OK. Server matched our pinned cert or public key statusCode: 200 headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains </code></pre> <h1>Inspector<span><a class="mark" href="#inspector_inspector" id="inspector_inspector">#</a></span></h1> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>The <code>inspector</code> module provides an API for interacting with the V8 inspector.</p> <p>It can be accessed using:</p> <pre><code class="language-js">const inspector = require('inspector'); </code></pre> <h2>inspector.close()<span><a class="mark" href="#inspector_inspector_close" id="inspector_inspector_close">#</a></span></h2> <p>Deactivate the inspector. Blocks until there are no active connections.</p> <h2>inspector.console<span><a class="mark" href="#inspector_inspector_console" id="inspector_inspector_console">#</a></span></h2> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object to send messages to the remote inspector console.</li> </ul> <pre><code class="language-js">require('inspector').console.log('a message'); </code></pre> <p>The inspector console does not have API parity with Node.js console.</p> <h2>inspector.open([port[, host[, wait]]])<span><a class="mark" href="#inspector_inspector_open_port_host_wait" id="inspector_inspector_open_port_host_wait">#</a></span></h2> <ul> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port to listen on for inspector connections. Optional. <strong>Default:</strong> what was specified on the CLI.</li> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host to listen on for inspector connections. Optional. <strong>Default:</strong> what was specified on the CLI.</li> <li><code>wait</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Block until a client has connected. Optional. <strong>Default:</strong> <code>false</code>.</li> </ul> <p>Activate inspector on host and port. Equivalent to <code>node --inspect=[[host:]port]</code>, but can be done programmatically after node has started.</p> <p>If wait is <code>true</code>, will block until a client has connected to the inspect port and flow control has been passed to the debugger client.</p> <p>See the <a href="#inspector_security">security warning</a> regarding the <code>host</code> parameter usage.</p> <h2>inspector.url()<span><a class="mark" href="#inspector_inspector_url" id="inspector_inspector_url">#</a></span></h2> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> </ul> <p>Return the URL of the active inspector, or <code>undefined</code> if there is none.</p> <h2>Class: inspector.Session<span><a class="mark" href="#inspector_class_inspector_session" id="inspector_class_inspector_session">#</a></span></h2> <p>The <code>inspector.Session</code> is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications.</p> <h3>Constructor: new inspector.Session()<span><a class="mark" href="#inspector_constructor_new_inspector_session" id="inspector_constructor_new_inspector_session">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <p>Create a new instance of the <code>inspector.Session</code> class. The inspector session needs to be connected through <a href="#inspector_session_connect"><code>session.connect()</code></a> before the messages can be dispatched to the inspector backend.</p> <p><code>inspector.Session</code> is an <a href="#events_class_eventemitter"><code>EventEmitter</code></a> with the following events:</p> <h3>Event: 'inspectorNotification'<span><a class="mark" href="#inspector_event_inspectornotification" id="inspector_event_inspectornotification">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The notification message object</li> </ul> <p>Emitted when any notification from the V8 Inspector is received.</p> <pre><code class="language-js">session.on('inspectorNotification', (message) => console.log(message.method)); // Debugger.paused // Debugger.resumed </code></pre> <p>It is also possible to subscribe only to notifications with specific method:</p> <h3>Event: <inspector-protocol-method><span><a class="mark" href="#inspector_event_lt_inspector_protocol_method_gt" id="inspector_event_lt_inspector_protocol_method_gt">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The notification message object</li> </ul> <p>Emitted when an inspector notification is received that has its method field set to the <code><inspector-protocol-method></code> value.</p> <p>The following snippet installs a listener on the <a href="https://chromedevtools.github.io/devtools-protocol/v8/Debugger#event-paused"><code>'Debugger.paused'</code></a> event, and prints the reason for program suspension whenever program execution is suspended (through breakpoints, for example):</p> <pre><code class="language-js">session.on('Debugger.paused', ({ params }) => { console.log(params.hitBreakpoints); }); // [ '/the/file/that/has/the/breakpoint.js:11:0' ] </code></pre> <h3>session.connect()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/inspector.js#L33">[src]</a><span><a class="mark" href="#inspector_session_connect" id="inspector_session_connect">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <p>Connects a session to the inspector back-end. An exception will be thrown if there is already a connected session established either through the API or by a front-end connected to the Inspector WebSocket port.</p> <h3>session.disconnect()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/inspector.js#L88">[src]</a><span><a class="mark" href="#inspector_session_disconnect" id="inspector_session_disconnect">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <p>Immediately close the session. All pending message callbacks will be called with an error. <a href="#inspector_session_connect"><code>session.connect()</code></a> will need to be called to be able to send messages again. Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints.</p> <h3>session.post(method[, params][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/inspector.js#L61">[src]</a><span><a class="mark" href="#inspector_session_post_method_params_callback" id="inspector_session_post_method_params_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>method</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Posts a message to the inspector back-end. <code>callback</code> will be notified when a response is received. <code>callback</code> is a function that accepts two optional arguments - error and message-specific result.</p> <pre><code class="language-js">session.post('Runtime.evaluate', { expression: '2 + 2' }, (error, { result }) => console.log(result)); // Output: { type: 'number', value: 4, description: '4' } </code></pre> <p>The latest version of the V8 inspector protocol is published on the <a href="https://chromedevtools.github.io/devtools-protocol/v8/">Chrome DevTools Protocol Viewer</a>.</p> <p>Node.js inspector supports all the Chrome DevTools Protocol domains declared by V8. Chrome DevTools Protocol domain provides an interface for interacting with one of the runtime agents used to inspect the application state and listen to the run-time events.</p> <h2>Example usage<span><a class="mark" href="#inspector_example_usage" id="inspector_example_usage">#</a></span></h2> <p>Apart from the debugger, various V8 Profilers are available through the DevTools protocol.</p> <h3>CPU Profiler<span><a class="mark" href="#inspector_cpu_profiler" id="inspector_cpu_profiler">#</a></span></h3> <p>Here's an example showing how to use the <a href="https://chromedevtools.github.io/devtools-protocol/v8/Profiler">CPU Profiler</a>:</p> <pre><code class="language-js">const inspector = require('inspector'); const fs = require('fs'); const session = new inspector.Session(); session.connect(); session.post('Profiler.enable', () => { session.post('Profiler.start', () => { // invoke business logic under measurement here... // some time later... session.post('Profiler.stop', (err, { profile }) => { // write profile to disk, upload, etc. if (!err) { fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile)); } }); }); }); </code></pre> <h3>Heap Profiler<span><a class="mark" href="#inspector_heap_profiler" id="inspector_heap_profiler">#</a></span></h3> <p>Here's an example showing how to use the <a href="https://chromedevtools.github.io/devtools-protocol/v8/HeapProfiler">Heap Profiler</a>:</p> <pre><code class="language-js">const inspector = require('inspector'); const fs = require('fs'); const session = new inspector.Session(); const fd = fs.openSync('profile.heapsnapshot', 'w'); session.connect(); session.on('HeapProfiler.addHeapSnapshotChunk', (m) => { fs.writeSync(fd, m.params.chunk); }); session.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => { console.log('Runtime.takeHeapSnapshot done:', err, r); session.disconnect(); fs.closeSync(fd); }); </code></pre> <h1>Internationalization Support<span><a class="mark" href="#intl_internationalization_support" id="intl_internationalization_support">#</a></span></h1> <p>Node.js has many features that make it easier to write internationalized programs. Some of them are:</p> <ul> <li> <p>Locale-sensitive or Unicode-aware functions in the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>:</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase"><code>String.prototype.toLowerCase()</code></a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase"><code>String.prototype.toUpperCase()</code></a></li> </ul> </li> <li> <p>All functionality described in the <a href="https://tc39.github.io/ecma402/">ECMAScript Internationalization API Specification</a> (aka ECMA-402):</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl"><code>Intl</code></a> object</li> <li>Locale-sensitive methods like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare"><code>String.prototype.localeCompare()</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString"><code>Date.prototype.toLocaleString()</code></a></li> </ul> </li> <li>The <a href="#url_the_whatwg_url_api">WHATWG URL parser</a>'s <a href="https://en.wikipedia.org/wiki/Internationalized_domain_name">internationalized domain names</a> (IDNs) support</li> <li><a href="#buffer_buffer_transcode_source_fromenc_toenc"><code>require('buffer').transcode()</code></a></li> <li>More accurate <a href="#repl_repl">REPL</a> line editing</li> <li><a href="#util_class_util_textdecoder"><code>require('util').TextDecoder</code></a></li> <li><a href="https://github.com/tc39/proposal-regexp-unicode-property-escapes"><code>RegExp</code> Unicode Property Escapes</a></li> </ul> <p>Node.js (and its underlying V8 engine) uses <a href="http://site.icu-project.org/">ICU</a> to implement these features in native C/C++ code. However, some of them require a very large ICU data file in order to support all locales of the world. Because it is expected that most Node.js users will make use of only a small portion of ICU functionality, only a subset of the full ICU data set is provided by Node.js by default. Several options are provided for customizing and expanding the ICU data set either when building or running Node.js.</p> <h2>Options for building Node.js<span><a class="mark" href="#intl_options_for_building_node_js" id="intl_options_for_building_node_js">#</a></span></h2> <p>To control how ICU is used in Node.js, four <code>configure</code> options are available during compilation. Additional details on how to compile Node.js are documented in <a href="https://github.com/nodejs/node/blob/master/BUILDING.md">BUILDING.md</a>.</p> <ul> <li><code>--with-intl=none</code>/<code>--without-intl</code></li> <li><code>--with-intl=system-icu</code></li> <li><code>--with-intl=small-icu</code> (default)</li> <li><code>--with-intl=full-icu</code></li> </ul> <p>An overview of available Node.js and JavaScript features for each <code>configure</code> option:</p> <table><thead><tr><th></th><th><code>none</code></th><th><code>system-icu</code></th><th><code>small-icu</code></th><th><code>full-icu</code></th></tr></thead><tbody><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a></td><td>none (function is no-op)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><code>String.prototype.to*Case()</code></td><td>full</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl"><code>Intl</code></a></td><td>none (object does not exist)</td><td>partial/full (depends on OS)</td><td>partial (English-only)</td><td>full</td></tr><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare"><code>String.prototype.localeCompare()</code></a></td><td>partial (not locale-aware)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><code>String.prototype.toLocale*Case()</code></td><td>partial (not locale-aware)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString"><code>Number.prototype.toLocaleString()</code></a></td><td>partial (not locale-aware)</td><td>partial/full (depends on OS)</td><td>partial (English-only)</td><td>full</td></tr><tr><td><code>Date.prototype.toLocale*String()</code></td><td>partial (not locale-aware)</td><td>partial/full (depends on OS)</td><td>partial (English-only)</td><td>full</td></tr><tr><td><a href="#url_the_whatwg_url_api">WHATWG URL Parser</a></td><td>partial (no IDN support)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="#buffer_buffer_transcode_source_fromenc_toenc"><code>require('buffer').transcode()</code></a></td><td>none (function does not exist)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="#repl_repl">REPL</a></td><td>partial (inaccurate line editing)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="#util_class_util_textdecoder"><code>require('util').TextDecoder</code></a></td><td>partial (basic encodings support)</td><td>partial/full (depends on OS)</td><td>partial (Unicode-only)</td><td>full</td></tr><tr><td><a href="https://github.com/tc39/proposal-regexp-unicode-property-escapes"><code>RegExp</code> Unicode Property Escapes</a></td><td>none (invalid <code>RegExp</code> error)</td><td>full</td><td>full</td><td>full</td></tr></tbody></table> <p>The "(not locale-aware)" designation denotes that the function carries out its operation just like the non-<code>Locale</code> version of the function, if one exists. For example, under <code>none</code> mode, <code>Date.prototype.toLocaleString()</code>'s operation is identical to that of <code>Date.prototype.toString()</code>.</p> <h3>Disable all internationalization features (<code>none</code>)<span><a class="mark" href="#intl_disable_all_internationalization_features_none" id="intl_disable_all_internationalization_features_none">#</a></span></h3> <p>If this option is chosen, most internationalization features mentioned above will be <strong>unavailable</strong> in the resulting <code>node</code> binary.</p> <h3>Build with a pre-installed ICU (<code>system-icu</code>)<span><a class="mark" href="#intl_build_with_a_pre_installed_icu_system_icu" id="intl_build_with_a_pre_installed_icu_system_icu">#</a></span></h3> <p>Node.js can link against an ICU build already installed on the system. In fact, most Linux distributions already come with ICU installed, and this option would make it possible to reuse the same set of data used by other components in the OS.</p> <p>Functionalities that only require the ICU library itself, such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a> and the <a href="#url_the_whatwg_url_api">WHATWG URL parser</a>, are fully supported under <code>system-icu</code>. Features that require ICU locale data in addition, such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat"><code>Intl.DateTimeFormat</code></a> <em>may</em> be fully or partially supported, depending on the completeness of the ICU data installed on the system.</p> <h3>Embed a limited set of ICU data (<code>small-icu</code>)<span><a class="mark" href="#intl_embed_a_limited_set_of_icu_data_small_icu" id="intl_embed_a_limited_set_of_icu_data_small_icu">#</a></span></h3> <p>This option makes the resulting binary link against the ICU library statically, and includes a subset of ICU data (typically only the English locale) within the <code>node</code> executable.</p> <p>Functionalities that only require the ICU library itself, such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a> and the <a href="#url_the_whatwg_url_api">WHATWG URL parser</a>, are fully supported under <code>small-icu</code>. Features that require ICU locale data in addition, such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat"><code>Intl.DateTimeFormat</code></a>, generally only work with the English locale:</p> <pre><code class="language-js">const january = new Date(9e8); const english = new Intl.DateTimeFormat('en', { month: 'long' }); const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); console.log(english.format(january)); // Prints "January" console.log(spanish.format(january)); // Prints "M01" on small-icu // Should print "enero" </code></pre> <p>This mode provides a good balance between features and binary size, and it is the default behavior if no <code>--with-intl</code> flag is passed. The official binaries are also built in this mode.</p> <h4>Providing ICU data at runtime<span><a class="mark" href="#intl_providing_icu_data_at_runtime" id="intl_providing_icu_data_at_runtime">#</a></span></h4> <p>If the <code>small-icu</code> option is used, one can still provide additional locale data at runtime so that the JS methods would work for all ICU locales. Assuming the data file is stored at <code>/some/directory</code>, it can be made available to ICU through either:</p> <ul> <li> <p>The <a href="#cli_node_icu_data_file"><code>NODE_ICU_DATA</code></a> environment variable:</p> <pre><code class="language-shell">env NODE_ICU_DATA=/some/directory node </code></pre> </li> <li> <p>The <a href="#cli_icu_data_dir_file"><code>--icu-data-dir</code></a> CLI parameter:</p> <pre><code class="language-shell">node --icu-data-dir=/some/directory </code></pre> </li> </ul> <p>(If both are specified, the <code>--icu-data-dir</code> CLI parameter takes precedence.)</p> <p>ICU is able to automatically find and load a variety of data formats, but the data must be appropriate for the ICU version, and the file correctly named. The most common name for the data file is <code>icudt6X[bl].dat</code>, where <code>6X</code> denotes the intended ICU version, and <code>b</code> or <code>l</code> indicates the system's endianness. Check <a href="http://userguide.icu-project.org/icudata">"ICU Data"</a> article in the ICU User Guide for other supported formats and more details on ICU data in general.</p> <p>The <a href="https://www.npmjs.com/package/full-icu">full-icu</a> npm module can greatly simplify ICU data installation by detecting the ICU version of the running <code>node</code> executable and downloading the appropriate data file. After installing the module through <code>npm i full-icu</code>, the data file will be available at <code>./node_modules/full-icu</code>. This path can be then passed either to <code>NODE_ICU_DATA</code> or <code>--icu-data-dir</code> as shown above to enable full <code>Intl</code> support.</p> <h3>Embed the entire ICU (<code>full-icu</code>)<span><a class="mark" href="#intl_embed_the_entire_icu_full_icu" id="intl_embed_the_entire_icu_full_icu">#</a></span></h3> <p>This option makes the resulting binary link against ICU statically and include a full set of ICU data. A binary created this way has no further external dependencies and supports all locales, but might be rather large. See <a href="https://github.com/nodejs/node/blob/master/BUILDING.md#build-with-full-icu-support-all-locales-supported-by-icu">BUILDING.md</a> on how to compile a binary using this mode.</p> <h2>Detecting internationalization support<span><a class="mark" href="#intl_detecting_internationalization_support" id="intl_detecting_internationalization_support">#</a></span></h2> <p>To verify that ICU is enabled at all (<code>system-icu</code>, <code>small-icu</code>, or <code>full-icu</code>), simply checking the existence of <code>Intl</code> should suffice:</p> <pre><code class="language-js">const hasICU = typeof Intl === 'object'; </code></pre> <p>Alternatively, checking for <code>process.versions.icu</code>, a property defined only when ICU is enabled, works too:</p> <pre><code class="language-js">const hasICU = typeof process.versions.icu === 'string'; </code></pre> <p>To check for support for a non-English locale (i.e. <code>full-icu</code> or <code>system-icu</code>), <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat"><code>Intl.DateTimeFormat</code></a> can be a good distinguishing factor:</p> <pre><code class="language-js">const hasFullICU = (() => { try { const january = new Date(9e8); const spanish = new Intl.DateTimeFormat('es', { month: 'long' }); return spanish.format(january) === 'enero'; } catch (err) { return false; } })(); </code></pre> <p>For more verbose tests for <code>Intl</code> support, the following resources may be found to be helpful:</p> <ul> <li><a href="https://github.com/srl295/btest402">btest402</a>: Generally used to check whether Node.js with <code>Intl</code> support is built correctly.</li> <li><a href="https://github.com/tc39/test262/tree/master/test/intl402">Test262</a>: ECMAScript's official conformance test suite includes a section dedicated to ECMA-402.</li> </ul> <h1>Modules<span><a class="mark" href="#modules_modules" id="modules_modules">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>In the Node.js module system, each file is treated as a separate module. For example, consider a file named <code>foo.js</code>:</p> <pre><code class="language-js">const circle = require('./circle.js'); console.log(`The area of a circle of radius 4 is ${circle.area(4)}`); </code></pre> <p>On the first line, <code>foo.js</code> loads the module <code>circle.js</code> that is in the same directory as <code>foo.js</code>.</p> <p>Here are the contents of <code>circle.js</code>:</p> <pre><code class="language-js">const { PI } = Math; exports.area = (r) => PI * r ** 2; exports.circumference = (r) => 2 * PI * r; </code></pre> <p>The module <code>circle.js</code> has exported the functions <code>area()</code> and <code>circumference()</code>. Functions and objects are added to the root of a module by specifying additional properties on the special <code>exports</code> object.</p> <p>Variables local to the module will be private, because the module is wrapped in a function by Node.js (see <a href="#modules_the_module_wrapper">module wrapper</a>). In this example, the variable <code>PI</code> is private to <code>circle.js</code>.</p> <p>The <code>module.exports</code> property can be assigned a new value (such as a function or object).</p> <p>Below, <code>bar.js</code> makes use of the <code>square</code> module, which exports a Square class:</p> <pre><code class="language-js">const Square = require('./square.js'); const mySquare = new Square(2); console.log(`The area of mySquare is ${mySquare.area()}`); </code></pre> <p>The <code>square</code> module is defined in <code>square.js</code>:</p> <pre><code class="language-js">// assigning to exports will not modify module, must use module.exports module.exports = class Square { constructor(width) { this.width = width; } area() { return this.width ** 2; } }; </code></pre> <p>The module system is implemented in the <code>require('module')</code> module.</p> <h2>Accessing the main module<span><a class="mark" href="#modules_accessing_the_main_module" id="modules_accessing_the_main_module">#</a></span></h2> <p>When a file is run directly from Node.js, <code>require.main</code> is set to its <code>module</code>. That means that it is possible to determine whether a file has been run directly by testing <code>require.main === module</code>.</p> <p>For a file <code>foo.js</code>, this will be <code>true</code> if run via <code>node foo.js</code>, but <code>false</code> if run by <code>require('./foo')</code>.</p> <p>Because <code>module</code> provides a <code>filename</code> property (normally equivalent to <code>__filename</code>), the entry point of the current application can be obtained by checking <code>require.main.filename</code>.</p> <h2>Addenda: Package Manager Tips<span><a class="mark" href="#modules_addenda_package_manager_tips" id="modules_addenda_package_manager_tips">#</a></span></h2> <p>The semantics of Node.js's <code>require()</code> function were designed to be general enough to support a number of reasonable directory structures. Package manager programs such as <code>dpkg</code>, <code>rpm</code>, and <code>npm</code> will hopefully find it possible to build native packages from Node.js modules without modification.</p> <p>Below we give a suggested directory structure that could work:</p> <p>Let's say that we wanted to have the folder at <code>/usr/lib/node/<some-package>/<some-version></code> hold the contents of a specific version of a package.</p> <p>Packages can depend on one another. In order to install package <code>foo</code>, it may be necessary to install a specific version of package <code>bar</code>. The <code>bar</code> package may itself have dependencies, and in some cases, these may even collide or form cyclic dependencies.</p> <p>Since Node.js looks up the <code>realpath</code> of any modules it loads (that is, resolves symlinks), and then looks for their dependencies in the <code>node_modules</code> folders as described <a href="#modules_loading_from_node_modules_folders">here</a>, this situation is very simple to resolve with the following architecture:</p> <ul> <li><code>/usr/lib/node/foo/1.2.3/</code> - Contents of the <code>foo</code> package, version 1.2.3.</li> <li><code>/usr/lib/node/bar/4.3.2/</code> - Contents of the <code>bar</code> package that <code>foo</code> depends on.</li> <li><code>/usr/lib/node/foo/1.2.3/node_modules/bar</code> - Symbolic link to <code>/usr/lib/node/bar/4.3.2/</code>.</li> <li><code>/usr/lib/node/bar/4.3.2/node_modules/*</code> - Symbolic links to the packages that <code>bar</code> depends on.</li> </ul> <p>Thus, even if a cycle is encountered, or if there are dependency conflicts, every module will be able to get a version of its dependency that it can use.</p> <p>When the code in the <code>foo</code> package does <code>require('bar')</code>, it will get the version that is symlinked into <code>/usr/lib/node/foo/1.2.3/node_modules/bar</code>. Then, when the code in the <code>bar</code> package calls <code>require('quux')</code>, it'll get the version that is symlinked into <code>/usr/lib/node/bar/4.3.2/node_modules/quux</code>.</p> <p>Furthermore, to make the module lookup process even more optimal, rather than putting packages directly in <code>/usr/lib/node</code>, we could put them in <code>/usr/lib/node_modules/<name>/<version></code>. Then Node.js will not bother looking for missing dependencies in <code>/usr/node_modules</code> or <code>/node_modules</code>.</p> <p>In order to make modules available to the Node.js REPL, it might be useful to also add the <code>/usr/lib/node_modules</code> folder to the <code>$NODE_PATH</code> environment variable. Since the module lookups using <code>node_modules</code> folders are all relative, and based on the real path of the files making the calls to <code>require()</code>, the packages themselves can be anywhere.</p> <h2>All Together...<span><a class="mark" href="#modules_all_together" id="modules_all_together">#</a></span></h2> <p>To get the exact filename that will be loaded when <code>require()</code> is called, use the <code>require.resolve()</code> function.</p> <p>Putting together all of the above, here is the high-level algorithm in pseudocode of what <code>require.resolve()</code> does:</p> <pre><code class="language-txt">require(X) from module at path Y 1. If X is a core module, a. return the core module b. STOP 2. If X begins with '/' a. set Y to be the filesystem root 3. If X begins with './' or '/' or '../' a. LOAD_AS_FILE(Y + X) b. LOAD_AS_DIRECTORY(Y + X) 4. LOAD_NODE_MODULES(X, dirname(Y)) 5. THROW "not found" LOAD_AS_FILE(X) 1. If X is a file, load X as JavaScript text. STOP 2. If X.js is a file, load X.js as JavaScript text. STOP 3. If X.json is a file, parse X.json to a JavaScript Object. STOP 4. If X.node is a file, load X.node as binary addon. STOP LOAD_INDEX(X) 1. If X/index.js is a file, load X/index.js as JavaScript text. STOP 2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP 3. If X/index.node is a file, load X/index.node as binary addon. STOP LOAD_AS_DIRECTORY(X) 1. If X/package.json is a file, a. Parse X/package.json, and look for "main" field. b. let M = X + (json main field) c. LOAD_AS_FILE(M) d. LOAD_INDEX(M) 2. LOAD_INDEX(X) LOAD_NODE_MODULES(X, START) 1. let DIRS = NODE_MODULES_PATHS(START) 2. for each DIR in DIRS: a. LOAD_AS_FILE(DIR/X) b. LOAD_AS_DIRECTORY(DIR/X) NODE_MODULES_PATHS(START) 1. let PARTS = path split(START) 2. let I = count of PARTS - 1 3. let DIRS = [GLOBAL_FOLDERS] 4. while I >= 0, a. if PARTS[I] = "node_modules" CONTINUE b. DIR = path join(PARTS[0 .. I] + "node_modules") c. DIRS = DIRS + DIR d. let I = I - 1 5. return DIRS </code></pre> <h2>Caching<span><a class="mark" href="#modules_caching" id="modules_caching">#</a></span></h2> <p>Modules are cached after the first time they are loaded. This means (among other things) that every call to <code>require('foo')</code> will get exactly the same object returned, if it would resolve to the same file.</p> <p>Provided <code>require.cache</code> is not modified, multiple calls to <code>require('foo')</code> will not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.</p> <p>To have a module execute code multiple times, export a function, and call that function.</p> <h3>Module Caching Caveats<span><a class="mark" href="#modules_module_caching_caveats" id="modules_module_caching_caveats">#</a></span></h3> <p>Modules are cached based on their resolved filename. Since modules may resolve to a different filename based on the location of the calling module (loading from <code>node_modules</code> folders), it is not a <em>guarantee</em> that <code>require('foo')</code> will always return the exact same object, if it would resolve to different files.</p> <p>Additionally, on case-insensitive file systems or operating systems, different resolved filenames can point to the same file, but the cache will still treat them as different modules and will reload the file multiple times. For example, <code>require('./foo')</code> and <code>require('./FOO')</code> return two different objects, irrespective of whether or not <code>./foo</code> and <code>./FOO</code> are the same file.</p> <h2>Core Modules<span><a class="mark" href="#modules_core_modules" id="modules_core_modules">#</a></span></h2> <p>Node.js has several modules compiled into the binary. These modules are described in greater detail elsewhere in this documentation.</p> <p>The core modules are defined within Node.js's source and are located in the <code>lib/</code> folder.</p> <p>Core modules are always preferentially loaded if their identifier is passed to <code>require()</code>. For instance, <code>require('http')</code> will always return the built in HTTP module, even if there is a file by that name.</p> <h2>Cycles<span><a class="mark" href="#modules_cycles" id="modules_cycles">#</a></span></h2> <p>When there are circular <code>require()</code> calls, a module might not have finished executing when it is returned.</p> <p>Consider this situation:</p> <p><code>a.js</code>:</p> <pre><code class="language-js">console.log('a starting'); exports.done = false; const b = require('./b.js'); console.log('in a, b.done = %j', b.done); exports.done = true; console.log('a done'); </code></pre> <p><code>b.js</code>:</p> <pre><code class="language-js">console.log('b starting'); exports.done = false; const a = require('./a.js'); console.log('in b, a.done = %j', a.done); exports.done = true; console.log('b done'); </code></pre> <p><code>main.js</code>:</p> <pre><code class="language-js">console.log('main starting'); const a = require('./a.js'); const b = require('./b.js'); console.log('in main, a.done = %j, b.done = %j', a.done, b.done); </code></pre> <p>When <code>main.js</code> loads <code>a.js</code>, then <code>a.js</code> in turn loads <code>b.js</code>. At that point, <code>b.js</code> tries to load <code>a.js</code>. In order to prevent an infinite loop, an <strong>unfinished copy</strong> of the <code>a.js</code> exports object is returned to the <code>b.js</code> module. <code>b.js</code> then finishes loading, and its <code>exports</code> object is provided to the <code>a.js</code> module.</p> <p>By the time <code>main.js</code> has loaded both modules, they're both finished. The output of this program would thus be:</p> <pre><code class="language-txt">$ node main.js main starting a starting b starting in b, a.done = false b done in a, b.done = true a done in main, a.done = true, b.done = true </code></pre> <p>Careful planning is required to allow cyclic module dependencies to work correctly within an application.</p> <h2>File Modules<span><a class="mark" href="#modules_file_modules" id="modules_file_modules">#</a></span></h2> <p>If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: <code>.js</code>, <code>.json</code>, and finally <code>.node</code>.</p> <p><code>.js</code> files are interpreted as JavaScript text files, and <code>.json</code> files are parsed as JSON text files. <code>.node</code> files are interpreted as compiled addon modules loaded with <code>dlopen</code>.</p> <p>A required module prefixed with <code>'/'</code> is an absolute path to the file. For example, <code>require('/home/marco/foo.js')</code> will load the file at <code>/home/marco/foo.js</code>.</p> <p>A required module prefixed with <code>'./'</code> is relative to the file calling <code>require()</code>. That is, <code>circle.js</code> must be in the same directory as <code>foo.js</code> for <code>require('./circle')</code> to find it.</p> <p>Without a leading <code>'/'</code>, <code>'./'</code>, or <code>'../'</code> to indicate a file, the module must either be a core module or is loaded from a <code>node_modules</code> folder.</p> <p>If the given path does not exist, <code>require()</code> will throw an <a href="#errors_class_error"><code>Error</code></a> with its <code>code</code> property set to <code>'MODULE_NOT_FOUND'</code>.</p> <h2>Folders as Modules<span><a class="mark" href="#modules_folders_as_modules" id="modules_folders_as_modules">#</a></span></h2> <p>It is convenient to organize programs and libraries into self-contained directories, and then provide a single entry point to that library. There are three ways in which a folder may be passed to <code>require()</code> as an argument.</p> <p>The first is to create a <code>package.json</code> file in the root of the folder, which specifies a <code>main</code> module. An example <code>package.json</code> file might look like this:</p> <pre><code class="language-json">{ "name" : "some-library", "main" : "./lib/some-library.js" } </code></pre> <p>If this was in a folder at <code>./some-library</code>, then <code>require('./some-library')</code> would attempt to load <code>./some-library/lib/some-library.js</code>.</p> <p>This is the extent of Node.js's awareness of <code>package.json</code> files.</p> <p>If there is no <code>package.json</code> file present in the directory, or if the <code>'main'</code> entry is missing or cannot be resolved, then Node.js will attempt to load an <code>index.js</code> or <code>index.node</code> file out of that directory. For example, if there was no <code>package.json</code> file in the above example, then <code>require('./some-library')</code> would attempt to load:</p> <ul> <li><code>./some-library/index.js</code></li> <li><code>./some-library/index.node</code></li> </ul> <p>If these attempts fail, then Node.js will report the entire module as missing with the default error:</p> <pre><code class="language-txt">Error: Cannot find module 'some-library' </code></pre> <h2>Loading from <code>node_modules</code> Folders<span><a class="mark" href="#modules_loading_from_node_modules_folders" id="modules_loading_from_node_modules_folders">#</a></span></h2> <p>If the module identifier passed to <code>require()</code> is not a <a href="#modules_core_modules">core</a> module, and does not begin with <code>'/'</code>, <code>'../'</code>, or <code>'./'</code>, then Node.js starts at the parent directory of the current module, and adds <code>/node_modules</code>, and attempts to load the module from that location. Node.js will not append <code>node_modules</code> to a path already ending in <code>node_modules</code>.</p> <p>If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.</p> <p>For example, if the file at <code>'/home/ry/projects/foo.js'</code> called <code>require('bar.js')</code>, then Node.js would look in the following locations, in this order:</p> <ul> <li><code>/home/ry/projects/node_modules/bar.js</code></li> <li><code>/home/ry/node_modules/bar.js</code></li> <li><code>/home/node_modules/bar.js</code></li> <li><code>/node_modules/bar.js</code></li> </ul> <p>This allows programs to localize their dependencies, so that they do not clash.</p> <p>It is possible to require specific files or sub modules distributed with a module by including a path suffix after the module name. For instance <code>require('example-module/path/to/file')</code> would resolve <code>path/to/file</code> relative to where <code>example-module</code> is located. The suffixed path follows the same module resolution semantics.</p> <h2>Loading from the global folders<span><a class="mark" href="#modules_loading_from_the_global_folders" id="modules_loading_from_the_global_folders">#</a></span></h2> <p>If the <code>NODE_PATH</code> environment variable is set to a colon-delimited list of absolute paths, then Node.js will search those paths for modules if they are not found elsewhere.</p> <p>On Windows, <code>NODE_PATH</code> is delimited by semicolons (<code>;</code>) instead of colons.</p> <p><code>NODE_PATH</code> was originally created to support loading modules from varying paths before the current <a href="#modules_all_together">module resolution</a> algorithm was frozen.</p> <p><code>NODE_PATH</code> is still supported, but is less necessary now that the Node.js ecosystem has settled on a convention for locating dependent modules. Sometimes deployments that rely on <code>NODE_PATH</code> show surprising behavior when people are unaware that <code>NODE_PATH</code> must be set. Sometimes a module's dependencies change, causing a different version (or even a different module) to be loaded as the <code>NODE_PATH</code> is searched.</p> <p>Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:</p> <ul> <li>1: <code>$HOME/.node_modules</code></li> <li>2: <code>$HOME/.node_libraries</code></li> <li>3: <code>$PREFIX/lib/node</code></li> </ul> <p>Where <code>$HOME</code> is the user's home directory, and <code>$PREFIX</code> is Node.js's configured <code>node_prefix</code>.</p> <p>These are mostly for historic reasons.</p> <p>It is strongly encouraged to place dependencies in the local <code>node_modules</code> folder. These will be loaded faster, and more reliably.</p> <h2>The module wrapper<span><a class="mark" href="#modules_the_module_wrapper" id="modules_the_module_wrapper">#</a></span></h2> <p>Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following:</p> <pre><code class="language-js">(function(exports, require, module, __filename, __dirname) { // Module code actually lives in here }); </code></pre> <p>By doing this, Node.js achieves a few things:</p> <ul> <li>It keeps top-level variables (defined with <code>var</code>, <code>const</code> or <code>let</code>) scoped to the module rather than the global object.</li> <li> <p>It helps to provide some global-looking variables that are actually specific to the module, such as:</p> <ul> <li>The <code>module</code> and <code>exports</code> objects that the implementor can use to export values from the module.</li> <li>The convenience variables <code>__filename</code> and <code>__dirname</code>, containing the module's absolute filename and directory path.</li> </ul> </li> </ul> <h2>The module scope<span><a class="mark" href="#modules_the_module_scope" id="modules_the_module_scope">#</a></span></h2> <h3>__dirname<span><a class="mark" href="#modules_dirname" id="modules_dirname">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.27</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The directory name of the current module. This is the same as the <a href="#path_path_dirname_path"><code>path.dirname()</code></a> of the <a href="#modules_filename"><code>__filename</code></a>.</p> <p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p> <pre><code class="language-js">console.log(__dirname); // Prints: /Users/mjr console.log(path.dirname(__filename)); // Prints: /Users/mjr </code></pre> <h3>__filename<span><a class="mark" href="#modules_filename" id="modules_filename">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.0.1</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The file name of the current module. This is the current module file's absolute path with symlinks resolved.</p> <p>For a main program this is not necessarily the same as the file name used in the command line.</p> <p>See <a href="#modules_dirname"><code>__dirname</code></a> for the directory name of the current module.</p> <p>Examples:</p> <p>Running <code>node example.js</code> from <code>/Users/mjr</code></p> <pre><code class="language-js">console.log(__filename); // Prints: /Users/mjr/example.js console.log(__dirname); // Prints: /Users/mjr </code></pre> <p>Given two modules: <code>a</code> and <code>b</code>, where <code>b</code> is a dependency of <code>a</code> and there is a directory structure of:</p> <ul> <li><code>/Users/mjr/app/a.js</code></li> <li><code>/Users/mjr/app/node_modules/b/b.js</code></li> </ul> <p>References to <code>__filename</code> within <code>b.js</code> will return <code>/Users/mjr/app/node_modules/b/b.js</code> while references to <code>__filename</code> within <code>a.js</code> will return <code>/Users/mjr/app/a.js</code>.</p> <h3>exports<span><a class="mark" href="#modules_exports" id="modules_exports">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.12</span> </div> <p>A reference to the <code>module.exports</code> that is shorter to type. See the section about the <a href="#modules_exports_shortcut">exports shortcut</a> for details on when to use <code>exports</code> and when to use <code>module.exports</code>.</p> <h3>module<span><a class="mark" href="#modules_module" id="modules_module">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>A reference to the current module, see the section about the <a href="#modules_the_module_object"><code>module</code> object</a>. In particular, <code>module.exports</code> is used for defining what a module exports and makes available through <code>require()</code>.</p> <h3>require()<span><a class="mark" href="#modules_require" id="modules_require">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.13</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Used to import modules, <code>JSON</code>, and local files. Modules can be imported from <code>node_modules</code>. Local modules and JSON files can be imported using a relative path (e.g. <code>./</code>, <code>./foo</code>, <code>./bar/baz</code>, <code>../foo</code>) that will be resolved against the directory named by <a href="#modules_dirname"><code>__dirname</code></a> (if defined) or the current working directory.</p> <pre><code class="language-js">// Importing a local module: const myLocalModule = require('./path/myLocalModule'); // Importing a JSON file: const jsonData = require('./path/filename.json'); // Importing a module from node_modules or Node.js built-in module: const crypto = require('crypto'); </code></pre> <h4>require.cache<span><a class="mark" href="#modules_require_cache" id="modules_require_cache">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Modules are cached in this object when they are required. By deleting a key value from this object, the next <code>require</code> will reload the module. Note that this does not apply to <a href="addons.html">native addons</a>, for which reloading will result in an error.</p> <h4>require.extensions<span><a class="mark" href="#modules_require_extensions" id="modules_require_extensions">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.0</span><span>Deprecated since: v0.10.6</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Instruct <code>require</code> on how to handle certain file extensions.</p> <p>Process files with the extension <code>.sjs</code> as <code>.js</code>:</p> <pre><code class="language-js">require.extensions['.sjs'] = require.extensions['.js']; </code></pre> <p><strong>Deprecated</strong> In the past, this list has been used to load non-JavaScript modules into Node.js by compiling them on-demand. However, in practice, there are much better ways to do this, such as loading modules via some other Node.js program, or compiling them to JavaScript ahead of time.</p> <p>Since the module system is locked, this feature will probably never go away. However, it may have subtle bugs and complexities that are best left untouched.</p> <p>Note that the number of file system operations that the module system has to perform in order to resolve a <code>require(...)</code> statement to a filename scales linearly with the number of registered extensions.</p> <p>In other words, adding extensions slows down the module loader and should be discouraged.</p> <h4>require.main<span><a class="mark" href="#modules_require_main" id="modules_require_main">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>Module</code> object representing the entry script loaded when the Node.js process launched. See <a href="#modules_accessing_the_main_module">"Accessing the main module"</a>.</p> <p>In <code>entry.js</code> script:</p> <pre><code class="language-js">console.log(require.main); </code></pre> <pre><code class="language-sh">node entry.js </code></pre> <!-- eslint-skip --> <pre><code class="language-js">Module { id: '.', exports: {}, parent: null, filename: '/absolute/path/to/entry.js', loaded: false, children: [], paths: [ '/absolute/path/to/node_modules', '/absolute/path/node_modules', '/absolute/node_modules', '/node_modules' ] } </code></pre> <h4>require.resolve(request[, options])<span><a class="mark" href="#modules_require_resolve_request_options" id="modules_require_resolve_request_options">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.9.0</td> <td><p>The <code>paths</code> option is now supported.</p></td></tr> <tr><td>v0.3.0</td> <td><p><span>Added in: v0.3.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>request</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The module path to resolve.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>paths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> Paths to resolve module location from. If present, these paths are used instead of the default resolution paths, with the exception of <a href="#modules_loading_from_the_global_folders">GLOBAL_FOLDERS</a> like <code>$HOME/.node_modules</code>, which are always included. Note that each of these paths is used as a starting point for the module resolution algorithm, meaning that the <code>node_modules</code> hierarchy is checked from this location.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Use the internal <code>require()</code> machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.</p> <h4>require.resolve.paths(request)<span><a class="mark" href="#modules_require_resolve_paths_request" id="modules_require_resolve_paths_request">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.9.0</span> </div> <ul> <li><code>request</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The module path whose lookup paths are being retrieved.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a></li> </ul> <p>Returns an array containing the paths searched during resolution of <code>request</code> or <code>null</code> if the <code>request</code> string references a core module, for example <code>http</code> or <code>fs</code>.</p> <h2>The <code>module</code> Object<span><a class="mark" href="#modules_the_module_object" id="modules_the_module_object">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>In each module, the <code>module</code> free variable is a reference to the object representing the current module. For convenience, <code>module.exports</code> is also accessible via the <code>exports</code> module-global. <code>module</code> is not actually a global but rather local to each module.</p> <h3>module.children<span><a class="mark" href="#modules_module_children" id="modules_module_children">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <ul> <li><a href="#modules_the_module_object" class="type"><module[]></a></li> </ul> <p>The module objects required for the first time by this one.</p> <h3>module.exports<span><a class="mark" href="#modules_module_exports" id="modules_module_exports">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>module.exports</code> object is created by the <code>Module</code> system. Sometimes this is not acceptable; many want their module to be an instance of some class. To do this, assign the desired export object to <code>module.exports</code>. Note that assigning the desired object to <code>exports</code> will simply rebind the local <code>exports</code> variable, which is probably not what is desired.</p> <p>For example, suppose we were making a module called <code>a.js</code>:</p> <pre><code class="language-js">const EventEmitter = require('events'); module.exports = new EventEmitter(); // Do some work, and after some time emit // the 'ready' event from the module itself. setTimeout(() => { module.exports.emit('ready'); }, 1000); </code></pre> <p>Then in another file we could do:</p> <pre><code class="language-js">const a = require('./a'); a.on('ready', () => { console.log('module "a" is ready'); }); </code></pre> <p>Note that assignment to <code>module.exports</code> must be done immediately. It cannot be done in any callbacks. This does not work:</p> <p><code>x.js</code>:</p> <pre><code class="language-js">setTimeout(() => { module.exports = { a: 'hello' }; }, 0); </code></pre> <p><code>y.js</code>:</p> <pre><code class="language-js">const x = require('./x'); console.log(x.a); </code></pre> <h4>exports shortcut<span><a class="mark" href="#modules_exports_shortcut" id="modules_exports_shortcut">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <p>The <code>exports</code> variable is available within a module's file-level scope, and is assigned the value of <code>module.exports</code> before the module is evaluated.</p> <p>It allows a shortcut, so that <code>module.exports.f = ...</code> can be written more succinctly as <code>exports.f = ...</code>. However, be aware that like any variable, if a new value is assigned to <code>exports</code>, it is no longer bound to <code>module.exports</code>:</p> <pre><code class="language-js">module.exports.hello = true; // Exported from require of module exports = { hello: false }; // Not exported, only available in the module </code></pre> <p>When the <code>module.exports</code> property is being completely replaced by a new object, it is common to also reassign <code>exports</code>:</p> <!-- eslint-disable func-name-matching --> <pre><code class="language-js">module.exports = exports = function Constructor() { // ... etc. }; </code></pre> <p>To illustrate the behavior, imagine this hypothetical implementation of <code>require()</code>, which is quite similar to what is actually done by <code>require()</code>:</p> <pre><code class="language-js">function require(/* ... */) { const module = { exports: {} }; ((module, exports) => { // Module code here. In this example, define a function. function someFunc() {} exports = someFunc; // At this point, exports is no longer a shortcut to module.exports, and // this module will still export an empty default object. module.exports = someFunc; // At this point, the module will now export someFunc, instead of the // default object. })(module, module.exports); return module.exports; } </code></pre> <h3>module.filename<span><a class="mark" href="#modules_module_filename" id="modules_module_filename">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The fully resolved filename to the module.</p> <h3>module.id<span><a class="mark" href="#modules_module_id" id="modules_module_id">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The identifier for the module. Typically this is the fully resolved filename.</p> <h3>module.loaded<span><a class="mark" href="#modules_module_loaded" id="modules_module_loaded">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Whether or not the module is done loading, or is in the process of loading.</p> <h3>module.parent<span><a class="mark" href="#modules_module_parent" id="modules_module_parent">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <ul> <li><a href="#modules_the_module_object" class="type"><module></a></li> </ul> <p>The module that first required this one.</p> <h3>module.paths<span><a class="mark" href="#modules_module_paths" id="modules_module_paths">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The search paths for the module.</p> <h3>module.require(id)<span><a class="mark" href="#modules_module_require_id" id="modules_module_require_id">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.1</span> </div> <ul> <li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> <code>module.exports</code> from the resolved module</li> </ul> <p>The <code>module.require</code> method provides a way to load a module as if <code>require()</code> was called from the original module.</p> <p>In order to do this, it is necessary to get a reference to the <code>module</code> object. Since <code>require()</code> returns the <code>module.exports</code>, and the <code>module</code> is typically <em>only</em> available within a specific module's code, it must be explicitly exported in order to be used.</p> <h2>The <code>Module</code> Object<span><a class="mark" href="#modules_the_module_object_1" id="modules_the_module_object_1">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.7</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Provides general utility methods when interacting with instances of <code>Module</code>, the <code>module</code> variable often seen in file modules. Accessed via <code>require('module')</code>.</p> <h3>module.builtinModules<span><a class="mark" href="#modules_module_builtinmodules" id="modules_module_builtinmodules">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.3.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>A list of the names of all modules provided by Node.js. Can be used to verify if a module is maintained by a third party or not.</p> <p>Note that <code>module</code> in this context isn't the same object that's provided by the <a href="#modules_the_module_wrapper">module wrapper</a>. To access it, require the <code>Module</code> module:</p> <pre><code class="language-js">const builtin = require('module').builtinModules; </code></pre> <h3>module.createRequireFromPath(filename)<span><a class="mark" href="#modules_module_createrequirefrompath_filename" id="modules_module_createrequirefrompath_filename">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Filename to be used to construct the relative require function.</li> <li>Returns: {<a href="#modules_require"><code>require</code></a>} Require function</li> </ul> <pre><code class="language-js">const { createRequireFromPath } = require('module'); const requireUtil = createRequireFromPath('../src/utils'); // require `../src/utils/some-tool` requireUtil('./some-tool'); </code></pre> <h1>Net<span><a class="mark" href="#net_net" id="net_net">#</a></span></h1> <!--lint disable maximum-line-length--> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>net</code> module provides an asynchronous network API for creating stream-based TCP or <a href="#net_ipc_support">IPC</a> servers (<a href="#net_net_createserver_options_connectionlistener"><code>net.createServer()</code></a>) and clients (<a href="#net_net_createconnection"><code>net.createConnection()</code></a>).</p> <p>It can be accessed using:</p> <pre><code class="language-js">const net = require('net'); </code></pre> <h2>IPC Support<span><a class="mark" href="#net_ipc_support" id="net_ipc_support">#</a></span></h2> <p>The <code>net</code> module supports IPC with named pipes on Windows, and UNIX domain sockets on other operating systems.</p> <h3>Identifying paths for IPC connections<span><a class="mark" href="#net_identifying_paths_for_ipc_connections" id="net_identifying_paths_for_ipc_connections">#</a></span></h3> <p><a href="#net_net_connect"><code>net.connect()</code></a>, <a href="#net_net_createconnection"><code>net.createConnection()</code></a>, <a href="#net_server_listen"><code>server.listen()</code></a> and <a href="#net_socket_connect"><code>socket.connect()</code></a> take a <code>path</code> parameter to identify IPC endpoints.</p> <p>On UNIX, the local domain is also known as the UNIX domain. The path is a filesystem pathname. It gets truncated to <code>sizeof(sockaddr_un.sun_path) - 1</code>, which varies on different operating system between 91 and 107 bytes. The typical values are 107 on Linux and 103 on macOS. The path is subject to the same naming conventions and permissions checks as would be done on file creation. If the UNIX domain socket (that is visible as a file system path) is created and used in conjunction with one of Node.js' API abstractions such as <a href="#net_net_createserver_options_connectionlistener"><code>net.createServer()</code></a>, it will be unlinked as part of <a href="#net_server_close_callback"><code>server.close()</code></a>. On the other hand, if it is created and used outside of these abstractions, the user will need to manually remove it. The same applies when the path was created by a Node.js API but the program crashes abruptly. In short, a UNIX domain socket once successfully created will be visible in the filesystem, and will persist until unlinked.</p> <p>On Windows, the local domain is implemented using a named pipe. The path <em>must</em> refer to an entry in <code>\\?\pipe\</code> or <code>\\.\pipe\</code>. Any characters are permitted, but the latter may do some processing of pipe names, such as resolving <code>..</code> sequences. Despite how it might look, the pipe namespace is flat. Pipes will <em>not persist</em>. They are removed when the last reference to them is closed. Unlike UNIX domain sockets, Windows will close and remove the pipe when the owning process exits.</p> <p>JavaScript string escaping requires paths to be specified with extra backslash escaping such as:</p> <pre><code class="language-js">net.createServer().listen( path.join('\\\\?\\pipe', process.cwd(), 'myctl')); </code></pre> <h2>Class: net.Server<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1121">[src]</a><span><a class="mark" href="#net_class_net_server" id="net_class_net_server">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <p>This class is used to create a TCP or <a href="#net_ipc_support">IPC</a> server.</p> <h3>new net.Server([options][, connectionlistener])<span><a class="mark" href="#net_new_net_server_options_connectionlistener" id="net_new_net_server_options_connectionlistener">#</a></span></h3> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#net_net_createserver_options_connectionlistener"><code>net.createServer([options][, connectionListener])</code></a>.</li> <li><code>connectionListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Automatically set as a listener for the <a href="#net_event_connection"><code>'connection'</code></a> event.</li> <li>Returns: <a href="#net_class_net_server" class="type"><net.Server></a></li> </ul> <p><code>net.Server</code> is an <a href="#events_class_eventemitter"><code>EventEmitter</code></a> with the following events:</p> <h3>Event: 'close'<span><a class="mark" href="#net_event_close" id="net_event_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <p>Emitted when the server closes. Note that if connections exist, this event is not emitted until all connections are ended.</p> <h3>Event: 'connection'<span><a class="mark" href="#net_event_connection" id="net_event_connection">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><a href="#net_class_net_socket" class="type"><net.Socket></a> The connection object</li> </ul> <p>Emitted when a new connection is made. <code>socket</code> is an instance of <code>net.Socket</code>.</p> <h3>Event: 'error'<span><a class="mark" href="#net_event_error" id="net_event_error">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Emitted when an error occurs. Unlike <a href="#net_class_net_socket"><code>net.Socket</code></a>, the <a href="#net_event_close"><code>'close'</code></a> event will <strong>not</strong> be emitted directly following this event unless <a href="#net_server_close_callback"><code>server.close()</code></a> is manually called. See the example in discussion of <a href="#net_server_listen"><code>server.listen()</code></a>.</p> <h3>Event: 'listening'<span><a class="mark" href="#net_event_listening" id="net_event_listening">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <p>Emitted when the server has been bound after calling <a href="#net_server_listen"><code>server.listen()</code></a>.</p> <h3>server.address()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1475">[src]</a><span><a class="mark" href="#net_server_address" id="net_server_address">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the bound <code>address</code>, the address <code>family</code> name, and <code>port</code> of the server as reported by the operating system if listening on an IP socket (useful to find which port was assigned when getting an OS-assigned address): <code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code>.</p> <p>For a server listening on a pipe or UNIX domain socket, the name is returned as a string.</p> <pre><code class="language-js">const server = net.createServer((socket) => { socket.end('goodbye\n'); }).on('error', (err) => { // handle errors here throw err; }); // grab an arbitrary unused port. server.listen(() => { console.log('opened server on', server.address()); }); </code></pre> <p>Don't call <code>server.address()</code> until the <code>'listening'</code> event has been emitted.</p> <h3>server.close([callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1562">[src]</a><span><a class="mark" href="#net_server_close_callback" id="net_server_close_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called when the server is closed</li> <li>Returns: <a href="#net_class_net_server" class="type"><net.Server></a></li> </ul> <p>Stops the server from accepting new connections and keeps existing connections. This function is asynchronous, the server is finally closed when all connections are ended and the server emits a <a href="#net_event_close"><code>'close'</code></a> event. The optional <code>callback</code> will be called once the <code>'close'</code> event occurs. Unlike that event, it will be called with an <code>Error</code> as its only argument if the server was not open when it was closed.</p> <h3>server.connections<span><a class="mark" href="#net_server_connections" id="net_server_connections">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.2.0</span><span>Deprecated since: v0.9.7</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#net_server_getconnections_callback"><code>server.getConnections()</code></a> instead.</div><p></p> <p>The number of concurrent connections on the server.</p> <p>This becomes <code>null</code> when sending a socket to a child with <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>. To poll forks and get current number of active connections, use asynchronous <a href="#net_server_getconnections_callback"><code>server.getConnections()</code></a> instead.</p> <h3>server.getConnections(callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1524">[src]</a><span><a class="mark" href="#net_server_getconnections_callback" id="net_server_getconnections_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.7</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#net_class_net_server" class="type"><net.Server></a></li> </ul> <p>Asynchronously get the number of concurrent connections on the server. Works when sockets were sent to forks.</p> <p>Callback should take two arguments <code>err</code> and <code>count</code>.</p> <h3>server.listen()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1360">[src]</a><span><a class="mark" href="#net_server_listen" id="net_server_listen">#</a></span></h3> <p>Start a server listening for connections. A <code>net.Server</code> can be a TCP or an <a href="#net_ipc_support">IPC</a> server depending on what it listens to.</p> <p>Possible signatures:</p> <ul> <li><a href="#net_server_listen_handle_backlog_callback"><code>server.listen(handle[, backlog][, callback])</code></a></li> <li><a href="#net_server_listen_options_callback"><code>server.listen(options[, callback])</code></a></li> <li><a href="#net_server_listen_path_backlog_callback"><code>server.listen(path[, backlog][, callback])</code></a> for <a href="#net_ipc_support">IPC</a> servers</li> <li> <a href="#net_server_listen_port_host_backlog_callback"> <code>server.listen([port[, host[, backlog]]][, callback])</code></a> for TCP servers </li> </ul> <p>This function is asynchronous. When the server starts listening, the <a href="#net_event_listening"><code>'listening'</code></a> event will be emitted. The last parameter <code>callback</code> will be added as a listener for the <a href="#net_event_listening"><code>'listening'</code></a> event.</p> <p>All <code>listen()</code> methods can take a <code>backlog</code> parameter to specify the maximum length of the queue of pending connections. The actual length will be determined by the OS through sysctl settings such as <code>tcp_max_syn_backlog</code> and <code>somaxconn</code> on Linux. The default value of this parameter is 511 (not 512).</p> <p>All <a href="#net_class_net_socket"><code>net.Socket</code></a> are set to <code>SO_REUSEADDR</code> (see <a href="http://man7.org/linux/man-pages/man7/socket.7.html"><code>socket(7)</code></a> for details).</p> <p>The <code>server.listen()</code> method can be called again if and only if there was an error during the first <code>server.listen()</code> call or <code>server.close()</code> has been called. Otherwise, an <code>ERR_SERVER_ALREADY_LISTEN</code> error will be thrown.</p> <p>One of the most common errors raised when listening is <code>EADDRINUSE</code>. This happens when another server is already listening on the requested <code>port</code>/<code>path</code>/<code>handle</code>. One way to handle this would be to retry after a certain amount of time:</p> <pre><code class="language-js">server.on('error', (e) => { if (e.code === 'EADDRINUSE') { console.log('Address in use, retrying...'); setTimeout(() => { server.close(); server.listen(PORT, HOST); }, 1000); } }); </code></pre> <h4>server.listen(handle[, backlog][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1360">[src]</a><span><a class="mark" href="#net_server_listen_handle_backlog_callback" id="net_server_listen_handle_backlog_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.5.10</span> </div> <ul> <li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>backlog</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a> functions</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a> functions</li> <li>Returns: <a href="#net_class_net_server" class="type"><net.Server></a></li> </ul> <p>Start a server listening for connections on a given <code>handle</code> that has already been bound to a port, a UNIX domain socket, or a Windows named pipe.</p> <p>The <code>handle</code> object can be either a server, a socket (anything with an underlying <code>_handle</code> member), or an object with an <code>fd</code> member that is a valid file descriptor.</p> <p>Listening on a file descriptor is not supported on Windows.</p> <h4>server.listen(options[, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1360">[src]</a><span><a class="mark" href="#net_server_listen_options_callback" id="net_server_listen_options_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Required. Supports the following properties:</p> <ul> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Will be ignored if <code>port</code> is specified. See <a href="#net_identifying_paths_for_ipc_connections">Identifying paths for IPC connections</a>.</li> <li><code>backlog</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a> functions.</li> <li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li> <li><code>readableAll</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> For IPC servers makes the pipe readable for all users. <strong>Default:</strong> <code>false</code></li> <li><code>writableAll</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> For IPC servers makes the pipe writable for all users. <strong>Default:</strong> <code>false</code></li> </ul> </li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a> functions.</li> <li>Returns: <a href="#net_class_net_server" class="type"><net.Server></a></li> </ul> <p>If <code>port</code> is specified, it behaves the same as <a href="#net_server_listen_port_host_backlog_callback"> <code>server.listen([port[, host[, backlog]]][, callback])</code></a>. Otherwise, if <code>path</code> is specified, it behaves the same as <a href="#net_server_listen_path_backlog_callback"><code>server.listen(path[, backlog][, callback])</code></a>. If none of them is specified, an error will be thrown.</p> <p>If <code>exclusive</code> is <code>false</code> (default), then cluster workers will use the same underlying handle, allowing connection handling duties to be shared. When <code>exclusive</code> is <code>true</code>, the handle is not shared, and attempted port sharing results in an error. An example which listens on an exclusive port is shown below.</p> <pre><code class="language-js">server.listen({ host: 'localhost', port: 80, exclusive: true }); </code></pre> <p>Starting an IPC server as root may cause the server path to be inaccessible for unprivileged users. Using <code>readableAll</code> and <code>writableAll</code> will make the server accessible for all users.</p> <h4>server.listen(path[, backlog][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1360">[src]</a><span><a class="mark" href="#net_server_listen_path_backlog_callback" id="net_server_listen_path_backlog_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Path the server should listen to. See <a href="#net_identifying_paths_for_ipc_connections">Identifying paths for IPC connections</a>.</li> <li><code>backlog</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a> functions.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a> functions.</li> <li>Returns: <a href="#net_class_net_server" class="type"><net.Server></a></li> </ul> <p>Start an <a href="#net_ipc_support">IPC</a> server listening for connections on the given <code>path</code>.</p> <h4>server.listen([port[, host[, backlog]]][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1360">[src]</a><span><a class="mark" href="#net_server_listen_port_host_backlog_callback" id="net_server_listen_port_host_backlog_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>backlog</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a> functions.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a> functions.</li> <li>Returns: <a href="#net_class_net_server" class="type"><net.Server></a></li> </ul> <p>Start a TCP server listening for connections on the given <code>port</code> and <code>host</code>.</p> <p>If <code>port</code> is omitted or is 0, the operating system will assign an arbitrary unused port, which can be retrieved by using <code>server.address().port</code> after the <a href="#net_event_listening"><code>'listening'</code></a> event has been emitted.</p> <p>If <code>host</code> is omitted, the server will accept connections on the <a href="https://en.wikipedia.org/wiki/IPv6_address#Unspecified_address">unspecified IPv6 address</a> (<code>::</code>) when IPv6 is available, or the <a href="https://en.wikipedia.org/wiki/0.0.0.0">unspecified IPv4 address</a> (<code>0.0.0.0</code>) otherwise.</p> <p>In most operating systems, listening to the <a href="https://en.wikipedia.org/wiki/IPv6_address#Unspecified_address">unspecified IPv6 address</a> (<code>::</code>) may cause the <code>net.Server</code> to also listen on the <a href="https://en.wikipedia.org/wiki/0.0.0.0">unspecified IPv4 address</a> (<code>0.0.0.0</code>).</p> <h3>server.listening<span><a class="mark" href="#net_server_listening" id="net_server_listening">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.7.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether or not the server is listening for connections.</li> </ul> <h3>server.maxConnections<span><a class="mark" href="#net_server_maxconnections" id="net_server_maxconnections">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.2.0</span> </div> <p>Set this property to reject connections when the server's connection count gets high.</p> <p>It is not recommended to use this option once a socket has been sent to a child with <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>.</p> <h3>server.ref()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1645">[src]</a><span><a class="mark" href="#net_server_ref" id="net_server_ref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <ul> <li>Returns: <a href="#net_class_net_server" class="type"><net.Server></a></li> </ul> <p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref</code>ed server will <em>not</em> let the program exit if it's the only server left (the default behavior). If the server is <code>ref</code>ed calling <code>ref()</code> again will have no effect.</p> <h3>server.unref()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1654">[src]</a><span><a class="mark" href="#net_server_unref" id="net_server_unref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <ul> <li>Returns: <a href="#net_class_net_server" class="type"><net.Server></a></li> </ul> <p>Calling <code>unref()</code> on a server will allow the program to exit if this is the only active server in the event system. If the server is already <code>unref</code>ed calling <code>unref()</code> again will have no effect.</p> <h2>Class: net.Socket<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L225">[src]</a><span><a class="mark" href="#net_class_net_socket" id="net_class_net_socket">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.4</span> </div> <p>This class is an abstraction of a TCP socket or a streaming <a href="#net_ipc_support">IPC</a> endpoint (uses named pipes on Windows, and UNIX domain sockets otherwise). A <code>net.Socket</code> is also a <a href="#stream_class_stream_duplex">duplex stream</a>, so it can be both readable and writable, and it is also an <a href="#events_class_eventemitter"><code>EventEmitter</code></a>.</p> <p>A <code>net.Socket</code> can be created by the user and used directly to interact with a server. For example, it is returned by <a href="#net_net_createconnection"><code>net.createConnection()</code></a>, so the user can use it to talk to the server.</p> <p>It can also be created by Node.js and passed to the user when a connection is received. For example, it is passed to the listeners of a <a href="#net_event_connection"><code>'connection'</code></a> event emitted on a <a href="#net_class_net_server"><code>net.Server</code></a>, so the user can use it to interact with the client.</p> <h3>new net.Socket([options])<span><a class="mark" href="#net_new_net_socket_options" id="net_new_net_socket_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.4</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Available options are:</p> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If specified, wrap around an existing socket with the given file descriptor, otherwise a new socket will be created.</li> <li><code>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether half-opened TCP connections are allowed. See <a href="#net_net_createserver_options_connectionlistener"><code>net.createServer()</code></a> and the <a href="#net_event_end"><code>'end'</code></a> event for details. <strong>Default:</strong> <code>false</code>.</li> <li><code>readable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Allow reads on the socket when an <code>fd</code> is passed, otherwise ignored. <strong>Default:</strong> <code>false</code>.</li> <li><code>writable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Allow writes on the socket when an <code>fd</code> is passed, otherwise ignored. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>Creates a new socket object.</p> <p>The newly created socket can be either a TCP socket or a streaming <a href="#net_ipc_support">IPC</a> endpoint, depending on what it <a href="#net_socket_connect"><code>connect()</code></a> to.</p> <h3>Event: 'close'<span><a class="mark" href="#net_event_close_1" id="net_event_close_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>hadError</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the socket had a transmission error.</li> </ul> <p>Emitted once the socket is fully closed. The argument <code>hadError</code> is a boolean which says if the socket was closed due to a transmission error.</p> <h3>Event: 'connect'<span><a class="mark" href="#net_event_connect" id="net_event_connect">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <p>Emitted when a socket connection is successfully established. See <a href="#net_net_createconnection"><code>net.createConnection()</code></a>.</p> <h3>Event: 'data'<span><a class="mark" href="#net_event_data" id="net_event_data">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Emitted when data is received. The argument <code>data</code> will be a <code>Buffer</code> or <code>String</code>. Encoding of data is set by <a href="#net_socket_setencoding_encoding"><code>socket.setEncoding()</code></a>.</p> <p>Note that the <strong>data will be lost</strong> if there is no listener when a <code>Socket</code> emits a <code>'data'</code> event.</p> <h3>Event: 'drain'<span><a class="mark" href="#net_event_drain" id="net_event_drain">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <p>Emitted when the write buffer becomes empty. Can be used to throttle uploads.</p> <p>See also: the return values of <code>socket.write()</code>.</p> <h3>Event: 'end'<span><a class="mark" href="#net_event_end" id="net_event_end">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <p>Emitted when the other end of the socket sends a FIN packet, thus ending the readable side of the socket.</p> <p>By default (<code>allowHalfOpen</code> is <code>false</code>) the socket will send a FIN packet back and destroy its file descriptor once it has written out its pending write queue. However, if <code>allowHalfOpen</code> is set to <code>true</code>, the socket will not automatically <a href="#net_socket_end_data_encoding_callback"><code>end()</code></a> its writable side, allowing the user to write arbitrary amounts of data. The user must call <a href="#net_socket_end_data_encoding_callback"><code>end()</code></a> explicitly to close the connection (i.e. sending a FIN packet back).</p> <h3>Event: 'error'<span><a class="mark" href="#net_event_error_1" id="net_event_error_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Emitted when an error occurs. The <code>'close'</code> event will be called directly following this event.</p> <h3>Event: 'lookup'<span><a class="mark" href="#net_event_lookup" id="net_event_lookup">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v5.10.0</td> <td><p>The <code>host</code> parameter is supported now.</p></td></tr> <tr><td>v0.11.3</td> <td><p><span>Added in: v0.11.3</span></p></td></tr> </tbody></table> </details> </div> <p>Emitted after resolving the hostname but before connecting. Not applicable to UNIX sockets.</p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The error object. See <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The IP address.</li> <li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> The address type. See <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The hostname.</li> </ul> <h3>Event: 'ready'<span><a class="mark" href="#net_event_ready" id="net_event_ready">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.11.0</span> </div> <p>Emitted when a socket is ready to be used.</p> <p>Triggered immediately after <code>'connect'</code>.</p> <h3>Event: 'timeout'<span><a class="mark" href="#net_event_timeout" id="net_event_timeout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <p>Emitted if the socket times out from inactivity. This is only to notify that the socket has been idle. The user must manually close the connection.</p> <p>See also: <a href="#net_socket_settimeout_timeout_callback"><code>socket.setTimeout()</code></a>.</p> <h3>socket.address()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L505">[src]</a><span><a class="mark" href="#net_socket_address" id="net_socket_address">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns the bound <code>address</code>, the address <code>family</code> name and <code>port</code> of the socket as reported by the operating system: <code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code></p> <h3>socket.bufferSize<span><a class="mark" href="#net_socket_buffersize" id="net_socket_buffersize">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.8</span> </div> <p><code>net.Socket</code> has the property that <code>socket.write()</code> always works. This is to help users get up and running quickly. The computer cannot always keep up with the amount of data that is written to a socket - the network connection simply might be too slow. Node.js will internally queue up the data written to a socket and send it out over the wire when it is possible. (Internally it is polling on the socket's file descriptor for being writable).</p> <p>The consequence of this internal buffering is that memory may grow. This property shows the number of characters currently buffered to be written. (Number of characters is approximately equal to the number of bytes to be written, but the buffer may contain strings, and the strings are lazily encoded, so the exact number of bytes is not known.)</p> <p>Users who experience large or growing <code>bufferSize</code> should attempt to "throttle" the data flows in their program with <a href="#net_socket_pause"><code>socket.pause()</code></a> and <a href="#net_socket_resume"><code>socket.resume()</code></a>.</p> <h3>socket.bytesRead<span><a class="mark" href="#net_socket_bytesread" id="net_socket_bytesread">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.3</span> </div> <p>The amount of received bytes.</p> <h3>socket.bytesWritten<span><a class="mark" href="#net_socket_byteswritten" id="net_socket_byteswritten">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.3</span> </div> <p>The amount of bytes sent.</p> <h3>socket.connect()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L888">[src]</a><span><a class="mark" href="#net_socket_connect" id="net_socket_connect">#</a></span></h3> <p>Initiate a connection on a given socket.</p> <p>Possible signatures:</p> <ul> <li><a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a></li> <li><a href="#net_socket_connect_path_connectlistener"><code>socket.connect(path[, connectListener])</code></a> for <a href="#net_ipc_support">IPC</a> connections.</li> <li><a href="#net_socket_connect_port_host_connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a> for TCP connections.</li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>This function is asynchronous. When the connection is established, the <a href="#net_event_connect"><code>'connect'</code></a> event will be emitted. If there is a problem connecting, instead of a <a href="#net_event_connect"><code>'connect'</code></a> event, an <a href="#net_event_error_1"><code>'error'</code></a> event will be emitted with the error passed to the <a href="#net_event_error_1"><code>'error'</code></a> listener. The last parameter <code>connectListener</code>, if supplied, will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event <strong>once</strong>.</p> <h4>socket.connect(options[, connectListener])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L888">[src]</a><span><a class="mark" href="#net_socket_connect_options_connectlistener" id="net_socket_connect_options_connectlistener">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>The <code>hints</code> option defaults to <code>0</code> in all cases now. Previously, in the absence of the <code>family</code> option it would default to <code>dns.ADDRCONFIG | dns.V4MAPPED</code>.</p></td></tr> <tr><td>v5.11.0</td> <td><p>The <code>hints</code> option is supported now.</p></td></tr> <tr><td>v0.1.90</td> <td><p><span>Added in: v0.1.90</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of <a href="#net_socket_connect"><code>socket.connect()</code></a> methods. Will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once.</li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Initiate a connection on a given socket. Normally this method is not needed, the socket should be created and opened with <a href="#net_net_createconnection"><code>net.createConnection()</code></a>. Use this only when implementing a custom Socket.</p> <p>For TCP connections, available <code>options</code> are:</p> <ul> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Required. Port the socket should connect to.</li> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host the socket should connect to. <strong>Default:</strong> <code>'localhost'</code>.</li> <li><code>localAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Local address the socket should connect from.</li> <li><code>localPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Local port the socket should connect from.</li> <li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a>: Version of IP stack, can be either <code>4</code> or <code>6</code>. <strong>Default:</strong> <code>4</code>.</li> <li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optional <a href="#dns_supported_getaddrinfo_flags"><code>dns.lookup()</code> hints</a>.</li> <li><code>lookup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Custom lookup function. <strong>Default:</strong> <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li> </ul> <p>For <a href="#net_ipc_support">IPC</a> connections, available <code>options</code> are:</p> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Required. Path the client should connect to. See <a href="#net_identifying_paths_for_ipc_connections">Identifying paths for IPC connections</a>. If provided, the TCP-specific options above are ignored.</li> </ul> <h4>socket.connect(path[, connectListener])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L888">[src]</a><span><a class="mark" href="#net_socket_connect_path_connectlistener" id="net_socket_connect_path_connectlistener">#</a></span></h4> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Path the client should connect to. See <a href="#net_identifying_paths_for_ipc_connections">Identifying paths for IPC connections</a>.</li> <li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of <a href="#net_socket_connect"><code>socket.connect()</code></a> methods. Will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once.</li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Initiate an <a href="#net_ipc_support">IPC</a> connection on the given socket.</p> <p>Alias to <a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a> called with <code>{ path: path }</code> as <code>options</code>.</p> <h4>socket.connect(port[, host][, connectlistener])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L888">[src]</a><span><a class="mark" href="#net_socket_connect_port_host_connectlistener" id="net_socket_connect_port_host_connectlistener">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port the client should connect to.</li> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host the client should connect to.</li> <li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of <a href="#net_socket_connect"><code>socket.connect()</code></a> methods. Will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once.</li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Initiate a TCP connection on the given socket.</p> <p>Alias to <a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a> called with <code>{port: port, host: host}</code> as <code>options</code>.</p> <h3>socket.connecting<span><a class="mark" href="#net_socket_connecting" id="net_socket_connecting">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.1.0</span> </div> <p>If <code>true</code>, <a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a> was called and has not yet finished. It will stay <code>true</code> until the socket becomes connected, then it is set to <code>false</code> and the <code>'connect'</code> event is emitted. Note that the <a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a> callback is a listener for the <code>'connect'</code> event.</p> <h3>socket.destroy([exception])<span><a class="mark" href="#net_socket_destroy_exception" id="net_socket_destroy_exception">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>exception</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a></li> </ul> <p>Ensures that no more I/O activity happens on this socket. Only necessary in case of errors (parse error or so).</p> <p>If <code>exception</code> is specified, an <a href="#net_event_error_1"><code>'error'</code></a> event will be emitted and any listeners for that event will receive <code>exception</code> as an argument.</p> <h3>socket.destroyed<span><a class="mark" href="#net_socket_destroyed" id="net_socket_destroyed">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates if the connection is destroyed or not. Once a connection is destroyed no further data can be transferred using it.</li> </ul> <h3>socket.end([data][, encoding][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L544">[src]</a><span><a class="mark" href="#net_socket_end_data_encoding_callback" id="net_socket_end_data_encoding_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Only used when data is <code>string</code>. <strong>Default:</strong> <code>'utf8'</code>.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional callback for when the socket is finished.</li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.</p> <p>If <code>data</code> is specified, it is equivalent to calling <code>socket.write(data, encoding)</code> followed by <a href="#net_socket_end_data_encoding_callback"><code>socket.end()</code></a>.</p> <h3>socket.localAddress<span><a class="mark" href="#net_socket_localaddress" id="net_socket_localaddress">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.6</span> </div> <p>The string representation of the local IP address the remote client is connecting on. For example, in a server listening on <code>'0.0.0.0'</code>, if a client connects on <code>'192.168.1.1'</code>, the value of <code>socket.localAddress</code> would be <code>'192.168.1.1'</code>.</p> <h3>socket.localPort<span><a class="mark" href="#net_socket_localport" id="net_socket_localport">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.6</span> </div> <p>The numeric representation of the local port. For example, <code>80</code> or <code>21</code>.</p> <h3>socket.pause()<span><a class="mark" href="#net_socket_pause" id="net_socket_pause">#</a></span></h3> <ul> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Pauses the reading of data. That is, <a href="#net_event_data"><code>'data'</code></a> events will not be emitted. Useful to throttle back an upload.</p> <h3>socket.pending<span><a class="mark" href="#net_socket_pending" id="net_socket_pending">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>This is <code>true</code> if the socket is not connected yet, either because <code>.connect()</code> has not yet been called or because it is still in the process of connecting (see <a href="#net_socket_connecting"><code>socket.connecting</code></a>).</p> <h3>socket.ref()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L632">[src]</a><span><a class="mark" href="#net_socket_ref" id="net_socket_ref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <ul> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref</code>ed socket will <em>not</em> let the program exit if it's the only socket left (the default behavior). If the socket is <code>ref</code>ed calling <code>ref</code> again will have no effect.</p> <h3>socket.remoteAddress<span><a class="mark" href="#net_socket_remoteaddress" id="net_socket_remoteaddress">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.10</span> </div> <p>The string representation of the remote IP address. For example, <code>'74.125.127.100'</code> or <code>'2001:4860:a005::68'</code>. Value may be <code>undefined</code> if the socket is destroyed (for example, if the client disconnected).</p> <h3>socket.remoteFamily<span><a class="mark" href="#net_socket_remotefamily" id="net_socket_remotefamily">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <p>The string representation of the remote IP family. <code>'IPv4'</code> or <code>'IPv6'</code>.</p> <h3>socket.remotePort<span><a class="mark" href="#net_socket_remoteport" id="net_socket_remoteport">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.10</span> </div> <p>The numeric representation of the remote port. For example, <code>80</code> or <code>21</code>.</p> <h3>socket.resume()<span><a class="mark" href="#net_socket_resume" id="net_socket_resume">#</a></span></h3> <ul> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Resumes reading after a call to <a href="#net_socket_pause"><code>socket.pause()</code></a>.</p> <h3>socket.setEncoding([encoding])<span><a class="mark" href="#net_socket_setencoding_encoding" id="net_socket_setencoding_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Set the encoding for the socket as a <a href="#stream_class_stream_readable">Readable Stream</a>. See <a href="#stream_readable_setencoding_encoding"><code>readable.setEncoding()</code></a> for more information.</p> <h3>socket.setKeepAlive([enable][, initialdelay])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L462">[src]</a><span><a class="mark" href="#net_socket_setkeepalive_enable_initialdelay" id="net_socket_setkeepalive_enable_initialdelay">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.92</span> </div> <ul> <li><code>enable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li> <li><code>initialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> <strong>Default:</strong> <code>0</code></li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sent on an idle socket.</p> <p>Set <code>initialDelay</code> (in milliseconds) to set the delay between the last data packet received and the first keepalive probe. Setting <code>0</code> for <code>initialDelay</code> will leave the value unchanged from the default (or previous) setting.</p> <h3>socket.setNoDelay([noDelay])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L447">[src]</a><span><a class="mark" href="#net_socket_setnodelay_nodelay" id="net_socket_setnodelay_nodelay">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>noDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>true</code></li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Disables the Nagle algorithm. By default TCP connections use the Nagle algorithm, they buffer data before sending it off. Setting <code>true</code> for <code>noDelay</code> will immediately fire off data each time <code>socket.write()</code> is called.</p> <h3>socket.setTimeout(timeout[, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L405">[src]</a><span><a class="mark" href="#net_socket_settimeout_timeout_callback" id="net_socket_settimeout_timeout_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Sets the socket to timeout after <code>timeout</code> milliseconds of inactivity on the socket. By default <code>net.Socket</code> do not have a timeout.</p> <p>When an idle timeout is triggered the socket will receive a <a href="#net_event_timeout"><code>'timeout'</code></a> event but the connection will not be severed. The user must manually call <a href="#net_socket_end_data_encoding_callback"><code>socket.end()</code></a> or <a href="#net_socket_destroy_exception"><code>socket.destroy()</code></a> to end the connection.</p> <pre><code class="language-js">socket.setTimeout(3000); socket.on('timeout', () => { console.log('socket timeout'); socket.end(); }); </code></pre> <p>If <code>timeout</code> is 0, then the existing idle timeout is disabled.</p> <p>The optional <code>callback</code> parameter will be added as a one-time listener for the <a href="#net_event_timeout"><code>'timeout'</code></a> event.</p> <h3>socket.unref()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L642">[src]</a><span><a class="mark" href="#net_socket_unref" id="net_socket_unref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <ul> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li> </ul> <p>Calling <code>unref()</code> on a socket will allow the program to exit if this is the only active socket in the event system. If the socket is already <code>unref</code>ed calling <code>unref()</code> again will have no effect.</p> <h3>socket.write(data[, encoding][, callback])<span><a class="mark" href="#net_socket_write_data_encoding_callback" id="net_socket_write_data_encoding_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Only used when data is <code>string</code>. <strong>Default:</strong> <code>utf8</code>.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Sends data on the socket. The second parameter specifies the encoding in the case of a string. It defaults to UTF8 encoding.</p> <p>Returns <code>true</code> if the entire data was flushed successfully to the kernel buffer. Returns <code>false</code> if all or part of the data was queued in user memory. <a href="#net_event_drain"><code>'drain'</code></a> will be emitted when the buffer is again free.</p> <p>The optional <code>callback</code> parameter will be executed when the data is finally written out - this may not be immediately.</p> <p>See <code>Writable</code> stream <a href="#stream_writable_write_chunk_encoding_callback"><code>write()</code></a> method for more information.</p> <h2>net.connect()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L147">[src]</a><span><a class="mark" href="#net_net_connect" id="net_net_connect">#</a></span></h2> <p>Aliases to <a href="#net_net_createconnection"><code>net.createConnection()</code></a>.</p> <p>Possible signatures:</p> <ul> <li><a href="#net_net_connect_options_connectlistener"><code>net.connect(options[, connectListener])</code></a></li> <li><a href="#net_net_connect_path_connectlistener"><code>net.connect(path[, connectListener])</code></a> for <a href="#net_ipc_support">IPC</a> connections.</li> <li><a href="#net_net_connect_port_host_connectlistener"><code>net.connect(port[, host][, connectListener])</code></a> for TCP connections.</li> </ul> <h3>net.connect(options[, connectListener])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L147">[src]</a><span><a class="mark" href="#net_net_connect_options_connectlistener" id="net_net_connect_options_connectlistener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Alias to <a href="#net_net_createconnection_options_connectlistener"><code>net.createConnection(options[, connectListener])</code></a>.</p> <h3>net.connect(path[, connectListener])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L147">[src]</a><span><a class="mark" href="#net_net_connect_path_connectlistener" id="net_net_connect_path_connectlistener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Alias to <a href="#net_net_createconnection_path_connectlistener"><code>net.createConnection(path[, connectListener])</code></a>.</p> <h3>net.connect(port[, host][, connectlistener])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L147">[src]</a><span><a class="mark" href="#net_net_connect_port_host_connectlistener" id="net_net_connect_port_host_connectlistener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Alias to <a href="#net_net_createconnection_port_host_connectlistener"><code>net.createConnection(port[, host][, connectListener])</code></a>.</p> <h2>net.createConnection()<span><a class="mark" href="#net_net_createconnection" id="net_net_createconnection">#</a></span></h2> <p>A factory function, which creates a new <a href="#net_class_net_socket"><code>net.Socket</code></a>, immediately initiates connection with <a href="#net_socket_connect"><code>socket.connect()</code></a>, then returns the <code>net.Socket</code> that starts the connection.</p> <p>When the connection is established, a <a href="#net_event_connect"><code>'connect'</code></a> event will be emitted on the returned socket. The last parameter <code>connectListener</code>, if supplied, will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event <strong>once</strong>.</p> <p>Possible signatures:</p> <ul> <li><a href="#net_net_createconnection_options_connectlistener"><code>net.createConnection(options[, connectListener])</code></a></li> <li><a href="#net_net_createconnection_path_connectlistener"><code>net.createConnection(path[, connectListener])</code></a> for <a href="#net_ipc_support">IPC</a> connections.</li> <li><a href="#net_net_createconnection_port_host_connectlistener"><code>net.createConnection(port[, host][, connectListener])</code></a> for TCP connections.</li> </ul> <p>The <a href="#net_net_connect"><code>net.connect()</code></a> function is an alias to this function.</p> <h3>net.createConnection(options[, connectListener])<span><a class="mark" href="#net_net_createconnection_options_connectlistener" id="net_net_createconnection_options_connectlistener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Required. Will be passed to both the <a href="#net_new_net_socket_options"><code>new net.Socket([options])</code></a> call and the <a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a> method.</li> <li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of the <a href="#net_net_createconnection"><code>net.createConnection()</code></a> functions. If supplied, will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event on the returned socket once.</li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The newly created socket used to start the connection.</li> </ul> <p>For available options, see <a href="#net_new_net_socket_options"><code>new net.Socket([options])</code></a> and <a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a>.</p> <p>Additional options:</p> <ul> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If set, will be used to call <a href="#net_socket_settimeout_timeout_callback"><code>socket.setTimeout(timeout)</code></a> after the socket is created, but before it starts the connection.</li> </ul> <p>Following is an example of a client of the echo server described in the <a href="#net_net_createserver_options_connectionlistener"><code>net.createServer()</code></a> section:</p> <pre><code class="language-js">const net = require('net'); const client = net.createConnection({ port: 8124 }, () => { // 'connect' listener console.log('connected to server!'); client.write('world!\r\n'); }); client.on('data', (data) => { console.log(data.toString()); client.end(); }); client.on('end', () => { console.log('disconnected from server'); }); </code></pre> <p>To connect on the socket <code>/tmp/echo.sock</code> the second line would just be changed to:</p> <pre><code class="language-js">const client = net.createConnection({ path: '/tmp/echo.sock' }); </code></pre> <h3>net.createConnection(path[, connectListener])<span><a class="mark" href="#net_net_createconnection_path_connectlistener" id="net_net_createconnection_path_connectlistener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Path the socket should connect to. Will be passed to <a href="#net_socket_connect_path_connectlistener"><code>socket.connect(path[, connectListener])</code></a>. See <a href="#net_identifying_paths_for_ipc_connections">Identifying paths for IPC connections</a>.</li> <li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of the <a href="#net_net_createconnection"><code>net.createConnection()</code></a> functions, an "once" listener for the <code>'connect'</code> event on the initiating socket. Will be passed to <a href="#net_socket_connect_path_connectlistener"><code>socket.connect(path[, connectListener])</code></a>.</li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The newly created socket used to start the connection.</li> </ul> <p>Initiates an <a href="#net_ipc_support">IPC</a> connection.</p> <p>This function creates a new <a href="#net_class_net_socket"><code>net.Socket</code></a> with all options set to default, immediately initiates connection with <a href="#net_socket_connect_path_connectlistener"><code>socket.connect(path[, connectListener])</code></a>, then returns the <code>net.Socket</code> that starts the connection.</p> <h3>net.createConnection(port[, host][, connectlistener])<span><a class="mark" href="#net_net_createconnection_port_host_connectlistener" id="net_net_createconnection_port_host_connectlistener">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.90</span> </div> <ul> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port the socket should connect to. Will be passed to <a href="#net_socket_connect_port_host_connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>.</li> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host the socket should connect to. Will be passed to <a href="#net_socket_connect_port_host_connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>. <strong>Default:</strong> <code>'localhost'</code>.</li> <li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Common parameter of the <a href="#net_net_createconnection"><code>net.createConnection()</code></a> functions, an "once" listener for the <code>'connect'</code> event on the initiating socket. Will be passed to <a href="#net_socket_connect_port_host_connectlistener"><code>socket.connect(path[, connectListener])</code></a>.</li> <li>Returns: <a href="#net_class_net_socket" class="type"><net.Socket></a> The newly created socket used to start the connection.</li> </ul> <p>Initiates a TCP connection.</p> <p>This function creates a new <a href="#net_class_net_socket"><code>net.Socket</code></a> with all options set to default, immediately initiates connection with <a href="#net_socket_connect_port_host_connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>, then returns the <code>net.Socket</code> that starts the connection.</p> <h2>net.createServer([options][, connectionlistener])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L130">[src]</a><span><a class="mark" href="#net_net_createserver_options_connectionlistener" id="net_net_createserver_options_connectionlistener">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether half-opened TCP connections are allowed. <strong>Default:</strong> <code>false</code>.</li> <li><code>pauseOnConnect</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Indicates whether the socket should be paused on incoming connections. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li><code>connectionListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Automatically set as a listener for the <a href="#net_event_connection"><code>'connection'</code></a> event.</li> <li>Returns: <a href="#net_class_net_server" class="type"><net.Server></a></li> </ul> <p>Creates a new TCP or <a href="#net_ipc_support">IPC</a> server.</p> <p>If <code>allowHalfOpen</code> is set to <code>true</code>, when the other end of the socket sends a FIN packet, the server will only send a FIN packet back when <a href="#net_socket_end_data_encoding_callback"><code>socket.end()</code></a> is explicitly called, until then the connection is half-closed (non-readable but still writable). See <a href="#net_event_end"><code>'end'</code></a> event and <a href="https://tools.ietf.org/html/rfc1122">RFC 1122</a> (section 4.2.2.13) for more information.</p> <p>If <code>pauseOnConnect</code> is set to <code>true</code>, then the socket associated with each incoming connection will be paused, and no data will be read from its handle. This allows connections to be passed between processes without any data being read by the original process. To begin reading data from a paused socket, call <a href="#net_socket_resume"><code>socket.resume()</code></a>.</p> <p>The server can be a TCP server or an <a href="#net_ipc_support">IPC</a> server, depending on what it <a href="#net_server_listen"><code>listen()</code></a> to.</p> <p>Here is an example of an TCP echo server which listens for connections on port 8124:</p> <pre><code class="language-js">const net = require('net'); const server = net.createServer((c) => { // 'connection' listener console.log('client connected'); c.on('end', () => { console.log('client disconnected'); }); c.write('hello\r\n'); c.pipe(c); }); server.on('error', (err) => { throw err; }); server.listen(8124, () => { console.log('server bound'); }); </code></pre> <p>Test this by using <code>telnet</code>:</p> <pre><code class="language-console">$ telnet localhost 8124 </code></pre> <p>To listen on the socket <code>/tmp/echo.sock</code> the third line from the last would just be changed to:</p> <pre><code class="language-js">server.listen('/tmp/echo.sock', () => { console.log('server bound'); }); </code></pre> <p>Use <code>nc</code> to connect to a UNIX domain socket server:</p> <pre><code class="language-console">$ nc -U /tmp/echo.sock </code></pre> <h2>net.isIP(input)<span><a class="mark" href="#net_net_isip_input" id="net_net_isip_input">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Tests if input is an IP address. Returns <code>0</code> for invalid strings, returns <code>4</code> for IP version 4 addresses, and returns <code>6</code> for IP version 6 addresses.</p> <h2>net.isIPv4(input)<span><a class="mark" href="#net_net_isipv4_input" id="net_net_isipv4_input">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if input is a version 4 IP address, otherwise returns <code>false</code>.</p> <h2>net.isIPv6(input)<span><a class="mark" href="#net_net_isipv6_input" id="net_net_isipv6_input">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if input is a version 6 IP address, otherwise returns <code>false</code>.</p> <h1>OS<span><a class="mark" href="#os_os" id="os_os">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>os</code> module provides a number of operating system-related utility methods. It can be accessed using:</p> <pre><code class="language-js">const os = require('os'); </code></pre> <h2>os.EOL<span><a class="mark" href="#os_os_eol" id="os_os_eol">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.8</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>A string constant defining the operating system-specific end-of-line marker:</p> <ul> <li><code>\n</code> on POSIX</li> <li><code>\r\n</code> on Windows</li> </ul> <h2>os.arch()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/os.js#L112">[src]</a><span><a class="mark" href="#os_os_arch" id="os_os_arch">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>os.arch()</code> method returns a string identifying the operating system CPU architecture for which the Node.js binary was compiled.</p> <p>The current possible values are: <code>'arm'</code>, <code>'arm64'</code>, <code>'ia32'</code>, <code>'mips'</code>, <code>'mipsel'</code>, <code>'ppc'</code>, <code>'ppc64'</code>, <code>'s390'</code>, <code>'s390x'</code>, <code>'x32'</code>, and <code>'x64'</code>.</p> <p>Equivalent to <a href="#process_process_arch"><code>process.arch</code></a>.</p> <h2>os.constants<span><a class="mark" href="#os_os_constants" id="os_os_constants">#</a></span></h2> <div class="api_metadata"> <span>Added in: v6.3.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns an object containing commonly used operating system specific constants for error codes, process signals, and so on. The specific constants currently defined are described in <a href="#os_os_constants_1">OS Constants</a>.</p> <h2>os.cpus()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/os.js#L108">[src]</a><span><a class="mark" href="#os_os_cpus" id="os_os_cpus">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.3</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> <p>The <code>os.cpus()</code> method returns an array of objects containing information about each logical CPU core.</p> <p>The properties included on each object include:</p> <ul> <li><code>model</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>speed</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> (in MHz)</li> <li> <p><code>times</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>user</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds the CPU has spent in user mode.</li> <li><code>nice</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds the CPU has spent in nice mode.</li> <li><code>sys</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds the CPU has spent in sys mode.</li> <li><code>idle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds the CPU has spent in idle mode.</li> <li><code>irq</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds the CPU has spent in irq mode.</li> </ul> </li> </ul> <!-- eslint-disable semi --> <pre><code class="language-js">[ { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 252020, nice: 0, sys: 30340, idle: 1070356870, irq: 0 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 306960, nice: 0, sys: 26980, idle: 1071569080, irq: 0 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 248450, nice: 0, sys: 21750, idle: 1070919370, irq: 0 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 256880, nice: 0, sys: 19430, idle: 1070905480, irq: 20 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 511580, nice: 20, sys: 40900, idle: 1070842510, irq: 0 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 291660, nice: 0, sys: 34360, idle: 1070888000, irq: 10 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 308260, nice: 0, sys: 55410, idle: 1071129970, irq: 880 } }, { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', speed: 2926, times: { user: 266450, nice: 1480, sys: 34920, idle: 1072572010, irq: 30 } } ] </code></pre> <p>Because <code>nice</code> values are UNIX-specific, on Windows the <code>nice</code> values of all processors are always 0.</p> <h2>os.endianness()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/os.js#L143">[src]</a><span><a class="mark" href="#os_os_endianness" id="os_os_endianness">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>os.endianness()</code> method returns a string identifying the endianness of the CPU <em>for which the Node.js binary was compiled</em>.</p> <p>Possible values are:</p> <ul> <li><code>'BE'</code> for big endian</li> <li><code>'LE'</code> for little endian.</li> </ul> <h2>os.freemem()<span><a class="mark" href="#os_os_freemem" id="os_os_freemem">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.3</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>The <code>os.freemem()</code> method returns the amount of free system memory in bytes as an integer.</p> <h2>os.getPriority([pid])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/os.js#L226">[src]</a><span><a class="mark" href="#os_os_getpriority_pid" id="os_os_getpriority_pid">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The process ID to retrieve scheduling priority for. <strong>Default</strong> <code>0</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>The <code>os.getPriority()</code> method returns the scheduling priority for the process specified by <code>pid</code>. If <code>pid</code> is not provided, or is <code>0</code>, the priority of the current process is returned.</p> <h2>os.homedir()<span><a class="mark" href="#os_os_homedir" id="os_os_homedir">#</a></span></h2> <div class="api_metadata"> <span>Added in: v2.3.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>os.homedir()</code> method returns the home directory of the current user as a string.</p> <h2>os.hostname()<span><a class="mark" href="#os_os_hostname" id="os_os_hostname">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.3</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>os.hostname()</code> method returns the hostname of the operating system as a string.</p> <h2>os.loadavg()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/os.js#L87">[src]</a><span><a class="mark" href="#os_os_loadavg" id="os_os_loadavg">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.3</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number[]></a></li> </ul> <p>The <code>os.loadavg()</code> method returns an array containing the 1, 5, and 15 minute load averages.</p> <p>The load average is a measure of system activity, calculated by the operating system and expressed as a fractional number. As a rule of thumb, the load average should ideally be less than the number of logical CPUs in the system.</p> <p>The load average is a UNIX-specific concept with no real equivalent on Windows platforms. On Windows, the return value is always <code>[0, 0, 0]</code>.</p> <h2>os.networkInterfaces()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/os.js#L197">[src]</a><span><a class="mark" href="#os_os_networkinterfaces" id="os_os_networkinterfaces">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.6.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>os.networkInterfaces()</code> method returns an object containing only network interfaces that have been assigned a network address.</p> <p>Each key on the returned object identifies a network interface. The associated value is an array of objects that each describe an assigned network address.</p> <p>The properties available on the assigned network address object include:</p> <ul> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The assigned IPv4 or IPv6 address</li> <li><code>netmask</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The IPv4 or IPv6 network mask</li> <li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Either <code>IPv4</code> or <code>IPv6</code></li> <li><code>mac</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The MAC address of the network interface</li> <li><code>internal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the network interface is a loopback or similar interface that is not remotely accessible; otherwise <code>false</code></li> <li><code>scopeid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The numeric IPv6 scope ID (only specified when <code>family</code> is <code>IPv6</code>)</li> <li><code>cidr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The assigned IPv4 or IPv6 address with the routing prefix in CIDR notation. If the <code>netmask</code> is invalid, this property is set to <code>null</code>.</li> </ul> <!-- eslint-skip --> <pre><code class="language-js">{ lo: [ { address: '127.0.0.1', netmask: '255.0.0.0', family: 'IPv4', mac: '00:00:00:00:00:00', internal: true, cidr: '127.0.0.1/8' }, { address: '::1', netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', family: 'IPv6', mac: '00:00:00:00:00:00', scopeid: 0, internal: true, cidr: '::1/128' } ], eth0: [ { address: '192.168.1.108', netmask: '255.255.255.0', family: 'IPv4', mac: '01:02:03:0a:0b:0c', internal: false, cidr: '192.168.1.108/24' }, { address: 'fe80::a00:27ff:fe4e:66a1', netmask: 'ffff:ffff:ffff:ffff::', family: 'IPv6', mac: '01:02:03:0a:0b:0c', scopeid: 1, internal: false, cidr: 'fe80::a00:27ff:fe4e:66a1/64' } ] } </code></pre> <h2>os.platform()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/os.js#L117">[src]</a><span><a class="mark" href="#os_os_platform" id="os_os_platform">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>os.platform()</code> method returns a string identifying the operating system platform as set during compile time of Node.js.</p> <p>Currently possible values are:</p> <ul> <li><code>'aix'</code></li> <li><code>'darwin'</code></li> <li><code>'freebsd'</code></li> <li><code>'linux'</code></li> <li><code>'openbsd'</code></li> <li><code>'sunos'</code></li> <li><code>'win32'</code></li> </ul> <p>Equivalent to <a href="#process_process_platform"><code>process.platform</code></a>.</p> <p>The value <code>'android'</code> may also be returned if the Node.js is built on the Android operating system. However, Android support in Node.js is considered <a href="https://github.com/nodejs/node/blob/master/BUILDING.md#androidandroid-based-devices-eg-firefox-os">to be experimental</a> at this time.</p> <h2>os.release()<span><a class="mark" href="#os_os_release" id="os_os_release">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.3</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>os.release()</code> method returns a string identifying the operating system release.</p> <p>On POSIX systems, the operating system release is determined by calling <a href="https://linux.die.net/man/3/uname"></a><a href="http://man7.org/linux/man-pages/man3/uname.3.html"><code>uname(3)</code></a>. On Windows, <code>GetVersionExW()</code> is used. Please see <a href="https://en.wikipedia.org/wiki/Uname#Examples">https://en.wikipedia.org/wiki/Uname#Examples</a> for more information.</p> <h2>os.setPriority([pid, ]priority)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/os.js#L211">[src]</a><span><a class="mark" href="#os_os_setpriority_pid_priority" id="os_os_setpriority_pid_priority">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The process ID to set scheduling priority for. <strong>Default</strong> <code>0</code>.</li> <li><code>priority</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The scheduling priority to assign to the process.</li> </ul> <p>The <code>os.setPriority()</code> method attempts to set the scheduling priority for the process specified by <code>pid</code>. If <code>pid</code> is not provided, or is <code>0</code>, the priority of the current process is used.</p> <p>The <code>priority</code> input must be an integer between <code>-20</code> (high priority) and <code>19</code> (low priority). Due to differences between Unix priority levels and Windows priority classes, <code>priority</code> is mapped to one of six priority constants in <code>os.constants.priority</code>. When retrieving a process priority level, this range mapping may cause the return value to be slightly different on Windows. To avoid confusion, it is recommended to set <code>priority</code> to one of the priority constants.</p> <p>On Windows setting priority to <code>PRIORITY_HIGHEST</code> requires elevated user, otherwise the set priority will be silently reduced to <code>PRIORITY_HIGH</code>.</p> <h2>os.tmpdir()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/os.js#L122">[src]</a><span><a class="mark" href="#os_os_tmpdir" id="os_os_tmpdir">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v2.0.0</td> <td><p>This function is now cross-platform consistent and no longer returns a path with a trailing slash on any platform</p></td></tr> <tr><td>v0.9.9</td> <td><p><span>Added in: v0.9.9</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>os.tmpdir()</code> method returns a string specifying the operating system's default directory for temporary files.</p> <h2>os.totalmem()<span><a class="mark" href="#os_os_totalmem" id="os_os_totalmem">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.3</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>The <code>os.totalmem()</code> method returns the total amount of system memory in bytes as an integer.</p> <h2>os.type()<span><a class="mark" href="#os_os_type" id="os_os_type">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.3</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>os.type()</code> method returns a string identifying the operating system name as returned by <a href="https://linux.die.net/man/3/uname"></a><a href="http://man7.org/linux/man-pages/man3/uname.3.html"><code>uname(3)</code></a>. For example, <code>'Linux'</code> on Linux, <code>'Darwin'</code> on macOS, and <code>'Windows_NT'</code> on Windows.</p> <p>Please see <a href="https://en.wikipedia.org/wiki/Uname#Examples">https://en.wikipedia.org/wiki/Uname#Examples</a> for additional information about the output of running <a href="https://linux.die.net/man/3/uname"></a><a href="http://man7.org/linux/man-pages/man3/uname.3.html"><code>uname(3)</code></a> on various operating systems.</p> <h2>os.uptime()<span><a class="mark" href="#os_os_uptime" id="os_os_uptime">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The result of this function no longer contains a fraction component on Windows.</p></td></tr> <tr><td>v0.3.3</td> <td><p><span>Added in: v0.3.3</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>The <code>os.uptime()</code> method returns the system uptime in number of seconds.</p> <h2>os.userInfo([options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/os.js#L241">[src]</a><span><a class="mark" href="#os_os_userinfo_options" id="os_os_userinfo_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Character encoding used to interpret resulting strings. If <code>encoding</code> is set to <code>'buffer'</code>, the <code>username</code>, <code>shell</code>, and <code>homedir</code> values will be <code>Buffer</code> instances. <strong>Default:</strong> <code>'utf8'</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>os.userInfo()</code> method returns information about the currently effective user — on POSIX platforms, this is typically a subset of the password file. The returned object includes the <code>username</code>, <code>uid</code>, <code>gid</code>, <code>shell</code>, and <code>homedir</code>. On Windows, the <code>uid</code> and <code>gid</code> fields are <code>-1</code>, and <code>shell</code> is <code>null</code>.</p> <p>The value of <code>homedir</code> returned by <code>os.userInfo()</code> is provided by the operating system. This differs from the result of <code>os.homedir()</code>, which queries several environment variables for the home directory before falling back to the operating system response.</p> <h2>OS Constants<span><a class="mark" href="#os_os_constants_1" id="os_os_constants_1">#</a></span></h2> <p>The following constants are exported by <code>os.constants</code>.</p> <p>Not all constants will be available on every operating system.</p> <h3>Signal Constants<span><a class="mark" href="#os_signal_constants" id="os_signal_constants">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v5.11.0</td> <td><p>Added support for <code>SIGINFO</code>.</p></td></tr> </tbody></table> </details> </div> <p>The following signal constants are exported by <code>os.constants.signals</code>:</p> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>SIGHUP</code></td> <td>Sent to indicate when a controlling terminal is closed or a parent process exits.</td> </tr> <tr> <td><code>SIGINT</code></td> <td>Sent to indicate when a user wishes to interrupt a process (<code>(Ctrl+C)</code>).</td> </tr> <tr> <td><code>SIGQUIT</code></td> <td>Sent to indicate when a user wishes to terminate a process and perform a core dump.</td> </tr> <tr> <td><code>SIGILL</code></td> <td>Sent to a process to notify that it has attempted to perform an illegal, malformed, unknown, or privileged instruction.</td> </tr> <tr> <td><code>SIGTRAP</code></td> <td>Sent to a process when an exception has occurred.</td> </tr> <tr> <td><code>SIGABRT</code></td> <td>Sent to a process to request that it abort.</td> </tr> <tr> <td><code>SIGIOT</code></td> <td>Synonym for <code>SIGABRT</code></td> </tr> <tr> <td><code>SIGBUS</code></td> <td>Sent to a process to notify that it has caused a bus error.</td> </tr> <tr> <td><code>SIGFPE</code></td> <td>Sent to a process to notify that it has performed an illegal arithmetic operation.</td> </tr> <tr> <td><code>SIGKILL</code></td> <td>Sent to a process to terminate it immediately.</td> </tr> <tr> <td><code>SIGUSR1</code> <code>SIGUSR2</code></td> <td>Sent to a process to identify user-defined conditions.</td> </tr> <tr> <td><code>SIGSEGV</code></td> <td>Sent to a process to notify of a segmentation fault.</td> </tr> <tr> <td><code>SIGPIPE</code></td> <td>Sent to a process when it has attempted to write to a disconnected pipe.</td> </tr> <tr> <td><code>SIGALRM</code></td> <td>Sent to a process when a system timer elapses.</td> </tr> <tr> <td><code>SIGTERM</code></td> <td>Sent to a process to request termination.</td> </tr> <tr> <td><code>SIGCHLD</code></td> <td>Sent to a process when a child process terminates.</td> </tr> <tr> <td><code>SIGSTKFLT</code></td> <td>Sent to a process to indicate a stack fault on a coprocessor.</td> </tr> <tr> <td><code>SIGCONT</code></td> <td>Sent to instruct the operating system to continue a paused process.</td> </tr> <tr> <td><code>SIGSTOP</code></td> <td>Sent to instruct the operating system to halt a process.</td> </tr> <tr> <td><code>SIGTSTP</code></td> <td>Sent to a process to request it to stop.</td> </tr> <tr> <td><code>SIGBREAK</code></td> <td>Sent to indicate when a user wishes to interrupt a process.</td> </tr> <tr> <td><code>SIGTTIN</code></td> <td>Sent to a process when it reads from the TTY while in the background.</td> </tr> <tr> <td><code>SIGTTOU</code></td> <td>Sent to a process when it writes to the TTY while in the background.</td> </tr> <tr> <td><code>SIGURG</code></td> <td>Sent to a process when a socket has urgent data to read.</td> </tr> <tr> <td><code>SIGXCPU</code></td> <td>Sent to a process when it has exceeded its limit on CPU usage.</td> </tr> <tr> <td><code>SIGXFSZ</code></td> <td>Sent to a process when it grows a file larger than the maximum allowed.</td> </tr> <tr> <td><code>SIGVTALRM</code></td> <td>Sent to a process when a virtual timer has elapsed.</td> </tr> <tr> <td><code>SIGPROF</code></td> <td>Sent to a process when a system timer has elapsed.</td> </tr> <tr> <td><code>SIGWINCH</code></td> <td>Sent to a process when the controlling terminal has changed its size.</td> </tr> <tr> <td><code>SIGIO</code></td> <td>Sent to a process when I/O is available.</td> </tr> <tr> <td><code>SIGPOLL</code></td> <td>Synonym for <code>SIGIO</code></td> </tr> <tr> <td><code>SIGLOST</code></td> <td>Sent to a process when a file lock has been lost.</td> </tr> <tr> <td><code>SIGPWR</code></td> <td>Sent to a process to notify of a power failure.</td> </tr> <tr> <td><code>SIGINFO</code></td> <td>Synonym for <code>SIGPWR</code></td> </tr> <tr> <td><code>SIGSYS</code></td> <td>Sent to a process to notify of a bad argument.</td> </tr> <tr> <td><code>SIGUNUSED</code></td> <td>Synonym for <code>SIGSYS</code></td> </tr> </tbody></table> <h3>Error Constants<span><a class="mark" href="#os_error_constants" id="os_error_constants">#</a></span></h3> <p>The following error constants are exported by <code>os.constants.errno</code>:</p> <h4>POSIX Error Constants<span><a class="mark" href="#os_posix_error_constants" id="os_posix_error_constants">#</a></span></h4> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>E2BIG</code></td> <td>Indicates that the list of arguments is longer than expected.</td> </tr> <tr> <td><code>EACCES</code></td> <td>Indicates that the operation did not have sufficient permissions.</td> </tr> <tr> <td><code>EADDRINUSE</code></td> <td>Indicates that the network address is already in use.</td> </tr> <tr> <td><code>EADDRNOTAVAIL</code></td> <td>Indicates that the network address is currently unavailable for use.</td> </tr> <tr> <td><code>EAFNOSUPPORT</code></td> <td>Indicates that the network address family is not supported.</td> </tr> <tr> <td><code>EAGAIN</code></td> <td>Indicates that there is currently no data available and to try the operation again later.</td> </tr> <tr> <td><code>EALREADY</code></td> <td>Indicates that the socket already has a pending connection in progress.</td> </tr> <tr> <td><code>EBADF</code></td> <td>Indicates that a file descriptor is not valid.</td> </tr> <tr> <td><code>EBADMSG</code></td> <td>Indicates an invalid data message.</td> </tr> <tr> <td><code>EBUSY</code></td> <td>Indicates that a device or resource is busy.</td> </tr> <tr> <td><code>ECANCELED</code></td> <td>Indicates that an operation was canceled.</td> </tr> <tr> <td><code>ECHILD</code></td> <td>Indicates that there are no child processes.</td> </tr> <tr> <td><code>ECONNABORTED</code></td> <td>Indicates that the network connection has been aborted.</td> </tr> <tr> <td><code>ECONNREFUSED</code></td> <td>Indicates that the network connection has been refused.</td> </tr> <tr> <td><code>ECONNRESET</code></td> <td>Indicates that the network connection has been reset.</td> </tr> <tr> <td><code>EDEADLK</code></td> <td>Indicates that a resource deadlock has been avoided.</td> </tr> <tr> <td><code>EDESTADDRREQ</code></td> <td>Indicates that a destination address is required.</td> </tr> <tr> <td><code>EDOM</code></td> <td>Indicates that an argument is out of the domain of the function.</td> </tr> <tr> <td><code>EDQUOT</code></td> <td>Indicates that the disk quota has been exceeded.</td> </tr> <tr> <td><code>EEXIST</code></td> <td>Indicates that the file already exists.</td> </tr> <tr> <td><code>EFAULT</code></td> <td>Indicates an invalid pointer address.</td> </tr> <tr> <td><code>EFBIG</code></td> <td>Indicates that the file is too large.</td> </tr> <tr> <td><code>EHOSTUNREACH</code></td> <td>Indicates that the host is unreachable.</td> </tr> <tr> <td><code>EIDRM</code></td> <td>Indicates that the identifier has been removed.</td> </tr> <tr> <td><code>EILSEQ</code></td> <td>Indicates an illegal byte sequence.</td> </tr> <tr> <td><code>EINPROGRESS</code></td> <td>Indicates that an operation is already in progress.</td> </tr> <tr> <td><code>EINTR</code></td> <td>Indicates that a function call was interrupted.</td> </tr> <tr> <td><code>EINVAL</code></td> <td>Indicates that an invalid argument was provided.</td> </tr> <tr> <td><code>EIO</code></td> <td>Indicates an otherwise unspecified I/O error.</td> </tr> <tr> <td><code>EISCONN</code></td> <td>Indicates that the socket is connected.</td> </tr> <tr> <td><code>EISDIR</code></td> <td>Indicates that the path is a directory.</td> </tr> <tr> <td><code>ELOOP</code></td> <td>Indicates too many levels of symbolic links in a path.</td> </tr> <tr> <td><code>EMFILE</code></td> <td>Indicates that there are too many open files.</td> </tr> <tr> <td><code>EMLINK</code></td> <td>Indicates that there are too many hard links to a file.</td> </tr> <tr> <td><code>EMSGSIZE</code></td> <td>Indicates that the provided message is too long.</td> </tr> <tr> <td><code>EMULTIHOP</code></td> <td>Indicates that a multihop was attempted.</td> </tr> <tr> <td><code>ENAMETOOLONG</code></td> <td>Indicates that the filename is too long.</td> </tr> <tr> <td><code>ENETDOWN</code></td> <td>Indicates that the network is down.</td> </tr> <tr> <td><code>ENETRESET</code></td> <td>Indicates that the connection has been aborted by the network.</td> </tr> <tr> <td><code>ENETUNREACH</code></td> <td>Indicates that the network is unreachable.</td> </tr> <tr> <td><code>ENFILE</code></td> <td>Indicates too many open files in the system.</td> </tr> <tr> <td><code>ENOBUFS</code></td> <td>Indicates that no buffer space is available.</td> </tr> <tr> <td><code>ENODATA</code></td> <td>Indicates that no message is available on the stream head read queue.</td> </tr> <tr> <td><code>ENODEV</code></td> <td>Indicates that there is no such device.</td> </tr> <tr> <td><code>ENOENT</code></td> <td>Indicates that there is no such file or directory.</td> </tr> <tr> <td><code>ENOEXEC</code></td> <td>Indicates an exec format error.</td> </tr> <tr> <td><code>ENOLCK</code></td> <td>Indicates that there are no locks available.</td> </tr> <tr> <td><code>ENOLINK</code></td> <td>Indications that a link has been severed.</td> </tr> <tr> <td><code>ENOMEM</code></td> <td>Indicates that there is not enough space.</td> </tr> <tr> <td><code>ENOMSG</code></td> <td>Indicates that there is no message of the desired type.</td> </tr> <tr> <td><code>ENOPROTOOPT</code></td> <td>Indicates that a given protocol is not available.</td> </tr> <tr> <td><code>ENOSPC</code></td> <td>Indicates that there is no space available on the device.</td> </tr> <tr> <td><code>ENOSR</code></td> <td>Indicates that there are no stream resources available.</td> </tr> <tr> <td><code>ENOSTR</code></td> <td>Indicates that a given resource is not a stream.</td> </tr> <tr> <td><code>ENOSYS</code></td> <td>Indicates that a function has not been implemented.</td> </tr> <tr> <td><code>ENOTCONN</code></td> <td>Indicates that the socket is not connected.</td> </tr> <tr> <td><code>ENOTDIR</code></td> <td>Indicates that the path is not a directory.</td> </tr> <tr> <td><code>ENOTEMPTY</code></td> <td>Indicates that the directory is not empty.</td> </tr> <tr> <td><code>ENOTSOCK</code></td> <td>Indicates that the given item is not a socket.</td> </tr> <tr> <td><code>ENOTSUP</code></td> <td>Indicates that a given operation is not supported.</td> </tr> <tr> <td><code>ENOTTY</code></td> <td>Indicates an inappropriate I/O control operation.</td> </tr> <tr> <td><code>ENXIO</code></td> <td>Indicates no such device or address.</td> </tr> <tr> <td><code>EOPNOTSUPP</code></td> <td>Indicates that an operation is not supported on the socket. Note that while <code>ENOTSUP</code> and <code>EOPNOTSUPP</code> have the same value on Linux, according to POSIX.1 these error values should be distinct.)</td> </tr> <tr> <td><code>EOVERFLOW</code></td> <td>Indicates that a value is too large to be stored in a given data type.</td> </tr> <tr> <td><code>EPERM</code></td> <td>Indicates that the operation is not permitted.</td> </tr> <tr> <td><code>EPIPE</code></td> <td>Indicates a broken pipe.</td> </tr> <tr> <td><code>EPROTO</code></td> <td>Indicates a protocol error.</td> </tr> <tr> <td><code>EPROTONOSUPPORT</code></td> <td>Indicates that a protocol is not supported.</td> </tr> <tr> <td><code>EPROTOTYPE</code></td> <td>Indicates the wrong type of protocol for a socket.</td> </tr> <tr> <td><code>ERANGE</code></td> <td>Indicates that the results are too large.</td> </tr> <tr> <td><code>EROFS</code></td> <td>Indicates that the file system is read only.</td> </tr> <tr> <td><code>ESPIPE</code></td> <td>Indicates an invalid seek operation.</td> </tr> <tr> <td><code>ESRCH</code></td> <td>Indicates that there is no such process.</td> </tr> <tr> <td><code>ESTALE</code></td> <td>Indicates that the file handle is stale.</td> </tr> <tr> <td><code>ETIME</code></td> <td>Indicates an expired timer.</td> </tr> <tr> <td><code>ETIMEDOUT</code></td> <td>Indicates that the connection timed out.</td> </tr> <tr> <td><code>ETXTBSY</code></td> <td>Indicates that a text file is busy.</td> </tr> <tr> <td><code>EWOULDBLOCK</code></td> <td>Indicates that the operation would block.</td> </tr> <tr> <td><code>EXDEV</code></td> <td>Indicates an improper link. </td></tr> </tbody></table> <h4>Windows Specific Error Constants<span><a class="mark" href="#os_windows_specific_error_constants" id="os_windows_specific_error_constants">#</a></span></h4> <p>The following error codes are specific to the Windows operating system:</p> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>WSAEINTR</code></td> <td>Indicates an interrupted function call.</td> </tr> <tr> <td><code>WSAEBADF</code></td> <td>Indicates an invalid file handle.</td> </tr> <tr> <td><code>WSAEACCES</code></td> <td>Indicates insufficient permissions to complete the operation.</td> </tr> <tr> <td><code>WSAEFAULT</code></td> <td>Indicates an invalid pointer address.</td> </tr> <tr> <td><code>WSAEINVAL</code></td> <td>Indicates that an invalid argument was passed.</td> </tr> <tr> <td><code>WSAEMFILE</code></td> <td>Indicates that there are too many open files.</td> </tr> <tr> <td><code>WSAEWOULDBLOCK</code></td> <td>Indicates that a resource is temporarily unavailable.</td> </tr> <tr> <td><code>WSAEINPROGRESS</code></td> <td>Indicates that an operation is currently in progress.</td> </tr> <tr> <td><code>WSAEALREADY</code></td> <td>Indicates that an operation is already in progress.</td> </tr> <tr> <td><code>WSAENOTSOCK</code></td> <td>Indicates that the resource is not a socket.</td> </tr> <tr> <td><code>WSAEDESTADDRREQ</code></td> <td>Indicates that a destination address is required.</td> </tr> <tr> <td><code>WSAEMSGSIZE</code></td> <td>Indicates that the message size is too long.</td> </tr> <tr> <td><code>WSAEPROTOTYPE</code></td> <td>Indicates the wrong protocol type for the socket.</td> </tr> <tr> <td><code>WSAENOPROTOOPT</code></td> <td>Indicates a bad protocol option.</td> </tr> <tr> <td><code>WSAEPROTONOSUPPORT</code></td> <td>Indicates that the protocol is not supported.</td> </tr> <tr> <td><code>WSAESOCKTNOSUPPORT</code></td> <td>Indicates that the socket type is not supported.</td> </tr> <tr> <td><code>WSAEOPNOTSUPP</code></td> <td>Indicates that the operation is not supported.</td> </tr> <tr> <td><code>WSAEPFNOSUPPORT</code></td> <td>Indicates that the protocol family is not supported.</td> </tr> <tr> <td><code>WSAEAFNOSUPPORT</code></td> <td>Indicates that the address family is not supported.</td> </tr> <tr> <td><code>WSAEADDRINUSE</code></td> <td>Indicates that the network address is already in use.</td> </tr> <tr> <td><code>WSAEADDRNOTAVAIL</code></td> <td>Indicates that the network address is not available.</td> </tr> <tr> <td><code>WSAENETDOWN</code></td> <td>Indicates that the network is down.</td> </tr> <tr> <td><code>WSAENETUNREACH</code></td> <td>Indicates that the network is unreachable.</td> </tr> <tr> <td><code>WSAENETRESET</code></td> <td>Indicates that the network connection has been reset.</td> </tr> <tr> <td><code>WSAECONNABORTED</code></td> <td>Indicates that the connection has been aborted.</td> </tr> <tr> <td><code>WSAECONNRESET</code></td> <td>Indicates that the connection has been reset by the peer.</td> </tr> <tr> <td><code>WSAENOBUFS</code></td> <td>Indicates that there is no buffer space available.</td> </tr> <tr> <td><code>WSAEISCONN</code></td> <td>Indicates that the socket is already connected.</td> </tr> <tr> <td><code>WSAENOTCONN</code></td> <td>Indicates that the socket is not connected.</td> </tr> <tr> <td><code>WSAESHUTDOWN</code></td> <td>Indicates that data cannot be sent after the socket has been shutdown.</td> </tr> <tr> <td><code>WSAETOOMANYREFS</code></td> <td>Indicates that there are too many references.</td> </tr> <tr> <td><code>WSAETIMEDOUT</code></td> <td>Indicates that the connection has timed out.</td> </tr> <tr> <td><code>WSAECONNREFUSED</code></td> <td>Indicates that the connection has been refused.</td> </tr> <tr> <td><code>WSAELOOP</code></td> <td>Indicates that a name cannot be translated.</td> </tr> <tr> <td><code>WSAENAMETOOLONG</code></td> <td>Indicates that a name was too long.</td> </tr> <tr> <td><code>WSAEHOSTDOWN</code></td> <td>Indicates that a network host is down.</td> </tr> <tr> <td><code>WSAEHOSTUNREACH</code></td> <td>Indicates that there is no route to a network host.</td> </tr> <tr> <td><code>WSAENOTEMPTY</code></td> <td>Indicates that the directory is not empty.</td> </tr> <tr> <td><code>WSAEPROCLIM</code></td> <td>Indicates that there are too many processes.</td> </tr> <tr> <td><code>WSAEUSERS</code></td> <td>Indicates that the user quota has been exceeded.</td> </tr> <tr> <td><code>WSAEDQUOT</code></td> <td>Indicates that the disk quota has been exceeded.</td> </tr> <tr> <td><code>WSAESTALE</code></td> <td>Indicates a stale file handle reference.</td> </tr> <tr> <td><code>WSAEREMOTE</code></td> <td>Indicates that the item is remote.</td> </tr> <tr> <td><code>WSASYSNOTREADY</code></td> <td>Indicates that the network subsystem is not ready.</td> </tr> <tr> <td><code>WSAVERNOTSUPPORTED</code></td> <td>Indicates that the <code>winsock.dll</code> version is out of range.</td> </tr> <tr> <td><code>WSANOTINITIALISED</code></td> <td>Indicates that successful WSAStartup has not yet been performed.</td> </tr> <tr> <td><code>WSAEDISCON</code></td> <td>Indicates that a graceful shutdown is in progress.</td> </tr> <tr> <td><code>WSAENOMORE</code></td> <td>Indicates that there are no more results.</td> </tr> <tr> <td><code>WSAECANCELLED</code></td> <td>Indicates that an operation has been canceled.</td> </tr> <tr> <td><code>WSAEINVALIDPROCTABLE</code></td> <td>Indicates that the procedure call table is invalid.</td> </tr> <tr> <td><code>WSAEINVALIDPROVIDER</code></td> <td>Indicates an invalid service provider.</td> </tr> <tr> <td><code>WSAEPROVIDERFAILEDINIT</code></td> <td>Indicates that the service provider failed to initialized.</td> </tr> <tr> <td><code>WSASYSCALLFAILURE</code></td> <td>Indicates a system call failure.</td> </tr> <tr> <td><code>WSASERVICE_NOT_FOUND</code></td> <td>Indicates that a service was not found.</td> </tr> <tr> <td><code>WSATYPE_NOT_FOUND</code></td> <td>Indicates that a class type was not found.</td> </tr> <tr> <td><code>WSA_E_NO_MORE</code></td> <td>Indicates that there are no more results.</td> </tr> <tr> <td><code>WSA_E_CANCELLED</code></td> <td>Indicates that the call was canceled.</td> </tr> <tr> <td><code>WSAEREFUSED</code></td> <td>Indicates that a database query was refused.</td> </tr> </tbody></table> <h3>dlopen Constants<span><a class="mark" href="#os_dlopen_constants" id="os_dlopen_constants">#</a></span></h3> <p>If available on the operating system, the following constants are exported in <code>os.constants.dlopen</code>. See <a href="http://man7.org/linux/man-pages/man3/dlopen.3.html"><code>dlopen(3)</code></a> for detailed information.</p> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>RTLD_LAZY</code></td> <td>Perform lazy binding. Node.js sets this flag by default.</td> </tr> <tr> <td><code>RTLD_NOW</code></td> <td>Resolve all undefined symbols in the library before dlopen(3) returns.</td> </tr> <tr> <td><code>RTLD_GLOBAL</code></td> <td>Symbols defined by the library will be made available for symbol resolution of subsequently loaded libraries.</td> </tr> <tr> <td><code>RTLD_LOCAL</code></td> <td>The converse of <code>RTLD_GLOBAL</code>. This is the default behavior if neither flag is specified.</td> </tr> <tr> <td><code>RTLD_DEEPBIND</code></td> <td>Make a self-contained library use its own symbols in preference to symbols from previously loaded libraries.</td> </tr> </tbody></table> <h3>Priority Constants<span><a class="mark" href="#os_priority_constants" id="os_priority_constants">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <p>The following process scheduling constants are exported by <code>os.constants.priority</code>:</p> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>PRIORITY_LOW</code></td> <td>The lowest process scheduling priority. This corresponds to <code>IDLE_PRIORITY_CLASS</code> on Windows, and a nice value of <code>19</code> on all other platforms.</td> </tr> <tr> <td><code>PRIORITY_BELOW_NORMAL</code></td> <td>The process scheduling priority above <code>PRIORITY_LOW</code> and below <code>PRIORITY_NORMAL</code>. This corresponds to <code>BELOW_NORMAL_PRIORITY_CLASS</code> on Windows, and a nice value of <code>10</code> on all other platforms.</td> </tr> <tr> <td><code>PRIORITY_NORMAL</code></td> <td>The default process scheduling priority. This corresponds to <code>NORMAL_PRIORITY_CLASS</code> on Windows, and a nice value of <code>0</code> on all other platforms.</td> </tr> <tr> <td><code>PRIORITY_ABOVE_NORMAL</code></td> <td>The process scheduling priority above <code>PRIORITY_NORMAL</code> and below <code>PRIORITY_HIGH</code>. This corresponds to <code>ABOVE_NORMAL_PRIORITY_CLASS</code> on Windows, and a nice value of <code>-7</code> on all other platforms.</td> </tr> <tr> <td><code>PRIORITY_HIGH</code></td> <td>The process scheduling priority above <code>PRIORITY_ABOVE_NORMAL</code> and below <code>PRIORITY_HIGHEST</code>. This corresponds to <code>HIGH_PRIORITY_CLASS</code> on Windows, and a nice value of <code>-14</code> on all other platforms.</td> </tr> <tr> <td><code>PRIORITY_HIGHEST</code></td> <td>The highest process scheduling priority. This corresponds to <code>REALTIME_PRIORITY_CLASS</code> on Windows, and a nice value of <code>-20</code> on all other platforms.</td> </tr> </tbody></table> <h3>libuv Constants<span><a class="mark" href="#os_libuv_constants" id="os_libuv_constants">#</a></span></h3> <table> <tbody><tr> <th>Constant</th> <th>Description</th> </tr> <tr> <td><code>UV_UDP_REUSEADDR</code></td> <td></td> </tr> </tbody></table> <h1>Path<span><a class="mark" href="#path_path" id="path_path">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>path</code> module provides utilities for working with file and directory paths. It can be accessed using:</p> <pre><code class="language-js">const path = require('path'); </code></pre> <h2>Windows vs. POSIX<span><a class="mark" href="#path_windows_vs_posix" id="path_windows_vs_posix">#</a></span></h2> <p>The default operation of the <code>path</code> module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the <code>path</code> module will assume that Windows-style paths are being used.</p> <p>So using <code>path.basename()</code> might yield different results on POSIX and Windows:</p> <p>On POSIX:</p> <pre><code class="language-js">path.basename('C:\\temp\\myfile.html'); // Returns: 'C:\\temp\\myfile.html' </code></pre> <p>On Windows:</p> <pre><code class="language-js">path.basename('C:\\temp\\myfile.html'); // Returns: 'myfile.html' </code></pre> <p>To achieve consistent results when working with Windows file paths on any operating system, use <a href="#path_path_win32"><code>path.win32</code></a>:</p> <p>On POSIX and Windows:</p> <pre><code class="language-js">path.win32.basename('C:\\temp\\myfile.html'); // Returns: 'myfile.html' </code></pre> <p>To achieve consistent results when working with POSIX file paths on any operating system, use <a href="#path_path_posix"><code>path.posix</code></a>:</p> <p>On POSIX and Windows:</p> <pre><code class="language-js">path.posix.basename('/tmp/myfile.html'); // Returns: 'myfile.html' </code></pre> <p>On Windows Node.js follows the concept of per-drive working directory. This behavior can be observed when using a drive path without a backslash. For example, <code>path.resolve('c:\\')</code> can potentially return a different result than <code>path.resolve('c:')</code>. For more information, see <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths">this MSDN page</a>.</p> <h2>path.basename(path[, ext])<span><a class="mark" href="#path_path_basename_path_ext" id="path_path_basename_path_ext">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>Passing a non-string as the <code>path</code> argument will throw now.</p></td></tr> <tr><td>v0.1.25</td> <td><p><span>Added in: v0.1.25</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>ext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> An optional file extension</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>path.basename()</code> methods returns the last portion of a <code>path</code>, similar to the Unix <code>basename</code> command. Trailing directory separators are ignored, see <a href="#path_path_sep"><code>path.sep</code></a>.</p> <pre><code class="language-js">path.basename('/foo/bar/baz/asdf/quux.html'); // Returns: 'quux.html' path.basename('/foo/bar/baz/asdf/quux.html', '.html'); // Returns: 'quux' </code></pre> <p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string or if <code>ext</code> is given and is not a string.</p> <h2>path.delimiter<span><a class="mark" href="#path_path_delimiter" id="path_path_delimiter">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.9.3</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Provides the platform-specific path delimiter:</p> <ul> <li><code>;</code> for Windows</li> <li><code>:</code> for POSIX</li> </ul> <p>For example, on POSIX:</p> <pre><code class="language-js">console.log(process.env.PATH); // Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' process.env.PATH.split(path.delimiter); // Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] </code></pre> <p>On Windows:</p> <pre><code class="language-js">console.log(process.env.PATH); // Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\' process.env.PATH.split(path.delimiter); // Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\'] </code></pre> <h2>path.dirname(path)<span><a class="mark" href="#path_path_dirname_path" id="path_path_dirname_path">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>Passing a non-string as the <code>path</code> argument will throw now.</p></td></tr> <tr><td>v0.1.16</td> <td><p><span>Added in: v0.1.16</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>path.dirname()</code> method returns the directory name of a <code>path</code>, similar to the Unix <code>dirname</code> command. Trailing directory separators are ignored, see <a href="#path_path_sep"><code>path.sep</code></a>.</p> <pre><code class="language-js">path.dirname('/foo/bar/baz/asdf/quux'); // Returns: '/foo/bar/baz/asdf' </code></pre> <p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p> <h2>path.extname(path)<span><a class="mark" href="#path_path_extname_path" id="path_path_extname_path">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>Passing a non-string as the <code>path</code> argument will throw now.</p></td></tr> <tr><td>v0.1.25</td> <td><p><span>Added in: v0.1.25</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>path.extname()</code> method returns the extension of the <code>path</code>, from the last occurrence of the <code>.</code> (period) character to end of string in the last portion of the <code>path</code>. If there is no <code>.</code> in the last portion of the <code>path</code>, or if the first character of the basename of <code>path</code> (see <code>path.basename()</code>) is <code>.</code>, then an empty string is returned.</p> <pre><code class="language-js">path.extname('index.html'); // Returns: '.html' path.extname('index.coffee.md'); // Returns: '.md' path.extname('index.'); // Returns: '.' path.extname('index'); // Returns: '' path.extname('.index'); // Returns: '' </code></pre> <p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p> <h2>path.format(pathObject)<span><a class="mark" href="#path_path_format_pathobject" id="path_path_format_pathobject">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.15</span> </div> <ul> <li> <p><code>pathObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>root</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>ext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>path.format()</code> method returns a path string from an object. This is the opposite of <a href="#path_path_parse_path"><code>path.parse()</code></a>.</p> <p>When providing properties to the <code>pathObject</code> remember that there are combinations where one property has priority over another:</p> <ul> <li><code>pathObject.root</code> is ignored if <code>pathObject.dir</code> is provided</li> <li><code>pathObject.ext</code> and <code>pathObject.name</code> are ignored if <code>pathObject.base</code> exists</li> </ul> <p>For example, on POSIX:</p> <pre><code class="language-js">// If `dir`, `root` and `base` are provided, // `${dir}${path.sep}${base}` // will be returned. `root` is ignored. path.format({ root: '/ignored', dir: '/home/user/dir', base: 'file.txt' }); // Returns: '/home/user/dir/file.txt' // `root` will be used if `dir` is not specified. // If only `root` is provided or `dir` is equal to `root` then the // platform separator will not be included. `ext` will be ignored. path.format({ root: '/', base: 'file.txt', ext: 'ignored' }); // Returns: '/file.txt' // `name` + `ext` will be used if `base` is not specified. path.format({ root: '/', name: 'file', ext: '.txt' }); // Returns: '/file.txt' </code></pre> <p>On Windows:</p> <pre><code class="language-js">path.format({ dir: 'C:\\path\\dir', base: 'file.txt' }); // Returns: 'C:\\path\\dir\\file.txt' </code></pre> <h2>path.isAbsolute(path)<span><a class="mark" href="#path_path_isabsolute_path" id="path_path_isabsolute_path">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.2</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>path.isAbsolute()</code> method determines if <code>path</code> is an absolute path.</p> <p>If the given <code>path</code> is a zero-length string, <code>false</code> will be returned.</p> <p>For example, on POSIX:</p> <pre><code class="language-js">path.isAbsolute('/foo/bar'); // true path.isAbsolute('/baz/..'); // true path.isAbsolute('qux/'); // false path.isAbsolute('.'); // false </code></pre> <p>On Windows:</p> <pre><code class="language-js">path.isAbsolute('//server'); // true path.isAbsolute('\\\\server'); // true path.isAbsolute('C:/foo/..'); // true path.isAbsolute('C:\\foo\\..'); // true path.isAbsolute('bar\\baz'); // false path.isAbsolute('bar/baz'); // false path.isAbsolute('.'); // false </code></pre> <p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p> <h2>path.join([...paths])<span><a class="mark" href="#path_path_join_paths" id="path_path_join_paths">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <ul> <li><code>...paths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A sequence of path segments</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>path.join()</code> method joins all given <code>path</code> segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.</p> <p>Zero-length <code>path</code> segments are ignored. If the joined path string is a zero-length string then <code>'.'</code> will be returned, representing the current working directory.</p> <pre><code class="language-js">path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); // Returns: '/foo/bar/baz/asdf' path.join('foo', {}, 'bar'); // throws 'TypeError: Path must be a string. Received {}' </code></pre> <p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if any of the path segments is not a string.</p> <h2>path.normalize(path)<span><a class="mark" href="#path_path_normalize_path" id="path_path_normalize_path">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.23</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>path.normalize()</code> method normalizes the given <code>path</code>, resolving <code>'..'</code> and <code>'.'</code> segments.</p> <p>When multiple, sequential path segment separation characters are found (e.g. <code>/</code> on POSIX and either <code>\</code> or <code>/</code> on Windows), they are replaced by a single instance of the platform-specific path segment separator (<code>/</code> on POSIX and <code>\</code> on Windows). Trailing separators are preserved.</p> <p>If the <code>path</code> is a zero-length string, <code>'.'</code> is returned, representing the current working directory.</p> <p>For example, on POSIX:</p> <pre><code class="language-js">path.normalize('/foo/bar//baz/asdf/quux/..'); // Returns: '/foo/bar/baz/asdf' </code></pre> <p>On Windows:</p> <pre><code class="language-js">path.normalize('C:\\temp\\\\foo\\bar\\..\\'); // Returns: 'C:\\temp\\foo\\' </code></pre> <p>Since Windows recognizes multiple path separators, both separators will be replaced by instances of the Windows preferred separator (<code>\</code>):</p> <pre><code class="language-js">path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar'); // Returns: 'C:\\temp\\foo\\bar' </code></pre> <p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p> <h2>path.parse(path)<span><a class="mark" href="#path_path_parse_path" id="path_path_parse_path">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.15</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>path.parse()</code> method returns an object whose properties represent significant elements of the <code>path</code>. Trailing directory separators are ignored, see <a href="#path_path_sep"><code>path.sep</code></a>.</p> <p>The returned object will have the following properties:</p> <ul> <li><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>root</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>ext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>For example, on POSIX:</p> <pre><code class="language-js">path.parse('/home/user/dir/file.txt'); // Returns: // { root: '/', // dir: '/home/user/dir', // base: 'file.txt', // ext: '.txt', // name: 'file' } </code></pre> <pre><code class="language-text">┌─────────────────────┬────────────┐ │ dir │ base │ ├──────┬ ├──────┬─────┤ │ root │ │ name │ ext │ " / home/user/dir / file .txt " └──────┴──────────────┴──────┴─────┘ (All spaces in the "" line should be ignored. They are purely for formatting.) </code></pre> <p>On Windows:</p> <pre><code class="language-js">path.parse('C:\\path\\dir\\file.txt'); // Returns: // { root: 'C:\\', // dir: 'C:\\path\\dir', // base: 'file.txt', // ext: '.txt', // name: 'file' } </code></pre> <pre><code class="language-text">┌─────────────────────┬────────────┐ │ dir │ base │ ├──────┬ ├──────┬─────┤ │ root │ │ name │ ext │ " C:\ path\dir \ file .txt " └──────┴──────────────┴──────┴─────┘ (All spaces in the "" line should be ignored. They are purely for formatting.) </code></pre> <p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p> <h2>path.posix<span><a class="mark" href="#path_path_posix" id="path_path_posix">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.15</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>path.posix</code> property provides access to POSIX specific implementations of the <code>path</code> methods.</p> <h2>path.relative(from, to)<span><a class="mark" href="#path_path_relative_from_to" id="path_path_relative_from_to">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.8.0</td> <td><p>On Windows, the leading slashes for UNC paths are now included in the return value.</p></td></tr> <tr><td>v0.5.0</td> <td><p><span>Added in: v0.5.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>from</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>to</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>path.relative()</code> method returns the relative path from <code>from</code> to <code>to</code> based on the current working directory. If <code>from</code> and <code>to</code> each resolve to the same path (after calling <code>path.resolve()</code> on each), a zero-length string is returned.</p> <p>If a zero-length string is passed as <code>from</code> or <code>to</code>, the current working directory will be used instead of the zero-length strings.</p> <p>For example, on POSIX:</p> <pre><code class="language-js">path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); // Returns: '../../impl/bbb' </code></pre> <p>On Windows:</p> <pre><code class="language-js">path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'); // Returns: '..\\..\\impl\\bbb' </code></pre> <p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if either <code>from</code> or <code>to</code> is not a string.</p> <h2>path.resolve([...paths])<span><a class="mark" href="#path_path_resolve_paths" id="path_path_resolve_paths">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.4</span> </div> <ul> <li><code>...paths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A sequence of paths or path segments</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>path.resolve()</code> method resolves a sequence of paths or path segments into an absolute path.</p> <p>The given sequence of paths is processed from right to left, with each subsequent <code>path</code> prepended until an absolute path is constructed. For instance, given the sequence of path segments: <code>/foo</code>, <code>/bar</code>, <code>baz</code>, calling <code>path.resolve('/foo', '/bar', 'baz')</code> would return <code>/bar/baz</code>.</p> <p>If after processing all given <code>path</code> segments an absolute path has not yet been generated, the current working directory is used.</p> <p>The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.</p> <p>Zero-length <code>path</code> segments are ignored.</p> <p>If no <code>path</code> segments are passed, <code>path.resolve()</code> will return the absolute path of the current working directory.</p> <pre><code class="language-js">path.resolve('/foo/bar', './baz'); // Returns: '/foo/bar/baz' path.resolve('/foo/bar', '/tmp/file/'); // Returns: '/tmp/file' path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); // if the current working directory is /home/myself/node, // this returns '/home/myself/node/wwwroot/static_files/gif/image.gif' </code></pre> <p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if any of the arguments is not a string.</p> <h2>path.sep<span><a class="mark" href="#path_path_sep" id="path_path_sep">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.9</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Provides the platform-specific path segment separator:</p> <ul> <li><code>\</code> on Windows</li> <li><code>/</code> on POSIX</li> </ul> <p>For example, on POSIX:</p> <pre><code class="language-js">'foo/bar/baz'.split(path.sep); // Returns: ['foo', 'bar', 'baz'] </code></pre> <p>On Windows:</p> <pre><code class="language-js">'foo\\bar\\baz'.split(path.sep); // Returns: ['foo', 'bar', 'baz'] </code></pre> <p>On Windows, both the forward slash (<code>/</code>) and backward slash (<code>\</code>) are accepted as path segment separators; however, the <code>path</code> methods only add backward slashes (<code>\</code>).</p> <h2>path.toNamespacedPath(path)<span><a class="mark" href="#path_path_tonamespacedpath_path" id="path_path_tonamespacedpath_path">#</a></span></h2> <div class="api_metadata"> <span>Added in: v9.0.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>On Windows systems only, returns an equivalent <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#namespaces">namespace-prefixed path</a> for the given <code>path</code>. If <code>path</code> is not a string, <code>path</code> will be returned without modifications.</p> <p>This method is meaningful only on Windows system. On POSIX systems, the method is non-operational and always returns <code>path</code> without modifications.</p> <h2>path.win32<span><a class="mark" href="#path_path_win32" id="path_path_win32">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.15</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>path.win32</code> property provides access to Windows-specific implementations of the <code>path</code> methods.</p> <h1>Performance Timing API<span><a class="mark" href="#perf_hooks_performance_timing_api" id="perf_hooks_performance_timing_api">#</a></span></h1> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>The Performance Timing API provides an implementation of the <a href="https://w3c.github.io/performance-timeline/">W3C Performance Timeline</a> specification. The purpose of the API is to support collection of high resolution performance metrics. This is the same Performance API as implemented in modern Web browsers.</p> <pre><code class="language-js">const { PerformanceObserver, performance } = require('perf_hooks'); const obs = new PerformanceObserver((items) => { console.log(items.getEntries()[0].duration); performance.clearMarks(); }); obs.observe({ entryTypes: ['measure'] }); performance.mark('A'); doSomeLongRunningProcess(() => { performance.mark('B'); performance.measure('A to B', 'A', 'B'); }); </code></pre> <h2>Class: Performance<span><a class="mark" href="#perf_hooks_class_performance" id="perf_hooks_class_performance">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <h3>performance.clearMarks([name])<span><a class="mark" href="#perf_hooks_performance_clearmarks_name" id="perf_hooks_performance_clearmarks_name">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>If <code>name</code> is not provided, removes all <code>PerformanceMark</code> objects from the Performance Timeline. If <code>name</code> is provided, removes only the named mark.</p> <h3>performance.mark([name])<span><a class="mark" href="#perf_hooks_performance_mark_name" id="perf_hooks_performance_mark_name">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Creates a new <code>PerformanceMark</code> entry in the Performance Timeline. A <code>PerformanceMark</code> is a subclass of <code>PerformanceEntry</code> whose <code>performanceEntry.entryType</code> is always <code>'mark'</code>, and whose <code>performanceEntry.duration</code> is always <code>0</code>. Performance marks are used to mark specific significant moments in the Performance Timeline.</p> <h3>performance.measure(name, startMark, endMark)<span><a class="mark" href="#perf_hooks_performance_measure_name_startmark_endmark" id="perf_hooks_performance_measure_name_startmark_endmark">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>startMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>endMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Creates a new <code>PerformanceMeasure</code> entry in the Performance Timeline. A <code>PerformanceMeasure</code> is a subclass of <code>PerformanceEntry</code> whose <code>performanceEntry.entryType</code> is always <code>'measure'</code>, and whose <code>performanceEntry.duration</code> measures the number of milliseconds elapsed since <code>startMark</code> and <code>endMark</code>.</p> <p>The <code>startMark</code> argument may identify any <em>existing</em> <code>PerformanceMark</code> in the Performance Timeline, or <em>may</em> identify any of the timestamp properties provided by the <code>PerformanceNodeTiming</code> class. If the named <code>startMark</code> does not exist, then <code>startMark</code> is set to <a href="https://w3c.github.io/hr-time/#dom-performance-timeorigin"><code>timeOrigin</code></a> by default.</p> <p>The <code>endMark</code> argument must identify any <em>existing</em> <code>PerformanceMark</code> in the Performance Timeline or any of the timestamp properties provided by the <code>PerformanceNodeTiming</code> class. If the named <code>endMark</code> does not exist, an error will be thrown.</p> <h3>performance.nodeTiming<span><a class="mark" href="#perf_hooks_performance_nodetiming" id="perf_hooks_performance_nodetiming">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="#perf_hooks_class_performancenodetiming_extends_performanceentry" class="type"><PerformanceNodeTiming></a></li> </ul> <p>An instance of the <code>PerformanceNodeTiming</code> class that provides performance metrics for specific Node.js operational milestones.</p> <h3>performance.now()<span><a class="mark" href="#perf_hooks_performance_now" id="perf_hooks_performance_now">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Returns the current high resolution millisecond timestamp, where 0 represents the start of the current <code>node</code> process.</p> <h3>performance.timeOrigin<span><a class="mark" href="#perf_hooks_performance_timeorigin" id="perf_hooks_performance_timeorigin">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <a href="https://w3c.github.io/hr-time/#dom-performance-timeorigin"><code>timeOrigin</code></a> specifies the high resolution millisecond timestamp at which the current <code>node</code> process began, measured in Unix time.</p> <h3>performance.timerify(fn)<span><a class="mark" href="#perf_hooks_performance_timerify_fn" id="perf_hooks_performance_timerify_fn">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Wraps a function within a new function that measures the running time of the wrapped function. A <code>PerformanceObserver</code> must be subscribed to the <code>'function'</code> event type in order for the timing details to be accessed.</p> <pre><code class="language-js">const { performance, PerformanceObserver } = require('perf_hooks'); function someFunction() { console.log('hello world'); } const wrapped = performance.timerify(someFunction); const obs = new PerformanceObserver((list) => { console.log(list.getEntries()[0].duration); obs.disconnect(); }); obs.observe({ entryTypes: ['function'] }); // A performance timeline entry will be created wrapped(); </code></pre> <h2>Class: PerformanceEntry<span><a class="mark" href="#perf_hooks_class_performanceentry" id="perf_hooks_class_performanceentry">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <h3>performanceEntry.duration<span><a class="mark" href="#perf_hooks_performanceentry_duration" id="perf_hooks_performanceentry_duration">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The total number of milliseconds elapsed for this entry. This value will not be meaningful for all Performance Entry types.</p> <h3>performanceEntry.name<span><a class="mark" href="#perf_hooks_performanceentry_name" id="perf_hooks_performanceentry_name">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The name of the performance entry.</p> <h3>performanceEntry.startTime<span><a class="mark" href="#perf_hooks_performanceentry_starttime" id="perf_hooks_performanceentry_starttime">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The high resolution millisecond timestamp marking the starting time of the Performance Entry.</p> <h3>performanceEntry.entryType<span><a class="mark" href="#perf_hooks_performanceentry_entrytype" id="perf_hooks_performanceentry_entrytype">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The type of the performance entry. Currently it may be one of: <code>'node'</code>, <code>'mark'</code>, <code>'measure'</code>, <code>'gc'</code>, <code>'function'</code>, or <code>'http2'</code>.</p> <h3>performanceEntry.kind<span><a class="mark" href="#perf_hooks_performanceentry_kind" id="perf_hooks_performanceentry_kind">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>When <code>performanceEntry.entryType</code> is equal to <code>'gc'</code>, the <code>performance.kind</code> property identifies the type of garbage collection operation that occurred. The value may be one of:</p> <ul> <li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR</code></li> <li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR</code></li> <li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL</code></li> <li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB</code></li> </ul> <h2>Class: PerformanceNodeTiming extends PerformanceEntry<span><a class="mark" href="#perf_hooks_class_performancenodetiming_extends_performanceentry" id="perf_hooks_class_performancenodetiming_extends_performanceentry">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <p>Provides timing details for Node.js itself.</p> <h3>performanceNodeTiming.bootstrapComplete<span><a class="mark" href="#perf_hooks_performancenodetiming_bootstrapcomplete" id="perf_hooks_performancenodetiming_bootstrapcomplete">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The high resolution millisecond timestamp at which the Node.js process completed bootstrapping. If bootstrapping has not yet finished, the property has the value of -1.</p> <h3>performanceNodeTiming.loopExit<span><a class="mark" href="#perf_hooks_performancenodetiming_loopexit" id="perf_hooks_performancenodetiming_loopexit">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The high resolution millisecond timestamp at which the Node.js event loop exited. If the event loop has not yet exited, the property has the value of -1. It can only have a value of not -1 in a handler of the <a href="#process_event_exit"><code>'exit'</code></a> event.</p> <h3>performanceNodeTiming.loopStart<span><a class="mark" href="#perf_hooks_performancenodetiming_loopstart" id="perf_hooks_performancenodetiming_loopstart">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The high resolution millisecond timestamp at which the Node.js event loop started. If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1.</p> <h3>performanceNodeTiming.nodeStart<span><a class="mark" href="#perf_hooks_performancenodetiming_nodestart" id="perf_hooks_performancenodetiming_nodestart">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The high resolution millisecond timestamp at which the Node.js process was initialized.</p> <h3>performanceNodeTiming.v8Start<span><a class="mark" href="#perf_hooks_performancenodetiming_v8start" id="perf_hooks_performancenodetiming_v8start">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The high resolution millisecond timestamp at which the V8 platform was initialized.</p> <h2>Class: PerformanceObserver<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/perf_hooks.js#L277">[src]</a><span><a class="mark" href="#perf_hooks_class_performanceobserver" id="perf_hooks_class_performanceobserver">#</a></span></h2> <h3>new PerformanceObserver(callback)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/perf_hooks.js#L278">[src]</a><span><a class="mark" href="#perf_hooks_new_performanceobserver_callback" id="perf_hooks_new_performanceobserver_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>list</code> <a href="#perf_hooks_class_performanceobserverentrylist" class="type"><PerformanceObserverEntryList></a></li> <li><code>observer</code> <a href="#perf_hooks_class_performanceobserver" class="type"><PerformanceObserver></a></li> </ul> </li> </ul> <p><code>PerformanceObserver</code> objects provide notifications when new <code>PerformanceEntry</code> instances have been added to the Performance Timeline.</p> <pre><code class="language-js">const { performance, PerformanceObserver } = require('perf_hooks'); const obs = new PerformanceObserver((list, observer) => { console.log(list.getEntries()); observer.disconnect(); }); obs.observe({ entryTypes: ['mark'], buffered: true }); performance.mark('test'); </code></pre> <p>Because <code>PerformanceObserver</code> instances introduce their own additional performance overhead, instances should not be left subscribed to notifications indefinitely. Users should disconnect observers as soon as they are no longer needed.</p> <p>The <code>callback</code> is invoked when a <code>PerformanceObserver</code> is notified about new <code>PerformanceEntry</code> instances. The callback receives a <code>PerformanceObserverEntryList</code> instance and a reference to the <code>PerformanceObserver</code>.</p> <h3>performanceObserver.disconnect()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/perf_hooks.js#L313">[src]</a><span><a class="mark" href="#perf_hooks_performanceobserver_disconnect" id="perf_hooks_performanceobserver_disconnect">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <p>Disconnects the <code>PerformanceObserver</code> instance from all notifications.</p> <h3>performanceObserver.observe(options)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/perf_hooks.js#L326">[src]</a><span><a class="mark" href="#perf_hooks_performanceobserver_observe_options" id="perf_hooks_performanceobserver_observe_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>entryTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array of strings identifying the types of <code>PerformanceEntry</code> instances the observer is interested in. If not provided an error will be thrown.</li> <li><code>buffered</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If true, the notification callback will be called using <code>setImmediate()</code> and multiple <code>PerformanceEntry</code> instance notifications will be buffered internally. If <code>false</code>, notifications will be immediate and synchronous. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> </ul> <p>Subscribes the <code>PerformanceObserver</code> instance to notifications of new <code>PerformanceEntry</code> instances identified by <code>options.entryTypes</code>.</p> <p>When <code>options.buffered</code> is <code>false</code>, the <code>callback</code> will be invoked once for every <code>PerformanceEntry</code> instance:</p> <pre><code class="language-js">const { performance, PerformanceObserver } = require('perf_hooks'); const obs = new PerformanceObserver((list, observer) => { // called three times synchronously. list contains one item }); obs.observe({ entryTypes: ['mark'] }); for (let n = 0; n < 3; n++) performance.mark(`test${n}`); </code></pre> <pre><code class="language-js">const { performance, PerformanceObserver } = require('perf_hooks'); const obs = new PerformanceObserver((list, observer) => { // called once. list contains three items }); obs.observe({ entryTypes: ['mark'], buffered: true }); for (let n = 0; n < 3; n++) performance.mark(`test${n}`); </code></pre> <h2>Class: PerformanceObserverEntryList<span><a class="mark" href="#perf_hooks_class_performanceobserverentrylist" id="perf_hooks_class_performanceobserverentrylist">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <p>The <code>PerformanceObserverEntryList</code> class is used to provide access to the <code>PerformanceEntry</code> instances passed to a <code>PerformanceObserver</code>.</p> <h3>performanceObserverEntryList.getEntries()<span><a class="mark" href="#perf_hooks_performanceobserverentrylist_getentries" id="perf_hooks_performanceobserverentrylist_getentries">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li>Returns: <a href="#perf_hooks_class_performanceentry" class="type"><PerformanceEntry[]></a></li> </ul> <p>Returns a list of <code>PerformanceEntry</code> objects in chronological order with respect to <code>performanceEntry.startTime</code>.</p> <h3>performanceObserverEntryList.getEntriesByName(name[, type])<span><a class="mark" href="#perf_hooks_performanceobserverentrylist_getentriesbyname_name_type" id="perf_hooks_performanceobserverentrylist_getentriesbyname_name_type">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="#perf_hooks_class_performanceentry" class="type"><PerformanceEntry[]></a></li> </ul> <p>Returns a list of <code>PerformanceEntry</code> objects in chronological order with respect to <code>performanceEntry.startTime</code> whose <code>performanceEntry.name</code> is equal to <code>name</code>, and optionally, whose <code>performanceEntry.entryType</code> is equal to <code>type</code>.</p> <h3>performanceObserverEntryList.getEntriesByType(type)<span><a class="mark" href="#perf_hooks_performanceobserverentrylist_getentriesbytype_type" id="perf_hooks_performanceobserverentrylist_getentriesbytype_type">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.5.0</span> </div> <ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="#perf_hooks_class_performanceentry" class="type"><PerformanceEntry[]></a></li> </ul> <p>Returns a list of <code>PerformanceEntry</code> objects in chronological order with respect to <code>performanceEntry.startTime</code> whose <code>performanceEntry.entryType</code> is equal to <code>type</code>.</p> <h2>Examples<span><a class="mark" href="#perf_hooks_examples" id="perf_hooks_examples">#</a></span></h2> <h3>Measuring the duration of async operations<span><a class="mark" href="#perf_hooks_measuring_the_duration_of_async_operations" id="perf_hooks_measuring_the_duration_of_async_operations">#</a></span></h3> <p>The following example uses the <a href="async_hooks.html">Async Hooks</a> and Performance APIs to measure the actual duration of a Timeout operation (including the amount of time it to execute the callback).</p> <pre><code class="language-js">'use strict'; const async_hooks = require('async_hooks'); const { performance, PerformanceObserver } = require('perf_hooks'); const set = new Set(); const hook = async_hooks.createHook({ init(id, type) { if (type === 'Timeout') { performance.mark(`Timeout-${id}-Init`); set.add(id); } }, destroy(id) { if (set.has(id)) { set.delete(id); performance.mark(`Timeout-${id}-Destroy`); performance.measure(`Timeout-${id}`, `Timeout-${id}-Init`, `Timeout-${id}-Destroy`); } } }); hook.enable(); const obs = new PerformanceObserver((list, observer) => { console.log(list.getEntries()[0]); performance.clearMarks(); observer.disconnect(); }); obs.observe({ entryTypes: ['measure'], buffered: true }); setTimeout(() => {}, 1000); </code></pre> <h3>Measuring how long it takes to load dependencies<span><a class="mark" href="#perf_hooks_measuring_how_long_it_takes_to_load_dependencies" id="perf_hooks_measuring_how_long_it_takes_to_load_dependencies">#</a></span></h3> <p>The following example measures the duration of <code>require()</code> operations to load dependencies:</p> <!-- eslint-disable no-global-assign --> <pre><code class="language-js">'use strict'; const { performance, PerformanceObserver } = require('perf_hooks'); const mod = require('module'); // Monkey patch the require function mod.Module.prototype.require = performance.timerify(mod.Module.prototype.require); require = performance.timerify(require); // Activate the observer const obs = new PerformanceObserver((list) => { const entries = list.getEntries(); entries.forEach((entry) => { console.log(`require('${entry[0]}')`, entry.duration); }); obs.disconnect(); }); obs.observe({ entryTypes: ['function'], buffered: true }); require('some-module'); </code></pre> <h1>Process<span><a class="mark" href="#process_process" id="process_process">#</a></span></h1> <p>The <code>process</code> object is a <code>global</code> that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using <code>require()</code>.</p> <h2>Process Events<span><a class="mark" href="#process_process_events" id="process_process_events">#</a></span></h2> <p>The <code>process</code> object is an instance of <a href="#events_class_eventemitter"><code>EventEmitter</code></a>.</p> <h3>Event: 'beforeExit'<span><a class="mark" href="#process_event_beforeexit" id="process_event_beforeexit">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.12</span> </div> <p>The <code>'beforeExit'</code> event is emitted when Node.js empties its event loop and has no additional work to schedule. Normally, the Node.js process will exit when there is no work scheduled, but a listener registered on the <code>'beforeExit'</code> event can make asynchronous calls, and thereby cause the Node.js process to continue.</p> <p>The listener callback function is invoked with the value of <a href="#process_process_exitcode"><code>process.exitCode</code></a> passed as the only argument.</p> <p>The <code>'beforeExit'</code> event is <em>not</em> emitted for conditions causing explicit termination, such as calling <a href="#process_process_exit_code"><code>process.exit()</code></a> or uncaught exceptions.</p> <p>The <code>'beforeExit'</code> should <em>not</em> be used as an alternative to the <code>'exit'</code> event unless the intention is to schedule additional work.</p> <h3>Event: 'disconnect'<span><a class="mark" href="#process_event_disconnect" id="process_event_disconnect">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <p>If the Node.js process is spawned with an IPC channel (see the <a href="child_process.html">Child Process</a> and <a href="cluster.html">Cluster</a> documentation), the <code>'disconnect'</code> event will be emitted when the IPC channel is closed.</p> <h3>Event: 'exit'<span><a class="mark" href="#process_event_exit" id="process_event_exit">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.7</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>The <code>'exit'</code> event is emitted when the Node.js process is about to exit as a result of either:</p> <ul> <li>The <code>process.exit()</code> method being called explicitly;</li> <li>The Node.js event loop no longer having any additional work to perform.</li> </ul> <p>There is no way to prevent the exiting of the event loop at this point, and once all <code>'exit'</code> listeners have finished running the Node.js process will terminate.</p> <p>The listener callback function is invoked with the exit code specified either by the <a href="#process_process_exitcode"><code>process.exitCode</code></a> property, or the <code>exitCode</code> argument passed to the <a href="#process_process_exit_code"><code>process.exit()</code></a> method.</p> <pre><code class="language-js">process.on('exit', (code) => { console.log(`About to exit with code: ${code}`); }); </code></pre> <p>Listener functions <strong>must</strong> only perform <strong>synchronous</strong> operations. The Node.js process will exit immediately after calling the <code>'exit'</code> event listeners causing any additional work still queued in the event loop to be abandoned. In the following example, for instance, the timeout will never occur:</p> <pre><code class="language-js">process.on('exit', (code) => { setTimeout(() => { console.log('This will not run'); }, 0); }); </code></pre> <h3>Event: 'message'<span><a class="mark" href="#process_event_message" id="process_event_message">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.10</span> </div> <ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> a parsed JSON object or a serializable primitive value.</li> <li><code>sendHandle</code> <a href="#net_class_net_server" class="type"><net.Server></a> | <a href="#net_class_net_socket" class="type"><net.Socket></a> a <a href="#net_class_net_server"><code>net.Server</code></a> or <a href="#net_class_net_socket"><code>net.Socket</code></a> object, or undefined.</li> </ul> <p>If the Node.js process is spawned with an IPC channel (see the <a href="child_process.html">Child Process</a> and <a href="cluster.html">Cluster</a> documentation), the <code>'message'</code> event is emitted whenever a message sent by a parent process using <a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>childprocess.send()</code></a> is received by the child process.</p> <p>The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent.</p> <h3>Event: 'multipleResolves'<span><a class="mark" href="#process_event_multipleresolves" id="process_event_multipleresolves">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The error type. One of <code>'resolve'</code> or <code>'reject'</code>.</li> <li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> The promise that resolved or rejected more than once.</li> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The value with which the promise was either resolved or rejected after the original resolve.</li> </ul> <p>The <code>'multipleResolves'</code> event is emitted whenever a <code>Promise</code> has been either:</p> <ul> <li>Resolved more than once.</li> <li>Rejected more than once.</li> <li>Rejected after resolve.</li> <li>Resolved after reject.</li> </ul> <p>This is useful for tracking errors in an application while using the promise constructor. Otherwise such mistakes are silently swallowed due to being in a dead zone.</p> <p>It is recommended to end the process on such errors, since the process could be in an undefined state. While using the promise constructor make sure that it is guaranteed to trigger the <code>resolve()</code> or <code>reject()</code> functions exactly once per call and never call both functions in the same call.</p> <pre><code class="language-js">process.on('multipleResolves', (type, promise, reason) => { console.error(type, promise, reason); setImmediate(() => process.exit(1)); }); async function main() { try { return await new Promise((resolve, reject) => { resolve('First call'); resolve('Swallowed resolve'); reject(new Error('Swallowed reject')); }); } catch { throw new Error('Failed'); } } main().then(console.log); // resolve: Promise { 'First call' } 'Swallowed resolve' // reject: Promise { 'First call' } Error: Swallowed reject // at Promise (*) // at new Promise (<anonymous>) // at main (*) // First call </code></pre> <h3>Event: 'rejectionHandled'<span><a class="mark" href="#process_event_rejectionhandled" id="process_event_rejectionhandled">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.4.1</span> </div> <ul> <li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> The late handled promise.</li> </ul> <p>The <code>'rejectionHandled'</code> event is emitted whenever a <code>Promise</code> has been rejected and an error handler was attached to it (using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch"><code>promise.catch()</code></a>, for example) later than one turn of the Node.js event loop.</p> <p>The <code>Promise</code> object would have previously been emitted in an <code>'unhandledRejection'</code> event, but during the course of processing gained a rejection handler.</p> <p>There is no notion of a top level for a <code>Promise</code> chain at which rejections can always be handled. Being inherently asynchronous in nature, a <code>Promise</code> rejection can be handled at a future point in time, possibly much later than the event loop turn it takes for the <code>'unhandledRejection'</code> event to be emitted.</p> <p>Another way of stating this is that, unlike in synchronous code where there is an ever-growing list of unhandled exceptions, with Promises there can be a growing-and-shrinking list of unhandled rejections.</p> <p>In synchronous code, the <code>'uncaughtException'</code> event is emitted when the list of unhandled exceptions grows.</p> <p>In asynchronous code, the <code>'unhandledRejection'</code> event is emitted when the list of unhandled rejections grows, and the <code>'rejectionHandled'</code> event is emitted when the list of unhandled rejections shrinks.</p> <pre><code class="language-js">const unhandledRejections = new Map(); process.on('unhandledRejection', (reason, promise) => { unhandledRejections.set(promise, reason); }); process.on('rejectionHandled', (promise) => { unhandledRejections.delete(promise); }); </code></pre> <p>In this example, the <code>unhandledRejections</code> <code>Map</code> will grow and shrink over time, reflecting rejections that start unhandled and then become handled. It is possible to record such errors in an error log, either periodically (which is likely best for long-running application) or upon process exit (which is likely most convenient for scripts).</p> <h3>Event: 'uncaughtException'<span><a class="mark" href="#process_event_uncaughtexception" id="process_event_uncaughtexception">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.17.0</td> <td><p>Added the <code>origin</code> argument.</p></td></tr> <tr><td>v0.1.18</td> <td><p><span>Added in: v0.1.18</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The uncaught exception.</li> <li><code>origin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Indicates if the exception originates from an unhandled rejection or from synchronous errors. Can either be <code>'uncaughtException'</code> or <code>'unhandledRejection'</code>.</li> </ul> <p>The <code>'uncaughtException'</code> event is emitted when an uncaught JavaScript exception bubbles all the way back to the event loop. By default, Node.js handles such exceptions by printing the stack trace to <code>stderr</code> and exiting with code 1, overriding any previously set <a href="#process_process_exitcode"><code>process.exitCode</code></a>. Adding a handler for the <code>'uncaughtException'</code> event overrides this default behavior. Alternatively, change the <a href="#process_process_exitcode"><code>process.exitCode</code></a> in the <code>'uncaughtException'</code> handler which will result in the process exiting with the provided exit code. Otherwise, in the presence of such handler the process will exit with 0.</p> <pre><code class="language-js">process.on('uncaughtException', (err, origin) => { fs.writeSync( process.stderr.fd, `Caught exception: ${err}\n` + `Exception origin: ${origin}` ); }); setTimeout(() => { console.log('This will still run.'); }, 500); // Intentionally cause an exception, but don't catch it. nonexistentFunc(); console.log('This will not run.'); </code></pre> <h4>Warning: Using <code>'uncaughtException'</code> correctly<span><a class="mark" href="#process_warning_using_uncaughtexception_correctly" id="process_warning_using_uncaughtexception_correctly">#</a></span></h4> <p>Note that <code>'uncaughtException'</code> is a crude mechanism for exception handling intended to be used only as a last resort. The event <em>should not</em> be used as an equivalent to <code>On Error Resume Next</code>. Unhandled exceptions inherently mean that an application is in an undefined state. Attempting to resume application code without properly recovering from the exception can cause additional unforeseen and unpredictable issues.</p> <p>Exceptions thrown from within the event handler will not be caught. Instead the process will exit with a non-zero exit code and the stack trace will be printed. This is to avoid infinite recursion.</p> <p>Attempting to resume normally after an uncaught exception can be similar to pulling out of the power cord when upgrading a computer — nine out of ten times nothing happens - but the 10th time, the system becomes corrupted.</p> <p>The correct use of <code>'uncaughtException'</code> is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process. <strong>It is not safe to resume normal operation after <code>'uncaughtException'</code>.</strong></p> <p>To restart a crashed application in a more reliable way, whether <code>'uncaughtException'</code> is emitted or not, an external monitor should be employed in a separate process to detect application failures and recover or restart as needed.</p> <h3>Event: 'unhandledRejection'<span><a class="mark" href="#process_event_unhandledrejection" id="process_event_unhandledrejection">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.0.0</td> <td><p>Not handling <code>Promise</code> rejections is deprecated.</p></td></tr> <tr><td>v6.6.0</td> <td><p>Unhandled <code>Promise</code> rejections will now emit a process warning.</p></td></tr> <tr><td>v1.4.1</td> <td><p><span>Added in: v1.4.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The object with which the promise was rejected (typically an <a href="#errors_class_error"><code>Error</code></a> object).</li> <li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a> The rejected promise.</li> </ul> <p>The <code>'unhandledRejection'</code> event is emitted whenever a <code>Promise</code> is rejected and no error handler is attached to the promise within a turn of the event loop. When programming with Promises, exceptions are encapsulated as "rejected promises". Rejections can be caught and handled using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch"><code>promise.catch()</code></a> and are propagated through a <code>Promise</code> chain. The <code>'unhandledRejection'</code> event is useful for detecting and keeping track of promises that were rejected whose rejections have not yet been handled.</p> <pre><code class="language-js">process.on('unhandledRejection', (reason, promise) => { console.log('Unhandled Rejection at:', promise, 'reason:', reason); // Application specific logging, throwing an error, or other logic here }); somePromise.then((res) => { return reportToUser(JSON.pasre(res)); // note the typo (`pasre`) }); // no `.catch()` or `.then()` </code></pre> <p>The following will also trigger the <code>'unhandledRejection'</code> event to be emitted:</p> <pre><code class="language-js">function SomeResource() { // Initially set the loaded status to a rejected promise this.loaded = Promise.reject(new Error('Resource not yet loaded!')); } const resource = new SomeResource(); // no .catch or .then on resource.loaded for at least a turn </code></pre> <p>In this example case, it is possible to track the rejection as a developer error as would typically be the case for other <code>'unhandledRejection'</code> events. To address such failures, a non-operational <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch"><code>.catch(() => { })</code></a> handler may be attached to <code>resource.loaded</code>, which would prevent the <code>'unhandledRejection'</code> event from being emitted.</p> <h3>Event: 'warning'<span><a class="mark" href="#process_event_warning" id="process_event_warning">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <ul> <li> <p><code>warning</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> Key properties of the warning are:</p> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the warning. <strong>Default:</strong> <code>'Warning'</code>.</li> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A system-provided description of the warning.</li> <li><code>stack</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A stack trace to the location in the code where the warning was issued.</li> </ul> </li> </ul> <p>The <code>'warning'</code> event is emitted whenever Node.js emits a process warning.</p> <p>A process warning is similar to an error in that it describes exceptional conditions that are being brought to the user's attention. However, warnings are not part of the normal Node.js and JavaScript error handling flow. Node.js can emit warnings whenever it detects bad coding practices that could lead to sub-optimal application performance, bugs, or security vulnerabilities.</p> <pre><code class="language-js">process.on('warning', (warning) => { console.warn(warning.name); // Print the warning name console.warn(warning.message); // Print the warning message console.warn(warning.stack); // Print the stack trace }); </code></pre> <p>By default, Node.js will print process warnings to <code>stderr</code>. The <code>--no-warnings</code> command-line option can be used to suppress the default console output but the <code>'warning'</code> event will still be emitted by the <code>process</code> object.</p> <p>The following example illustrates the warning that is printed to <code>stderr</code> when too many listeners have been added to an event:</p> <pre><code class="language-txt">$ node > events.defaultMaxListeners = 1; > process.on('foo', () => {}); > process.on('foo', () => {}); > (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit </code></pre> <p>In contrast, the following example turns off the default warning output and adds a custom handler to the <code>'warning'</code> event:</p> <pre><code class="language-txt">$ node --no-warnings > const p = process.on('warning', (warning) => console.warn('Do not do that!')); > events.defaultMaxListeners = 1; > process.on('foo', () => {}); > process.on('foo', () => {}); > Do not do that! </code></pre> <p>The <code>--trace-warnings</code> command-line option can be used to have the default console output for warnings include the full stack trace of the warning.</p> <p>Launching Node.js using the <code>--throw-deprecation</code> command line flag will cause custom deprecation warnings to be thrown as exceptions.</p> <p>Using the <code>--trace-deprecation</code> command line flag will cause the custom deprecation to be printed to <code>stderr</code> along with the stack trace.</p> <p>Using the <code>--no-deprecation</code> command line flag will suppress all reporting of the custom deprecation.</p> <p>The <code>*-deprecation</code> command line flags only affect warnings that use the name <code>'DeprecationWarning'</code>.</p> <h4>Emitting custom warnings<span><a class="mark" href="#process_emitting_custom_warnings" id="process_emitting_custom_warnings">#</a></span></h4> <p>See the <a href="#process_process_emitwarning_warning_type_code_ctor"><code>process.emitWarning()</code></a> method for issuing custom or application-specific warnings.</p> <h3>Signal Events<span><a class="mark" href="#process_signal_events" id="process_signal_events">#</a></span></h3> <p>Signal events will be emitted when the Node.js process receives a signal. Please refer to <a href="http://man7.org/linux/man-pages/man7/signal.7.html"><code>signal(7)</code></a> for a listing of standard POSIX signal names such as <code>'SIGINT'</code>, <code>'SIGHUP'</code>, etc.</p> <p>The signal handler will receive the signal's name (<code>'SIGINT'</code>, <code>'SIGTERM'</code>, etc.) as the first argument.</p> <p>The name of each event will be the uppercase common name for the signal (e.g. <code>'SIGINT'</code> for <code>SIGINT</code> signals).</p> <pre><code class="language-js">// Begin reading from stdin so the process does not exit. process.stdin.resume(); process.on('SIGINT', () => { console.log('Received SIGINT. Press Control-D to exit.'); }); // Using a single function to handle multiple signals function handle(signal) { console.log(`Received ${signal}`); } process.on('SIGINT', handle); process.on('SIGTERM', handle); </code></pre> <ul> <li><code>'SIGUSR1'</code> is reserved by Node.js to start the <a href="debugger.html">debugger</a>. It's possible to install a listener but doing so might interfere with the debugger.</li> <li><code>'SIGTERM'</code> and <code>'SIGINT'</code> have default handlers on non-Windows platforms that reset the terminal mode before exiting with code <code>128 + signal number</code>. If one of these signals has a listener installed, its default behavior will be removed (Node.js will no longer exit).</li> <li><code>'SIGPIPE'</code> is ignored by default. It can have a listener installed.</li> <li><code>'SIGHUP'</code> is generated on Windows when the console window is closed, and on other platforms under various similar conditions. See <a href="http://man7.org/linux/man-pages/man7/signal.7.html"><code>signal(7)</code></a>. It can have a listener installed, however Node.js will be unconditionally terminated by Windows about 10 seconds later. On non-Windows platforms, the default behavior of <code>SIGHUP</code> is to terminate Node.js, but once a listener has been installed its default behavior will be removed.</li> <li><code>'SIGTERM'</code> is not supported on Windows, it can be listened on.</li> <li><code>'SIGINT'</code> from the terminal is supported on all platforms, and can usually be generated with <code><Ctrl>+C</code> (though this may be configurable). It is not generated when terminal raw mode is enabled.</li> <li><code>'SIGBREAK'</code> is delivered on Windows when <code><Ctrl>+<Break></code> is pressed, on non-Windows platforms it can be listened on, but there is no way to send or generate it.</li> <li><code>'SIGWINCH'</code> is delivered when the console has been resized. On Windows, this will only happen on write to the console when the cursor is being moved, or when a readable tty is used in raw mode.</li> <li><code>'SIGKILL'</code> cannot have a listener installed, it will unconditionally terminate Node.js on all platforms.</li> <li><code>'SIGSTOP'</code> cannot have a listener installed.</li> <li><code>'SIGBUS'</code>, <code>'SIGFPE'</code>, <code>'SIGSEGV'</code> and <code>'SIGILL'</code>, when not raised artificially using <a href="http://man7.org/linux/man-pages/man2/kill.2.html"><code>kill(2)</code></a>, inherently leave the process in a state from which it is not safe to attempt to call JS listeners. Doing so might lead to the process hanging in an endless loop, since listeners attached using <code>process.on()</code> are called asynchronously and therefore unable to correct the underlying problem.</li> </ul> <p>Windows does not support sending signals, but Node.js offers some emulation with <a href="#process_process_kill_pid_signal"><code>process.kill()</code></a>, and <a href="#child_process_subprocess_kill_signal"><code>subprocess.kill()</code></a>. Sending signal <code>0</code> can be used to test for the existence of a process. Sending <code>SIGINT</code>, <code>SIGTERM</code>, and <code>SIGKILL</code> cause the unconditional termination of the target process.</p> <h2>process.abort()<span><a class="mark" href="#process_process_abort" id="process_process_abort">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <p>The <code>process.abort()</code> method causes the Node.js process to exit immediately and generate a core file.</p> <p>This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p> <h2>process.allowedNodeEnvironmentFlags<span><a class="mark" href="#process_process_allowednodeenvironmentflags" id="process_process_allowednodeenvironmentflags">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set" class="type"><Set></a></li> </ul> <p>The <code>process.allowedNodeEnvironmentFlags</code> property is a special, read-only <code>Set</code> of flags allowable within the <a href="#cli_node_options_options"><code>NODE_OPTIONS</code></a> environment variable.</p> <p><code>process.allowedNodeEnvironmentFlags</code> extends <code>Set</code>, but overrides <code>Set.prototype.has</code> to recognize several different possible flag representations. <code>process.allowedNodeEnvironmentFlags.has()</code> will return <code>true</code> in the following cases:</p> <ul> <li>Flags may omit leading single (<code>-</code>) or double (<code>--</code>) dashes; e.g., <code>inspect-brk</code> for <code>--inspect-brk</code>, or <code>r</code> for <code>-r</code>.</li> <li>Flags passed through to V8 (as listed in <code>--v8-options</code>) may replace one or more <em>non-leading</em> dashes for an underscore, or vice-versa; e.g., <code>--perf_basic_prof</code>, <code>--perf-basic-prof</code>, <code>--perf_basic-prof</code>, etc.</li> <li>Flags may contain one or more equals (<code>=</code>) characters; all characters after and including the first equals will be ignored; e.g., <code>--stack-trace-limit=100</code>.</li> <li>Flags <em>must</em> be allowable within <a href="#cli_node_options_options"><code>NODE_OPTIONS</code></a>.</li> </ul> <p>When iterating over <code>process.allowedNodeEnvironmentFlags</code>, flags will appear only <em>once</em>; each will begin with one or more dashes. Flags passed through to V8 will contain underscores instead of non-leading dashes:</p> <pre><code class="language-js">process.allowedNodeEnvironmentFlags.forEach((flag) => { // -r // --inspect-brk // --abort_on_uncaught_exception // ... }); </code></pre> <p>The methods <code>add()</code>, <code>clear()</code>, and <code>delete()</code> of <code>process.allowedNodeEnvironmentFlags</code> do nothing, and will fail silently.</p> <p>If Node.js was compiled <em>without</em> <a href="#cli_node_options_options"><code>NODE_OPTIONS</code></a> support (shown in <a href="#process_process_config"><code>process.config</code></a>), <code>process.allowedNodeEnvironmentFlags</code> will contain what <em>would have</em> been allowable.</p> <h2>process.arch<span><a class="mark" href="#process_process_arch" id="process_process_arch">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>process.arch</code> property returns a string identifying the operating system CPU architecture for which the Node.js binary was compiled.</p> <p>The current possible values are: <code>'arm'</code>, <code>'arm64'</code>, <code>'ia32'</code>, <code>'mips'</code>, <code>'mipsel'</code>, <code>'ppc'</code>, <code>'ppc64'</code>, <code>'s390'</code>, <code>'s390x'</code>, <code>'x32'</code>, and <code>'x64'</code>.</p> <pre><code class="language-js">console.log(`This processor architecture is ${process.arch}`); </code></pre> <h2>process.argv<span><a class="mark" href="#process_process_argv" id="process_process_argv">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.27</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The <code>process.argv</code> property returns an array containing the command line arguments passed when the Node.js process was launched. The first element will be <a href="#process_process_execpath"><code>process.execPath</code></a>. See <code>process.argv0</code> if access to the original value of <code>argv[0]</code> is needed. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command line arguments.</p> <p>For example, assuming the following script for <code>process-args.js</code>:</p> <pre><code class="language-js">// print process.argv process.argv.forEach((val, index) => { console.log(`${index}: ${val}`); }); </code></pre> <p>Launching the Node.js process as:</p> <pre><code class="language-console">$ node process-args.js one two=three four </code></pre> <p>Would generate the output:</p> <pre><code class="language-text">0: /usr/local/bin/node 1: /Users/mjr/work/node/process-args.js 2: one 3: two=three 4: four </code></pre> <h2>process.argv0<span><a class="mark" href="#process_process_argv0" id="process_process_argv0">#</a></span></h2> <div class="api_metadata"> <span>Added in: v6.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>process.argv0</code> property stores a read-only copy of the original value of <code>argv[0]</code> passed when Node.js starts.</p> <pre><code class="language-console">$ bash -c 'exec -a customArgv0 ./node' > process.argv[0] '/Volumes/code/external/node/out/Release/node' > process.argv0 'customArgv0' </code></pre> <h2>process.channel<span><a class="mark" href="#process_process_channel" id="process_process_channel">#</a></span></h2> <div class="api_metadata"> <span>Added in: v7.1.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>If the Node.js process was spawned with an IPC channel (see the <a href="child_process.html">Child Process</a> documentation), the <code>process.channel</code> property is a reference to the IPC channel. If no IPC channel exists, this property is <code>undefined</code>.</p> <h2>process.chdir(directory)<span><a class="mark" href="#process_process_chdir_directory" id="process_process_chdir_directory">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <ul> <li><code>directory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>process.chdir()</code> method changes the current working directory of the Node.js process or throws an exception if doing so fails (for instance, if the specified <code>directory</code> does not exist).</p> <pre><code class="language-js">console.log(`Starting directory: ${process.cwd()}`); try { process.chdir('/tmp'); console.log(`New directory: ${process.cwd()}`); } catch (err) { console.error(`chdir: ${err}`); } </code></pre> <p>This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p> <h2>process.config<span><a class="mark" href="#process_process_config" id="process_process_config">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>process.config</code> property returns an <code>Object</code> containing the JavaScript representation of the configure options used to compile the current Node.js executable. This is the same as the <code>config.gypi</code> file that was produced when running the <code>./configure</code> script.</p> <p>An example of the possible output looks like:</p> <!-- eslint-skip --> <pre><code class="language-js">{ target_defaults: { cflags: [], default_configuration: 'Release', defines: [], include_dirs: [], libraries: [] }, variables: { host_arch: 'x64', napi_build_version: 4, node_install_npm: 'true', node_prefix: '', node_shared_cares: 'false', node_shared_http_parser: 'false', node_shared_libuv: 'false', node_shared_zlib: 'false', node_use_dtrace: 'false', node_use_openssl: 'true', node_shared_openssl: 'false', strict_aliasing: 'true', target_arch: 'x64', v8_use_snapshot: 'true' } } </code></pre> <p>The <code>process.config</code> property is <strong>not</strong> read-only and there are existing modules in the ecosystem that are known to extend, modify, or entirely replace the value of <code>process.config</code>.</p> <h2>process.connected<span><a class="mark" href="#process_process_connected" id="process_process_connected">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.2</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>If the Node.js process is spawned with an IPC channel (see the <a href="child_process.html">Child Process</a> and <a href="cluster.html">Cluster</a> documentation), the <code>process.connected</code> property will return <code>true</code> so long as the IPC channel is connected and will return <code>false</code> after <code>process.disconnect()</code> is called.</p> <p>Once <code>process.connected</code> is <code>false</code>, it is no longer possible to send messages over the IPC channel using <code>process.send()</code>.</p> <h2>process.cpuUsage([previousValue])<span><a class="mark" href="#process_process_cpuusage_previousvalue" id="process_process_cpuusage_previousvalue">#</a></span></h2> <div class="api_metadata"> <span>Added in: v6.1.0</span> </div> <ul> <li><code>previousValue</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A previous return value from calling <code>process.cpuUsage()</code></li> <li> <p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>user</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>system</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> </li> </ul> <p>The <code>process.cpuUsage()</code> method returns the user and system CPU time usage of the current process, in an object with properties <code>user</code> and <code>system</code>, whose values are microsecond values (millionth of a second). These values measure time spent in user and system code respectively, and may end up being greater than actual elapsed time if multiple CPU cores are performing work for this process.</p> <p>The result of a previous call to <code>process.cpuUsage()</code> can be passed as the argument to the function, to get a diff reading.</p> <pre><code class="language-js">const startUsage = process.cpuUsage(); // { user: 38579, system: 6986 } // spin the CPU for 500 milliseconds const now = Date.now(); while (Date.now() - now < 500); console.log(process.cpuUsage(startUsage)); // { user: 514883, system: 11226 } </code></pre> <h2>process.cwd()<span><a class="mark" href="#process_process_cwd" id="process_process_cwd">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.8</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>process.cwd()</code> method returns the current working directory of the Node.js process.</p> <pre><code class="language-js">console.log(`Current directory: ${process.cwd()}`); </code></pre> <h2>process.debugPort<span><a class="mark" href="#process_process_debugport" id="process_process_debugport">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.2</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The port used by Node.js's debugger when enabled.</p> <pre><code class="language-js">process.debugPort = 5858; </code></pre> <h2>process.disconnect()<span><a class="mark" href="#process_process_disconnect" id="process_process_disconnect">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.2</span> </div> <p>If the Node.js process is spawned with an IPC channel (see the <a href="child_process.html">Child Process</a> and <a href="cluster.html">Cluster</a> documentation), the <code>process.disconnect()</code> method will close the IPC channel to the parent process, allowing the child process to exit gracefully once there are no other connections keeping it alive.</p> <p>The effect of calling <code>process.disconnect()</code> is that same as calling the parent process's <a href="#child_process_subprocess_disconnect"><code>ChildProcess.disconnect()</code></a>.</p> <p>If the Node.js process was not spawned with an IPC channel, <code>process.disconnect()</code> will be <code>undefined</code>.</p> <h2>process.dlopen(module, filename[, flags])<span><a class="mark" href="#process_process_dlopen_module_filename_flags" id="process_process_dlopen_module_filename_flags">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>Added support for the <code>flags</code> argument.</p></td></tr> <tr><td>v0.1.16</td> <td><p><span>Added in: v0.1.16</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>module</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>flags</code> <a href="#os_dlopen_constants" class="type"><os.constants.dlopen></a> <strong>Default:</strong> <code>os.constants.dlopen.RTLD_LAZY</code></li> </ul> <p>The <code>process.dlopen()</code> method allows to dynamically load shared objects. It is primarily used by <code>require()</code> to load C++ Addons, and should not be used directly, except in special cases. In other words, <a href="#globals_require"><code>require()</code></a> should be preferred over <code>process.dlopen()</code>, unless there are specific reasons.</p> <p>The <code>flags</code> argument is an integer that allows to specify dlopen behavior. See the <a href="#os_dlopen_constants"><code>os.constants.dlopen</code></a> documentation for details.</p> <p>If there are specific reasons to use <code>process.dlopen()</code> (for instance, to specify dlopen flags), it's often useful to use <a href="#modules_require_resolve_request_options"><code>require.resolve()</code></a> to look up the module's path.</p> <p>An important drawback when calling <code>process.dlopen()</code> is that the <code>module</code> instance must be passed. Functions exported by the C++ Addon will be accessible via <code>module.exports</code>.</p> <p>The example below shows how to load a C++ Addon, named as <code>binding</code>, that exports a <code>foo</code> function. All the symbols will be loaded before the call returns, by passing the <code>RTLD_NOW</code> constant. In this example the constant is assumed to be available.</p> <pre><code class="language-js">const os = require('os'); process.dlopen(module, require.resolve('binding'), os.constants.dlopen.RTLD_NOW); module.exports.foo(); </code></pre> <h2>process.emitWarning(warning[, options])<span><a class="mark" href="#process_process_emitwarning_warning_options" id="process_process_emitwarning_warning_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>warning</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The warning to emit.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> When <code>warning</code> is a <code>String</code>, <code>type</code> is the name to use for the <em>type</em> of warning being emitted. <strong>Default:</strong> <code>'Warning'</code>.</li> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A unique identifier for the warning instance being emitted.</li> <li><code>ctor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> When <code>warning</code> is a <code>String</code>, <code>ctor</code> is an optional function used to limit the generated stack trace. <strong>Default:</strong> <code>process.emitWarning</code>.</li> <li><code>detail</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Additional text to include with the error.</li> </ul> </li> </ul> <p>The <code>process.emitWarning()</code> method can be used to emit custom or application specific process warnings. These can be listened for by adding a handler to the <a href="#process_event_warning"><code>'warning'</code></a> event.</p> <pre><code class="language-js">// Emit a warning with a code and additional detail. process.emitWarning('Something happened!', { code: 'MY_WARNING', detail: 'This is some additional information' }); // Emits: // (node:56338) [MY_WARNING] Warning: Something happened! // This is some additional information </code></pre> <p>In this example, an <code>Error</code> object is generated internally by <code>process.emitWarning()</code> and passed through to the <a href="#process_event_warning"><code>'warning'</code></a> handler.</p> <pre><code class="language-js">process.on('warning', (warning) => { console.warn(warning.name); // 'Warning' console.warn(warning.message); // 'Something happened!' console.warn(warning.code); // 'MY_WARNING' console.warn(warning.stack); // Stack trace console.warn(warning.detail); // 'This is some additional information' }); </code></pre> <p>If <code>warning</code> is passed as an <code>Error</code> object, the <code>options</code> argument is ignored.</p> <h2>process.emitWarning(warning[, type[, code]][, ctor])<span><a class="mark" href="#process_process_emitwarning_warning_type_code_ctor" id="process_process_emitwarning_warning_type_code_ctor">#</a></span></h2> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <ul> <li><code>warning</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The warning to emit.</li> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> When <code>warning</code> is a <code>String</code>, <code>type</code> is the name to use for the <em>type</em> of warning being emitted. <strong>Default:</strong> <code>'Warning'</code>.</li> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A unique identifier for the warning instance being emitted.</li> <li><code>ctor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> When <code>warning</code> is a <code>String</code>, <code>ctor</code> is an optional function used to limit the generated stack trace. <strong>Default:</strong> <code>process.emitWarning</code>.</li> </ul> <p>The <code>process.emitWarning()</code> method can be used to emit custom or application specific process warnings. These can be listened for by adding a handler to the <a href="#process_event_warning"><code>'warning'</code></a> event.</p> <pre><code class="language-js">// Emit a warning using a string. process.emitWarning('Something happened!'); // Emits: (node: 56338) Warning: Something happened! </code></pre> <pre><code class="language-js">// Emit a warning using a string and a type. process.emitWarning('Something Happened!', 'CustomWarning'); // Emits: (node:56338) CustomWarning: Something Happened! </code></pre> <pre><code class="language-js">process.emitWarning('Something happened!', 'CustomWarning', 'WARN001'); // Emits: (node:56338) [WARN001] CustomWarning: Something happened! </code></pre> <p>In each of the previous examples, an <code>Error</code> object is generated internally by <code>process.emitWarning()</code> and passed through to the <a href="#process_event_warning"><code>'warning'</code></a> handler.</p> <pre><code class="language-js">process.on('warning', (warning) => { console.warn(warning.name); console.warn(warning.message); console.warn(warning.code); console.warn(warning.stack); }); </code></pre> <p>If <code>warning</code> is passed as an <code>Error</code> object, it will be passed through to the <code>'warning'</code> event handler unmodified (and the optional <code>type</code>, <code>code</code> and <code>ctor</code> arguments will be ignored):</p> <pre><code class="language-js">// Emit a warning using an Error object. const myWarning = new Error('Something happened!'); // Use the Error name property to specify the type name myWarning.name = 'CustomWarning'; myWarning.code = 'WARN001'; process.emitWarning(myWarning); // Emits: (node:56338) [WARN001] CustomWarning: Something happened! </code></pre> <p>A <code>TypeError</code> is thrown if <code>warning</code> is anything other than a string or <code>Error</code> object.</p> <p>Note that while process warnings use <code>Error</code> objects, the process warning mechanism is <strong>not</strong> a replacement for normal error handling mechanisms.</p> <p>The following additional handling is implemented if the warning <code>type</code> is <code>'DeprecationWarning'</code>:</p> <ul> <li>If the <code>--throw-deprecation</code> command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event.</li> <li>If the <code>--no-deprecation</code> command-line flag is used, the deprecation warning is suppressed.</li> <li>If the <code>--trace-deprecation</code> command-line flag is used, the deprecation warning is printed to <code>stderr</code> along with the full stack trace.</li> </ul> <h3>Avoiding duplicate warnings<span><a class="mark" href="#process_avoiding_duplicate_warnings" id="process_avoiding_duplicate_warnings">#</a></span></h3> <p>As a best practice, warnings should be emitted only once per process. To do so, it is recommended to place the <code>emitWarning()</code> behind a simple boolean flag as illustrated in the example below:</p> <pre><code class="language-js">function emitMyWarning() { if (!emitMyWarning.warned) { emitMyWarning.warned = true; process.emitWarning('Only warn once!'); } } emitMyWarning(); // Emits: (node: 56339) Warning: Only warn once! emitMyWarning(); // Emits nothing </code></pre> <h2>process.env<span><a class="mark" href="#process_process_env" id="process_process_env">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Implicit conversion of variable value to string is deprecated.</p></td></tr> <tr><td>v0.1.27</td> <td><p><span>Added in: v0.1.27</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>process.env</code> property returns an object containing the user environment. See <a href="http://man7.org/linux/man-pages/man7/environ.7.html"><code>environ(7)</code></a>.</p> <p>An example of this object looks like:</p> <!-- eslint-skip --> <pre><code class="language-js">{ TERM: 'xterm-256color', SHELL: '/usr/local/bin/bash', USER: 'maciej', PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', PWD: '/Users/maciej', EDITOR: 'vim', SHLVL: '1', HOME: '/Users/maciej', LOGNAME: 'maciej', _: '/usr/local/bin/node' } </code></pre> <p>It is possible to modify this object, but such modifications will not be reflected outside the Node.js process. In other words, the following example would not work:</p> <pre><code class="language-console">$ node -e 'process.env.foo = "bar"' && echo $foo </code></pre> <p>While the following will:</p> <pre><code class="language-js">process.env.foo = 'bar'; console.log(process.env.foo); </code></pre> <p>Assigning a property on <code>process.env</code> will implicitly convert the value to a string. <strong>This behavior is deprecated.</strong> Future versions of Node.js may throw an error when the value is not a string, number, or boolean.</p> <pre><code class="language-js">process.env.test = null; console.log(process.env.test); // => 'null' process.env.test = undefined; console.log(process.env.test); // => 'undefined' </code></pre> <p>Use <code>delete</code> to delete a property from <code>process.env</code>.</p> <pre><code class="language-js">process.env.TEST = 1; delete process.env.TEST; console.log(process.env.TEST); // => undefined </code></pre> <p>On Windows operating systems, environment variables are case-insensitive.</p> <pre><code class="language-js">process.env.TEST = 1; console.log(process.env.test); // => 1 </code></pre> <p><code>process.env</code> is read-only in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p> <h2>process.execArgv<span><a class="mark" href="#process_process_execargv" id="process_process_execargv">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The <code>process.execArgv</code> property returns the set of Node.js-specific command-line options passed when the Node.js process was launched. These options do not appear in the array returned by the <a href="#process_process_argv"><code>process.argv</code></a> property, and do not include the Node.js executable, the name of the script, or any options following the script name. These options are useful in order to spawn child processes with the same execution environment as the parent.</p> <pre><code class="language-console">$ node --harmony script.js --version </code></pre> <p>Results in <code>process.execArgv</code>:</p> <!-- eslint-disable semi --> <pre><code class="language-js">['--harmony'] </code></pre> <p>And <code>process.argv</code>:</p> <!-- eslint-disable semi --> <pre><code class="language-js">['/usr/local/bin/node', 'script.js', '--version'] </code></pre> <h2>process.execPath<span><a class="mark" href="#process_process_execpath" id="process_process_execpath">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.100</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>process.execPath</code> property returns the absolute pathname of the executable that started the Node.js process.</p> <!-- eslint-disable semi --> <pre><code class="language-js">'/usr/local/bin/node' </code></pre> <h2>process.exit([code])<span><a class="mark" href="#process_process_exit_code" id="process_process_exit_code">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.13</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The exit code. <strong>Default:</strong> <code>0</code>.</li> </ul> <p>The <code>process.exit()</code> method instructs Node.js to terminate the process synchronously with an exit status of <code>code</code>. If <code>code</code> is omitted, exit uses either the 'success' code <code>0</code> or the value of <code>process.exitCode</code> if it has been set. Node.js will not terminate until all the <a href="#process_event_exit"><code>'exit'</code></a> event listeners are called.</p> <p>To exit with a 'failure' code:</p> <pre><code class="language-js">process.exit(1); </code></pre> <p>The shell that executed Node.js should see the exit code as <code>1</code>.</p> <p>Calling <code>process.exit()</code> will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to <code>process.stdout</code> and <code>process.stderr</code>.</p> <p>In most situations, it is not actually necessary to call <code>process.exit()</code> explicitly. The Node.js process will exit on its own <em>if there is no additional work pending</em> in the event loop. The <code>process.exitCode</code> property can be set to tell the process which exit code to use when the process exits gracefully.</p> <p>For instance, the following example illustrates a <em>misuse</em> of the <code>process.exit()</code> method that could lead to data printed to stdout being truncated and lost:</p> <pre><code class="language-js">// This is an example of what *not* to do: if (someConditionNotMet()) { printUsageToStdout(); process.exit(1); } </code></pre> <p>The reason this is problematic is because writes to <code>process.stdout</code> in Node.js are sometimes <em>asynchronous</em> and may occur over multiple ticks of the Node.js event loop. Calling <code>process.exit()</code>, however, forces the process to exit <em>before</em> those additional writes to <code>stdout</code> can be performed.</p> <p>Rather than calling <code>process.exit()</code> directly, the code <em>should</em> set the <code>process.exitCode</code> and allow the process to exit naturally by avoiding scheduling any additional work for the event loop:</p> <pre><code class="language-js">// How to properly set the exit code while letting // the process exit gracefully. if (someConditionNotMet()) { printUsageToStdout(); process.exitCode = 1; } </code></pre> <p>If it is necessary to terminate the Node.js process due to an error condition, throwing an <em>uncaught</em> error and allowing the process to terminate accordingly is safer than calling <code>process.exit()</code>.</p> <p>In <a href="#worker_threads_class_worker"><code>Worker</code></a> threads, this function stops the current thread rather than the current process.</p> <h2>process.exitCode<span><a class="mark" href="#process_process_exitcode" id="process_process_exitcode">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.8</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>A number which will be the process exit code, when the process either exits gracefully, or is exited via <a href="#process_process_exit_code"><code>process.exit()</code></a> without specifying a code.</p> <p>Specifying a code to <a href="#process_process_exit_code"><code>process.exit(code)</code></a> will override any previous setting of <code>process.exitCode</code>.</p> <h2>process.getegid()<span><a class="mark" href="#process_process_getegid" id="process_process_getegid">#</a></span></h2> <div class="api_metadata"> <span>Added in: v2.0.0</span> </div> <p>The <code>process.getegid()</code> method returns the numerical effective group identity of the Node.js process. (See <a href="http://man7.org/linux/man-pages/man2/getegid.2.html"><code>getegid(2)</code></a>.)</p> <pre><code class="language-js">if (process.getegid) { console.log(`Current gid: ${process.getegid()}`); } </code></pre> <p>This function is only available on POSIX platforms (i.e. not Windows or Android).</p> <h2>process.geteuid()<span><a class="mark" href="#process_process_geteuid" id="process_process_geteuid">#</a></span></h2> <div class="api_metadata"> <span>Added in: v2.0.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>process.geteuid()</code> method returns the numerical effective user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/geteuid.2.html"><code>geteuid(2)</code></a>.)</p> <pre><code class="language-js">if (process.geteuid) { console.log(`Current uid: ${process.geteuid()}`); } </code></pre> <p>This function is only available on POSIX platforms (i.e. not Windows or Android).</p> <h2>process.getgid()<span><a class="mark" href="#process_process_getgid" id="process_process_getgid">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.31</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>process.getgid()</code> method returns the numerical group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/getgid.2.html"><code>getgid(2)</code></a>.)</p> <pre><code class="language-js">if (process.getgid) { console.log(`Current gid: ${process.getgid()}`); } </code></pre> <p>This function is only available on POSIX platforms (i.e. not Windows or Android).</p> <h2>process.getgroups()<span><a class="mark" href="#process_process_getgroups" id="process_process_getgroups">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a></li> </ul> <p>The <code>process.getgroups()</code> method returns an array with the supplementary group IDs. POSIX leaves it unspecified if the effective group ID is included but Node.js ensures it always is.</p> <p>This function is only available on POSIX platforms (i.e. not Windows or Android).</p> <h2>process.getuid()<span><a class="mark" href="#process_process_getuid" id="process_process_getuid">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.28</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>The <code>process.getuid()</code> method returns the numeric user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/getuid.2.html"><code>getuid(2)</code></a>.)</p> <pre><code class="language-js">if (process.getuid) { console.log(`Current uid: ${process.getuid()}`); } </code></pre> <p>This function is only available on POSIX platforms (i.e. not Windows or Android).</p> <h2>process.hasUncaughtExceptionCaptureCallback()<span><a class="mark" href="#process_process_hasuncaughtexceptioncapturecallback" id="process_process_hasuncaughtexceptioncapturecallback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v9.3.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Indicates whether a callback has been set using <a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a>.</p> <h2>process.hrtime([time])<span><a class="mark" href="#process_process_hrtime_time" id="process_process_hrtime_time">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.6</span> </div> <ul> <li><code>time</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a> The result of a previous call to <code>process.hrtime()</code></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a></li> </ul> <p>This is the legacy version of <a href="#process_process_hrtime_bigint"><code>process.hrtime.bigint()</code></a> before <code>bigint</code> was introduced in JavaScript.</p> <p>The <code>process.hrtime()</code> method returns the current high-resolution real time in a <code>[seconds, nanoseconds]</code> tuple <code>Array</code>, where <code>nanoseconds</code> is the remaining part of the real time that can't be represented in second precision.</p> <p><code>time</code> is an optional parameter that must be the result of a previous <code>process.hrtime()</code> call to diff with the current time. If the parameter passed in is not a tuple <code>Array</code>, a <code>TypeError</code> will be thrown. Passing in a user-defined array instead of the result of a previous call to <code>process.hrtime()</code> will lead to undefined behavior.</p> <p>These times are relative to an arbitrary time in the past, and not related to the time of day and therefore not subject to clock drift. The primary use is for measuring performance between intervals:</p> <pre><code class="language-js">const NS_PER_SEC = 1e9; const time = process.hrtime(); // [ 1800216, 25 ] setTimeout(() => { const diff = process.hrtime(time); // [ 1, 552 ] console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`); // benchmark took 1000000552 nanoseconds }, 1000); </code></pre> <h2>process.hrtime.bigint()<span><a class="mark" href="#process_process_hrtime_bigint" id="process_process_hrtime_bigint">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.7.0</span> </div> <ul> <li>Returns: <a href="https://github.com/tc39/proposal-bigint" class="type"><bigint></a></li> </ul> <p>The <code>bigint</code> version of the <a href="#process_process_hrtime_time"><code>process.hrtime()</code></a> method returning the current high-resolution real time in a <code>bigint</code>.</p> <p>Unlike <a href="#process_process_hrtime_time"><code>process.hrtime()</code></a>, it does not support an additional <code>time</code> argument since the difference can just be computed directly by subtraction of the two <code>bigint</code>s.</p> <pre><code class="language-js">const start = process.hrtime.bigint(); // 191051479007711n setTimeout(() => { const end = process.hrtime.bigint(); // 191052633396993n console.log(`Benchmark took ${end - start} nanoseconds`); // Benchmark took 1154389282 nanoseconds }, 1000); </code></pre> <h2>process.initgroups(user, extraGroup)<span><a class="mark" href="#process_process_initgroups_user_extragroup" id="process_process_initgroups_user_extragroup">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><code>user</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The user name or numeric identifier.</li> <li><code>extraGroup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A group name or numeric identifier.</li> </ul> <p>The <code>process.initgroups()</code> method reads the <code>/etc/group</code> file and initializes the group access list, using all groups of which the user is a member. This is a privileged operation that requires that the Node.js process either have <code>root</code> access or the <code>CAP_SETGID</code> capability.</p> <p>Note that care must be taken when dropping privileges:</p> <pre><code class="language-js">console.log(process.getgroups()); // [ 0 ] process.initgroups('bnoordhuis', 1000); // switch user console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ] process.setgid(1000); // drop root gid console.log(process.getgroups()); // [ 27, 30, 46, 1000 ] </code></pre> <p>This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p> <h2>process.kill(pid[, signal])<span><a class="mark" href="#process_process_kill_pid_signal" id="process_process_kill_pid_signal">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.0.6</span> </div> <ul> <li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A process ID</li> <li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The signal to send, either as a string or number. <strong>Default:</strong> <code>'SIGTERM'</code>.</li> </ul> <p>The <code>process.kill()</code> method sends the <code>signal</code> to the process identified by <code>pid</code>.</p> <p>Signal names are strings such as <code>'SIGINT'</code> or <code>'SIGHUP'</code>. See <a href="#process_signal_events">Signal Events</a> and <a href="http://man7.org/linux/man-pages/man2/kill.2.html"><code>kill(2)</code></a> for more information.</p> <p>This method will throw an error if the target <code>pid</code> does not exist. As a special case, a signal of <code>0</code> can be used to test for the existence of a process. Windows platforms will throw an error if the <code>pid</code> is used to kill a process group.</p> <p>Even though the name of this function is <code>process.kill()</code>, it is really just a signal sender, like the <code>kill</code> system call. The signal sent may do something other than kill the target process.</p> <pre><code class="language-js">process.on('SIGHUP', () => { console.log('Got SIGHUP signal.'); }); setTimeout(() => { console.log('Exiting.'); process.exit(0); }, 100); process.kill(process.pid, 'SIGHUP'); </code></pre> <p>When <code>SIGUSR1</code> is received by a Node.js process, Node.js will start the debugger. See <a href="#process_signal_events">Signal Events</a>.</p> <h2>process.mainModule<span><a class="mark" href="#process_process_mainmodule" id="process_process_mainmodule">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.17</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>process.mainModule</code> property provides an alternative way of retrieving <a href="#modules_accessing_the_main_module"><code>require.main</code></a>. The difference is that if the main module changes at runtime, <a href="#modules_accessing_the_main_module"><code>require.main</code></a> may still refer to the original main module in modules that were required before the change occurred. Generally, it's safe to assume that the two refer to the same module.</p> <p>As with <a href="#modules_accessing_the_main_module"><code>require.main</code></a>, <code>process.mainModule</code> will be <code>undefined</code> if there is no entry script.</p> <h2>process.memoryUsage()<span><a class="mark" href="#process_process_memoryusage" id="process_process_memoryusage">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.2.0</td> <td><p>Added <code>external</code> to the returned object.</p></td></tr> <tr><td>v0.1.16</td> <td><p><span>Added in: v0.1.16</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>rss</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>heapTotal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>heapUsed</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>external</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> </li> </ul> <p>The <code>process.memoryUsage()</code> method returns an object describing the memory usage of the Node.js process measured in bytes.</p> <p>For example, the code:</p> <pre><code class="language-js">console.log(process.memoryUsage()); </code></pre> <p>Will generate:</p> <!-- eslint-skip --> <pre><code class="language-js">{ rss: 4935680, heapTotal: 1826816, heapUsed: 650472, external: 49879 } </code></pre> <p><code>heapTotal</code> and <code>heapUsed</code> refer to V8's memory usage. <code>external</code> refers to the memory usage of C++ objects bound to JavaScript objects managed by V8. <code>rss</code>, Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the process, which includes the <em>heap</em>, <em>code segment</em> and <em>stack</em>.</p> <p>The <em>heap</em> is where objects, strings, and closures are stored. Variables are stored in the <em>stack</em> and the actual JavaScript code resides in the <em>code segment</em>.</p> <p>When using <a href="#worker_threads_class_worker"><code>Worker</code></a> threads, <code>rss</code> will be a value that is valid for the entire process, while the other fields will only refer to the current thread.</p> <h2>process.nextTick(callback[, ...args])<span><a class="mark" href="#process_process_nexttick_callback_args" id="process_process_nexttick_callback_args">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v1.8.1</td> <td><p>Additional arguments after <code>callback</code> are now supported.</p></td></tr> <tr><td>v0.1.26</td> <td><p><span>Added in: v0.1.26</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Additional arguments to pass when invoking the <code>callback</code></li> </ul> <p>The <code>process.nextTick()</code> method adds the <code>callback</code> to the "next tick queue". Once the current turn of the event loop turn runs to completion, all callbacks currently in the next tick queue will be called.</p> <p>This is <em>not</em> a simple alias to <a href="#timers_settimeout_callback_delay_args"><code>setTimeout(fn, 0)</code></a>. It is much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop.</p> <pre><code class="language-js">console.log('start'); process.nextTick(() => { console.log('nextTick callback'); }); console.log('scheduled'); // Output: // start // scheduled // nextTick callback </code></pre> <p>This is important when developing APIs in order to give users the opportunity to assign event handlers <em>after</em> an object has been constructed but before any I/O has occurred:</p> <pre><code class="language-js">function MyThing(options) { this.setupOptions(options); process.nextTick(() => { this.startDoingStuff(); }); } const thing = new MyThing(); thing.getReadyForStuff(); // thing.startDoingStuff() gets called now, not before. </code></pre> <p>It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example:</p> <pre><code class="language-js">// WARNING! DO NOT USE! BAD UNSAFE HAZARD! function maybeSync(arg, cb) { if (arg) { cb(); return; } fs.stat('file', cb); } </code></pre> <p>This API is hazardous because in the following case:</p> <pre><code class="language-js">const maybeTrue = Math.random() > 0.5; maybeSync(maybeTrue, () => { foo(); }); bar(); </code></pre> <p>It is not clear whether <code>foo()</code> or <code>bar()</code> will be called first.</p> <p>The following approach is much better:</p> <pre><code class="language-js">function definitelyAsync(arg, cb) { if (arg) { process.nextTick(cb); return; } fs.stat('file', cb); } </code></pre> <p>The next tick queue is completely drained on each pass of the event loop <strong>before</strong> additional I/O is processed. As a result, recursively setting <code>nextTick()</code> callbacks will block any I/O from happening, just like a <code>while(true);</code> loop.</p> <h2>process.noDeprecation<span><a class="mark" href="#process_process_nodeprecation" id="process_process_nodeprecation">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.8.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>process.noDeprecation</code> property indicates whether the <code>--no-deprecation</code> flag is set on the current Node.js process. See the documentation for the <a href="#process_event_warning"><code>'warning'</code> event</a> and the <a href="#process_process_emitwarning_warning_type_code_ctor"><code>emitWarning()</code> method</a> for more information about this flag's behavior.</p> <h2>process.pid<span><a class="mark" href="#process_process_pid" id="process_process_pid">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.15</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>The <code>process.pid</code> property returns the PID of the process.</p> <pre><code class="language-js">console.log(`This process is pid ${process.pid}`); </code></pre> <h2>process.platform<span><a class="mark" href="#process_process_platform" id="process_process_platform">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.16</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>process.platform</code> property returns a string identifying the operating system platform on which the Node.js process is running.</p> <p>Currently possible values are:</p> <ul> <li><code>'aix'</code></li> <li><code>'darwin'</code></li> <li><code>'freebsd'</code></li> <li><code>'linux'</code></li> <li><code>'openbsd'</code></li> <li><code>'sunos'</code></li> <li><code>'win32'</code></li> </ul> <pre><code class="language-js">console.log(`This platform is ${process.platform}`); </code></pre> <p>The value <code>'android'</code> may also be returned if the Node.js is built on the Android operating system. However, Android support in Node.js <a href="https://github.com/nodejs/node/blob/master/BUILDING.md#androidandroid-based-devices-eg-firefox-os">is experimental</a>.</p> <h2>process.ppid<span><a class="mark" href="#process_process_ppid" id="process_process_ppid">#</a></span></h2> <div class="api_metadata"> <span>Added in: v9.2.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>The <code>process.ppid</code> property returns the PID of the current parent process.</p> <pre><code class="language-js">console.log(`The parent process is pid ${process.ppid}`); </code></pre> <h2>process.release<span><a class="mark" href="#process_process_release" id="process_process_release">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v4.2.0</td> <td><p>The <code>lts</code> property is now supported.</p></td></tr> <tr><td>v3.0.0</td> <td><p><span>Added in: v3.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>process.release</code> property returns an <code>Object</code> containing metadata related to the current release, including URLs for the source tarball and headers-only tarball.</p> <p><code>process.release</code> contains the following properties:</p> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A value that will always be <code>'node'</code> for Node.js. For legacy io.js releases, this will be <code>'io.js'</code>.</li> <li><code>sourceUrl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> an absolute URL pointing to a <em><code>.tar.gz</code></em> file containing the source code of the current release.</li> <li><code>headersUrl</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> an absolute URL pointing to a <em><code>.tar.gz</code></em> file containing only the source header files for the current release. This file is significantly smaller than the full source file and can be used for compiling Node.js native add-ons.</li> <li><code>libUrl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> an absolute URL pointing to a <em><code>node.lib</code></em> file matching the architecture and version of the current release. This file is used for compiling Node.js native add-ons. <em>This property is only present on Windows builds of Node.js and will be missing on all other platforms.</em></li> <li> <p><code>lts</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> a string label identifying the <a href="https://github.com/nodejs/Release">LTS</a> label for this release. This property only exists for LTS releases and is <code>undefined</code> for all other release types, including <em>Current</em> releases. Currently the valid values are:</p> <ul> <li><code>'Argon'</code> for the 4.x LTS line beginning with 4.2.0.</li> <li><code>'Boron'</code> for the 6.x LTS line beginning with 6.9.0.</li> <li><code>'Carbon'</code> for the 8.x LTS line beginning with 8.9.1.</li> </ul> </li> </ul> <!-- eslint-skip --> <pre><code class="language-js">{ name: 'node', lts: 'Argon', sourceUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5.tar.gz', headersUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5-headers.tar.gz', libUrl: 'https://nodejs.org/download/release/v4.4.5/win-x64/node.lib' } </code></pre> <p>In custom builds from non-release versions of the source tree, only the <code>name</code> property may be present. The additional properties should not be relied upon to exist.</p> <h2>process.send(message[, sendHandle[, options]][, callback])<span><a class="mark" href="#process_process_send_message_sendhandle_options_callback" id="process_process_send_message_sendhandle_options_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.9</span> </div> <ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>sendHandle</code> <a href="#net_class_net_server" class="type"><net.Server></a> | <a href="#net_class_net_socket" class="type"><net.Socket></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>If Node.js is spawned with an IPC channel, the <code>process.send()</code> method can be used to send messages to the parent process. Messages will be received as a <a href="#child_process_event_message"><code>'message'</code></a> event on the parent's <a href="#child_process_class_childprocess"><code>ChildProcess</code></a> object.</p> <p>If Node.js was not spawned with an IPC channel, <code>process.send()</code> will be <code>undefined</code>.</p> <p>The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent.</p> <h2>process.setegid(id)<span><a class="mark" href="#process_process_setegid_id" id="process_process_setegid_id">#</a></span></h2> <div class="api_metadata"> <span>Added in: v2.0.0</span> </div> <ul> <li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A group name or ID</li> </ul> <p>The <code>process.setegid()</code> method sets the effective group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setegid.2.html"><code>setegid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a group name string. If a group name is specified, this method blocks while resolving the associated a numeric ID.</p> <pre><code class="language-js">if (process.getegid && process.setegid) { console.log(`Current gid: ${process.getegid()}`); try { process.setegid(501); console.log(`New gid: ${process.getegid()}`); } catch (err) { console.log(`Failed to set gid: ${err}`); } } </code></pre> <p>This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p> <h2>process.seteuid(id)<span><a class="mark" href="#process_process_seteuid_id" id="process_process_seteuid_id">#</a></span></h2> <div class="api_metadata"> <span>Added in: v2.0.0</span> </div> <ul> <li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A user name or ID</li> </ul> <p>The <code>process.seteuid()</code> method sets the effective user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/seteuid.2.html"><code>seteuid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a username string. If a username is specified, the method blocks while resolving the associated numeric ID.</p> <pre><code class="language-js">if (process.geteuid && process.seteuid) { console.log(`Current uid: ${process.geteuid()}`); try { process.seteuid(501); console.log(`New uid: ${process.geteuid()}`); } catch (err) { console.log(`Failed to set uid: ${err}`); } } </code></pre> <p>This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p> <h2>process.setgid(id)<span><a class="mark" href="#process_process_setgid_id" id="process_process_setgid_id">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.31</span> </div> <ul> <li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The group name or ID</li> </ul> <p>The <code>process.setgid()</code> method sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a group name string. If a group name is specified, this method blocks while resolving the associated numeric ID.</p> <pre><code class="language-js">if (process.getgid && process.setgid) { console.log(`Current gid: ${process.getgid()}`); try { process.setgid(501); console.log(`New gid: ${process.getgid()}`); } catch (err) { console.log(`Failed to set gid: ${err}`); } } </code></pre> <p>This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p> <h2>process.setgroups(groups)<span><a class="mark" href="#process_process_setgroups_groups" id="process_process_setgroups_groups">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><code>groups</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a></li> </ul> <p>The <code>process.setgroups()</code> method sets the supplementary group IDs for the Node.js process. This is a privileged operation that requires the Node.js process to have <code>root</code> or the <code>CAP_SETGID</code> capability.</p> <p>The <code>groups</code> array can contain numeric group IDs, group names or both.</p> <p>This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p> <h2>process.setuid(id)<span><a class="mark" href="#process_process_setuid_id" id="process_process_setuid_id">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.28</span> </div> <ul> <li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>process.setuid(id)</code> method sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a username string. If a username is specified, the method blocks while resolving the associated numeric ID.</p> <pre><code class="language-js">if (process.getuid && process.setuid) { console.log(`Current uid: ${process.getuid()}`); try { process.setuid(501); console.log(`New uid: ${process.getuid()}`); } catch (err) { console.log(`Failed to set uid: ${err}`); } } </code></pre> <p>This function is only available on POSIX platforms (i.e. not Windows or Android). This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p> <h2>process.setUncaughtExceptionCaptureCallback(fn)<span><a class="mark" href="#process_process_setuncaughtexceptioncapturecallback_fn" id="process_process_setuncaughtexceptioncapturecallback_fn">#</a></span></h2> <div class="api_metadata"> <span>Added in: v9.3.0</span> </div> <ul> <li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a></li> </ul> <p>The <code>process.setUncaughtExceptionCaptureCallback()</code> function sets a function that will be invoked when an uncaught exception occurs, which will receive the exception value itself as its first argument.</p> <p>If such a function is set, the <a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a> event will not be emitted. If <code>--abort-on-uncaught-exception</code> was passed from the command line or set through <a href="#v8_v8_setflagsfromstring_flags"><code>v8.setFlagsFromString()</code></a>, the process will not abort.</p> <p>To unset the capture function, <code>process.setUncaughtExceptionCaptureCallback(null)</code> may be used. Calling this method with a non-<code>null</code> argument while another capture function is set will throw an error.</p> <p>Using this function is mutually exclusive with using the deprecated <a href="domain.html"><code>domain</code></a> built-in module.</p> <h2>process.stderr<span><a class="mark" href="#process_process_stderr" id="process_process_stderr">#</a></span></h2> <ul> <li><a href="#stream_stream" class="type"><Stream></a></li> </ul> <p>The <code>process.stderr</code> property returns a stream connected to <code>stderr</code> (fd <code>2</code>). It is a <a href="#net_class_net_socket"><code>net.Socket</code></a> (which is a <a href="#stream_duplex_and_transform_streams">Duplex</a> stream) unless fd <code>2</code> refers to a file, in which case it is a <a href="#stream_writable_streams">Writable</a> stream.</p> <p><code>process.stderr</code> differs from other Node.js streams in important ways. See <a href="#process_a_note_on_process_i_o">note on process I/O</a> for more information.</p> <h2>process.stdin<span><a class="mark" href="#process_process_stdin" id="process_process_stdin">#</a></span></h2> <ul> <li><a href="#stream_stream" class="type"><Stream></a></li> </ul> <p>The <code>process.stdin</code> property returns a stream connected to <code>stdin</code> (fd <code>0</code>). It is a <a href="#net_class_net_socket"><code>net.Socket</code></a> (which is a <a href="#stream_duplex_and_transform_streams">Duplex</a> stream) unless fd <code>0</code> refers to a file, in which case it is a <a href="#stream_readable_streams">Readable</a> stream.</p> <pre><code class="language-js">process.stdin.setEncoding('utf8'); process.stdin.on('readable', () => { let chunk; // Use a loop to make sure we read all available data. while ((chunk = process.stdin.read()) !== null) { process.stdout.write(`data: ${chunk}`); } }); process.stdin.on('end', () => { process.stdout.write('end'); }); </code></pre> <p>As a <a href="#stream_duplex_and_transform_streams">Duplex</a> stream, <code>process.stdin</code> can also be used in "old" mode that is compatible with scripts written for Node.js prior to v0.10. For more information see <a href="#stream_compatibility_with_older_node_js_versions">Stream compatibility</a>.</p> <p>In "old" streams mode the <code>stdin</code> stream is paused by default, so one must call <code>process.stdin.resume()</code> to read from it. Note also that calling <code>process.stdin.resume()</code> itself would switch stream to "old" mode.</p> <h2>process.stdout<span><a class="mark" href="#process_process_stdout" id="process_process_stdout">#</a></span></h2> <ul> <li><a href="#stream_stream" class="type"><Stream></a></li> </ul> <p>The <code>process.stdout</code> property returns a stream connected to <code>stdout</code> (fd <code>1</code>). It is a <a href="#net_class_net_socket"><code>net.Socket</code></a> (which is a <a href="#stream_duplex_and_transform_streams">Duplex</a> stream) unless fd <code>1</code> refers to a file, in which case it is a <a href="#stream_writable_streams">Writable</a> stream.</p> <p>For example, to copy <code>process.stdin</code> to <code>process.stdout</code>:</p> <pre><code class="language-js">process.stdin.pipe(process.stdout); </code></pre> <p><code>process.stdout</code> differs from other Node.js streams in important ways. See <a href="#process_a_note_on_process_i_o">note on process I/O</a> for more information.</p> <h3>A note on process I/O<span><a class="mark" href="#process_a_note_on_process_i_o" id="process_a_note_on_process_i_o">#</a></span></h3> <p><code>process.stdout</code> and <code>process.stderr</code> differ from other Node.js streams in important ways:</p> <ol> <li>They are used internally by <a href="#console_console_log_data_args"><code>console.log()</code></a> and <a href="#console_console_error_data_args"><code>console.error()</code></a>, respectively.</li> <li> <p>Writes may be synchronous depending on what the stream is connected to and whether the system is Windows or POSIX:</p> <ul> <li>Files: <em>synchronous</em> on Windows and POSIX</li> <li>TTYs (Terminals): <em>asynchronous</em> on Windows, <em>synchronous</em> on POSIX</li> <li>Pipes (and sockets): <em>synchronous</em> on Windows, <em>asynchronous</em> on POSIX</li> </ul> </li> </ol> <p>These behaviors are partly for historical reasons, as changing them would create backwards incompatibility, but they are also expected by some users.</p> <p>Synchronous writes avoid problems such as output written with <code>console.log()</code> or <code>console.error()</code> being unexpectedly interleaved, or not written at all if <code>process.exit()</code> is called before an asynchronous write completes. See <a href="#process_process_exit_code"><code>process.exit()</code></a> for more information.</p> <p><strong><em>Warning</em></strong>: Synchronous writes block the event loop until the write has completed. This can be near instantaneous in the case of output to a file, but under high system load, pipes that are not being read at the receiving end, or with slow terminals or file systems, its possible for the event loop to be blocked often enough and long enough to have severe negative performance impacts. This may not be a problem when writing to an interactive terminal session, but consider this particularly careful when doing production logging to the process output streams.</p> <p>To check if a stream is connected to a <a href="#tty_tty">TTY</a> context, check the <code>isTTY</code> property.</p> <p>For instance:</p> <pre><code class="language-console">$ node -p "Boolean(process.stdin.isTTY)" true $ echo "foo" | node -p "Boolean(process.stdin.isTTY)" false $ node -p "Boolean(process.stdout.isTTY)" true $ node -p "Boolean(process.stdout.isTTY)" | cat false </code></pre> <p>See the <a href="#tty_tty">TTY</a> documentation for more information.</p> <h2>process.throwDeprecation<span><a class="mark" href="#process_process_throwdeprecation" id="process_process_throwdeprecation">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.9.12</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>process.throwDeprecation</code> property indicates whether the <code>--throw-deprecation</code> flag is set on the current Node.js process. See the documentation for the <a href="#process_event_warning"><code>'warning'</code> event</a> and the <a href="#process_process_emitwarning_warning_type_code_ctor"><code>emitWarning()</code> method</a> for more information about this flag's behavior.</p> <h2>process.title<span><a class="mark" href="#process_process_title" id="process_process_title">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.104</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>process.title</code> property returns the current process title (i.e. returns the current value of <code>ps</code>). Assigning a new value to <code>process.title</code> modifies the current value of <code>ps</code>.</p> <p>When a new value is assigned, different platforms will impose different maximum length restrictions on the title. Usually such restrictions are quite limited. For instance, on Linux and macOS, <code>process.title</code> is limited to the size of the binary name plus the length of the command line arguments because setting the <code>process.title</code> overwrites the <code>argv</code> memory of the process. Node.js v0.8 allowed for longer process title strings by also overwriting the <code>environ</code> memory but that was potentially insecure and confusing in some (rather obscure) cases.</p> <h2>process.traceDeprecation<span><a class="mark" href="#process_process_tracedeprecation" id="process_process_tracedeprecation">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.8.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>process.traceDeprecation</code> property indicates whether the <code>--trace-deprecation</code> flag is set on the current Node.js process. See the documentation for the <a href="#process_event_warning"><code>'warning'</code> event</a> and the <a href="#process_process_emitwarning_warning_type_code_ctor"><code>emitWarning()</code> method</a> for more information about this flag's behavior.</p> <h2>process.umask([mask])<span><a class="mark" href="#process_process_umask_mask" id="process_process_umask_mask">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.19</span> </div> <ul> <li><code>mask</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <code>process.umask()</code> method sets or returns the Node.js process's file mode creation mask. Child processes inherit the mask from the parent process. Invoked without an argument, the current mask is returned, otherwise the umask is set to the argument value and the previous mask is returned.</p> <pre><code class="language-js">const newmask = 0o022; const oldmask = process.umask(newmask); console.log( `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}` ); </code></pre> <p>This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p> <h2>process.uptime()<span><a class="mark" href="#process_process_uptime" id="process_process_uptime">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <code>process.uptime()</code> method returns the number of seconds the current Node.js process has been running.</p> <p>The return value includes fractions of a second. Use <code>Math.floor()</code> to get whole seconds.</p> <h2>process.version<span><a class="mark" href="#process_process_version" id="process_process_version">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.3</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>process.version</code> property returns the Node.js version string.</p> <pre><code class="language-js">console.log(`Version: ${process.version}`); </code></pre> <h2>process.versions<span><a class="mark" href="#process_process_versions" id="process_process_versions">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>The <code>v8</code> property now includes a Node.js specific suffix.</p></td></tr> <tr><td>v4.2.0</td> <td><p>The <code>icu</code> property is now supported.</p></td></tr> <tr><td>v0.2.0</td> <td><p><span>Added in: v0.2.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The <code>process.versions</code> property returns an object listing the version strings of Node.js and its dependencies. <code>process.versions.modules</code> indicates the current ABI version, which is increased whenever a C++ API changes. Node.js will refuse to load modules that were compiled against a different module ABI version.</p> <pre><code class="language-js">console.log(process.versions); </code></pre> <p>Will generate an object similar to:</p> <!-- eslint-skip --> <pre><code class="language-js">{ http_parser: '2.7.0', node: '8.9.0', v8: '6.3.292.48-node.6', uv: '1.18.0', zlib: '1.2.11', ares: '1.13.0', modules: '60', nghttp2: '1.29.0', napi: '2', openssl: '1.0.2n', icu: '60.1', unicode: '10.0', cldr: '32.0', tz: '2016b' } </code></pre> <h2>Exit Codes<span><a class="mark" href="#process_exit_codes" id="process_exit_codes">#</a></span></h2> <p>Node.js will normally exit with a <code>0</code> status code when no more async operations are pending. The following status codes are used in other cases:</p> <ul> <li><code>1</code> <strong>Uncaught Fatal Exception</strong> - There was an uncaught exception, and it was not handled by a domain or an <a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a> event handler.</li> <li><code>2</code> - Unused (reserved by Bash for builtin misuse)</li> <li><code>3</code> <strong>Internal JavaScript Parse Error</strong> - The JavaScript source code internal in Node.js's bootstrapping process caused a parse error. This is extremely rare, and generally can only happen during development of Node.js itself.</li> <li><code>4</code> <strong>Internal JavaScript Evaluation Failure</strong> - The JavaScript source code internal in Node.js's bootstrapping process failed to return a function value when evaluated. This is extremely rare, and generally can only happen during development of Node.js itself.</li> <li><code>5</code> <strong>Fatal Error</strong> - There was a fatal unrecoverable error in V8. Typically a message will be printed to stderr with the prefix <code>FATAL ERROR</code>.</li> <li><code>6</code> <strong>Non-function Internal Exception Handler</strong> - There was an uncaught exception, but the internal fatal exception handler function was somehow set to a non-function, and could not be called.</li> <li><code>7</code> <strong>Internal Exception Handler Run-Time Failure</strong> - There was an uncaught exception, and the internal fatal exception handler function itself threw an error while attempting to handle it. This can happen, for example, if an <a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a> or <code>domain.on('error')</code> handler throws an error.</li> <li><code>8</code> - Unused. In previous versions of Node.js, exit code 8 sometimes indicated an uncaught exception.</li> <li><code>9</code> - <strong>Invalid Argument</strong> - Either an unknown option was specified, or an option requiring a value was provided without a value.</li> <li><code>10</code> <strong>Internal JavaScript Run-Time Failure</strong> - The JavaScript source code internal in Node.js's bootstrapping process threw an error when the bootstrapping function was called. This is extremely rare, and generally can only happen during development of Node.js itself.</li> <li><code>12</code> <strong>Invalid Debug Argument</strong> - The <code>--inspect</code> and/or <code>--inspect-brk</code> options were set, but the port number chosen was invalid or unavailable.</li> <li><code>>128</code> <strong>Signal Exits</strong> - If Node.js receives a fatal signal such as <code>SIGKILL</code> or <code>SIGHUP</code>, then its exit code will be <code>128</code> plus the value of the signal code. This is a standard POSIX practice, since exit codes are defined to be 7-bit integers, and signal exits set the high-order bit, and then contain the value of the signal code. For example, signal <code>SIGABRT</code> has value <code>6</code>, so the expected exit code will be <code>128</code> + <code>6</code>, or <code>134</code>.</li> </ul> <h1>Punycode<span><a class="mark" href="#punycode_punycode" id="punycode_punycode">#</a></span></h1> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.0.0</td> <td><p>Accessing this module will now emit a deprecation warning.</p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p> <p><strong>The version of the punycode module bundled in Node.js is being deprecated</strong>. In a future major version of Node.js this module will be removed. Users currently depending on the <code>punycode</code> module should switch to using the userland-provided <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> module instead.</p> <p>The <code>punycode</code> module is a bundled version of the <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> module. It can be accessed using:</p> <pre><code class="language-js">const punycode = require('punycode'); </code></pre> <p><a href="https://tools.ietf.org/html/rfc3492">Punycode</a> is a character encoding scheme defined by RFC 3492 that is primarily intended for use in Internationalized Domain Names. Because host names in URLs are limited to ASCII characters only, Domain Names that contain non-ASCII characters must be converted into ASCII using the Punycode scheme. For instance, the Japanese character that translates into the English word, <code>'example'</code> is <code>'例'</code>. The Internationalized Domain Name, <code>'例.com'</code> (equivalent to <code>'example.com'</code>) is represented by Punycode as the ASCII string <code>'xn--fsq.com'</code>.</p> <p>The <code>punycode</code> module provides a simple implementation of the Punycode standard.</p> <p>The <code>punycode</code> module is a third-party dependency used by Node.js and made available to developers as a convenience. Fixes or other modifications to the module must be directed to the <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> project.</p> <h2>punycode.decode(string)<span><a class="mark" href="#punycode_punycode_decode_string" id="punycode_punycode_decode_string">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.1</span> </div> <ul> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>punycode.decode()</code> method converts a <a href="https://tools.ietf.org/html/rfc3492">Punycode</a> string of ASCII-only characters to the equivalent string of Unicode codepoints.</p> <pre><code class="language-js">punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' </code></pre> <h2>punycode.encode(string)<span><a class="mark" href="#punycode_punycode_encode_string" id="punycode_punycode_encode_string">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.1</span> </div> <ul> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>punycode.encode()</code> method converts a string of Unicode codepoints to a <a href="https://tools.ietf.org/html/rfc3492">Punycode</a> string of ASCII-only characters.</p> <pre><code class="language-js">punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' </code></pre> <h2>punycode.toASCII(domain)<span><a class="mark" href="#punycode_punycode_toascii_domain" id="punycode_punycode_toascii_domain">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.6.1</span> </div> <ul> <li><code>domain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>punycode.toASCII()</code> method converts a Unicode string representing an Internationalized Domain Name to <a href="https://tools.ietf.org/html/rfc3492">Punycode</a>. Only the non-ASCII parts of the domain name will be converted. Calling <code>punycode.toASCII()</code> on a string that already only contains ASCII characters will have no effect.</p> <pre><code class="language-js">// encode domain names punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' punycode.toASCII('example.com'); // 'example.com' </code></pre> <h2>punycode.toUnicode(domain)<span><a class="mark" href="#punycode_punycode_tounicode_domain" id="punycode_punycode_tounicode_domain">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.6.1</span> </div> <ul> <li><code>domain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>punycode.toUnicode()</code> method converts a string representing a domain name containing <a href="https://tools.ietf.org/html/rfc3492">Punycode</a> encoded characters into Unicode. Only the <a href="https://tools.ietf.org/html/rfc3492">Punycode</a> encoded parts of the domain name are be converted.</p> <pre><code class="language-js">// decode domain names punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' punycode.toUnicode('example.com'); // 'example.com' </code></pre> <h2>punycode.ucs2<span><a class="mark" href="#punycode_punycode_ucs2" id="punycode_punycode_ucs2">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <h3>punycode.ucs2.decode(string)<span><a class="mark" href="#punycode_punycode_ucs2_decode_string" id="punycode_punycode_ucs2_decode_string">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>punycode.ucs2.decode()</code> method returns an array containing the numeric codepoint values of each Unicode symbol in the string.</p> <pre><code class="language-js">punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63] // surrogate pair for U+1D306 tetragram for centre: punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306] </code></pre> <h3>punycode.ucs2.encode(codePoints)<span><a class="mark" href="#punycode_punycode_ucs2_encode_codepoints" id="punycode_punycode_ucs2_encode_codepoints">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <ul> <li><code>codePoints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a></li> </ul> <p>The <code>punycode.ucs2.encode()</code> method returns a string based on an array of numeric code point values.</p> <pre><code class="language-js">punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc' punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06' </code></pre> <h2>punycode.version<span><a class="mark" href="#punycode_punycode_version" id="punycode_punycode_version">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.6.1</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns a string identifying the current <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> version number.</p> <h1>Query String<span><a class="mark" href="#querystring_query_string" id="querystring_query_string">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>querystring</code> module provides utilities for parsing and formatting URL query strings. It can be accessed using:</p> <pre><code class="language-js">const querystring = require('querystring'); </code></pre> <h2>querystring.decode()<span><a class="mark" href="#querystring_querystring_decode" id="querystring_querystring_decode">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <p>The <code>querystring.decode()</code> function is an alias for <code>querystring.parse()</code>.</p> <h2>querystring.encode()<span><a class="mark" href="#querystring_querystring_encode" id="querystring_querystring_encode">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <p>The <code>querystring.encode()</code> function is an alias for <code>querystring.stringify()</code>.</p> <h2>querystring.escape(str)<span><a class="mark" href="#querystring_querystring_escape_str" id="querystring_querystring_escape_str">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.25</span> </div> <ul> <li><code>str</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>querystring.escape()</code> method performs URL percent-encoding on the given <code>str</code> in a manner that is optimized for the specific requirements of URL query strings.</p> <p>The <code>querystring.escape()</code> method is used by <code>querystring.stringify()</code> and is generally not expected to be used directly. It is exported primarily to allow application code to provide a replacement percent-encoding implementation if necessary by assigning <code>querystring.escape</code> to an alternative function.</p> <h2>querystring.parse(str[, sep[, eq[, options]]])<span><a class="mark" href="#querystring_querystring_parse_str_sep_eq_options" id="querystring_querystring_parse_str_sep_eq_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Multiple empty entries are now parsed correctly (e.g. <code>&=&=</code>).</p></td></tr> <tr><td>v6.0.0</td> <td><p>The returned object no longer inherits from <code>Object.prototype</code>.</p></td></tr> <tr><td>v6.0.0, v4.2.4</td> <td><p>The <code>eq</code> parameter may now have a length of more than <code>1</code>.</p></td></tr> <tr><td>v0.1.25</td> <td><p><span>Added in: v0.1.25</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>str</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The URL query string to parse</li> <li><code>sep</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The substring used to delimit key and value pairs in the query string. <strong>Default:</strong> <code>'&'</code>.</li> <li><code>eq</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>. The substring used to delimit keys and values in the query string. <strong>Default:</strong> <code>'='</code>.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>decodeURIComponent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to use when decoding percent-encoded characters in the query string. <strong>Default:</strong> <code>querystring.unescape()</code>.</li> <li><code>maxKeys</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the maximum number of keys to parse. Specify <code>0</code> to remove key counting limitations. <strong>Default:</strong> <code>1000</code>.</li> </ul> </li> </ul> <p>The <code>querystring.parse()</code> method parses a URL query string (<code>str</code>) into a collection of key and value pairs.</p> <p>For example, the query string <code>'foo=bar&abc=xyz&abc=123'</code> is parsed into:</p> <!-- eslint-skip --> <pre><code class="language-js">{ foo: 'bar', abc: ['xyz', '123'] } </code></pre> <p>The object returned by the <code>querystring.parse()</code> method <em>does not</em> prototypically inherit from the JavaScript <code>Object</code>. This means that typical <code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others are not defined and <em>will not work</em>.</p> <p>By default, percent-encoded characters within the query string will be assumed to use UTF-8 encoding. If an alternative character encoding is used, then an alternative <code>decodeURIComponent</code> option will need to be specified:</p> <pre><code class="language-js">// Assuming gbkDecodeURIComponent function already exists... querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, { decodeURIComponent: gbkDecodeURIComponent }); </code></pre> <h2>querystring.stringify(obj[, sep[, eq[, options]]])<span><a class="mark" href="#querystring_querystring_stringify_obj_sep_eq_options" id="querystring_querystring_stringify_obj_sep_eq_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.25</span> </div> <ul> <li><code>obj</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The object to serialize into a URL query string</li> <li><code>sep</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The substring used to delimit key and value pairs in the query string. <strong>Default:</strong> <code>'&'</code>.</li> <li><code>eq</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a>. The substring used to delimit keys and values in the query string. <strong>Default:</strong> <code>'='</code>.</li> <li> <p><code>options</code></p> <ul> <li><code>encodeURIComponent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to use when converting URL-unsafe characters to percent-encoding in the query string. <strong>Default:</strong> <code>querystring.escape()</code>.</li> </ul> </li> </ul> <p>The <code>querystring.stringify()</code> method produces a URL query string from a given <code>obj</code> by iterating through the object's "own properties".</p> <p>It serializes the following types of values passed in <code>obj</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean[]></a> Any other input values will be coerced to empty strings.</p> <pre><code class="language-js">querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); // returns 'foo=bar&baz=qux&baz=quux&corge=' querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); // returns 'foo:bar;baz:qux' </code></pre> <p>By default, characters requiring percent-encoding within the query string will be encoded as UTF-8. If an alternative encoding is required, then an alternative <code>encodeURIComponent</code> option will need to be specified:</p> <pre><code class="language-js">// Assuming gbkEncodeURIComponent function already exists, querystring.stringify({ w: '中文', foo: 'bar' }, null, null, { encodeURIComponent: gbkEncodeURIComponent }); </code></pre> <h2>querystring.unescape(str)<span><a class="mark" href="#querystring_querystring_unescape_str" id="querystring_querystring_unescape_str">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.25</span> </div> <ul> <li><code>str</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>querystring.unescape()</code> method performs decoding of URL percent-encoded characters on the given <code>str</code>.</p> <p>The <code>querystring.unescape()</code> method is used by <code>querystring.parse()</code> and is generally not expected to be used directly. It is exported primarily to allow application code to provide a replacement decoding implementation if necessary by assigning <code>querystring.unescape</code> to an alternative function.</p> <p>By default, the <code>querystring.unescape()</code> method will attempt to use the JavaScript built-in <code>decodeURIComponent()</code> method to decode. If that fails, a safer equivalent that does not throw on malformed URLs will be used.</p> <h1>Readline<span><a class="mark" href="#readline_readline" id="readline_readline">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>readline</code> module provides an interface for reading data from a <a href="#stream_readable_streams">Readable</a> stream (such as <a href="#process_process_stdin"><code>process.stdin</code></a>) one line at a time. It can be accessed using:</p> <pre><code class="language-js">const readline = require('readline'); </code></pre> <p>The following simple example illustrates the basic use of the <code>readline</code> module.</p> <pre><code class="language-js">const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('What do you think of Node.js? ', (answer) => { // TODO: Log the answer in a database console.log(`Thank you for your valuable feedback: ${answer}`); rl.close(); }); </code></pre> <p>Once this code is invoked, the Node.js application will not terminate until the <code>readline.Interface</code> is closed because the interface waits for data to be received on the <code>input</code> stream.</p> <h2>Class: Interface<span><a class="mark" href="#readline_class_interface" id="readline_class_interface">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.104</span> </div> <p>Instances of the <code>readline.Interface</code> class are constructed using the <code>readline.createInterface()</code> method. Every instance is associated with a single <code>input</code> <a href="#stream_readable_streams">Readable</a> stream and a single <code>output</code> <a href="#stream_writable_streams">Writable</a> stream. The <code>output</code> stream is used to print prompts for user input that arrives on, and is read from, the <code>input</code> stream.</p> <h3>Event: 'close'<span><a class="mark" href="#readline_event_close" id="readline_event_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.98</span> </div> <p>The <code>'close'</code> event is emitted when one of the following occur:</p> <ul> <li>The <code>rl.close()</code> method is called and the <code>readline.Interface</code> instance has relinquished control over the <code>input</code> and <code>output</code> streams;</li> <li>The <code>input</code> stream receives its <code>'end'</code> event;</li> <li>The <code>input</code> stream receives <code><ctrl>-D</code> to signal end-of-transmission (EOT);</li> <li>The <code>input</code> stream receives <code><ctrl>-C</code> to signal <code>SIGINT</code> and there is no <code>'SIGINT'</code> event listener registered on the <code>readline.Interface</code> instance.</li> </ul> <p>The listener function is called without passing any arguments.</p> <p>The <code>readline.Interface</code> instance is finished once the <code>'close'</code> event is emitted.</p> <h3>Event: 'line'<span><a class="mark" href="#readline_event_line" id="readline_event_line">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.98</span> </div> <p>The <code>'line'</code> event is emitted whenever the <code>input</code> stream receives an end-of-line input (<code>\n</code>, <code>\r</code>, or <code>\r\n</code>). This usually occurs when the user presses the <code><Enter></code>, or <code><Return></code> keys.</p> <p>The listener function is called with a string containing the single line of received input.</p> <pre><code class="language-js">rl.on('line', (input) => { console.log(`Received: ${input}`); }); </code></pre> <h3>Event: 'pause'<span><a class="mark" href="#readline_event_pause" id="readline_event_pause">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.5</span> </div> <p>The <code>'pause'</code> event is emitted when one of the following occur:</p> <ul> <li>The <code>input</code> stream is paused.</li> <li>The <code>input</code> stream is not paused and receives the <code>'SIGCONT'</code> event. (See events <a href="#readline_event_sigtstp"><code>'SIGTSTP'</code></a> and <a href="#readline_event_sigcont"><code>'SIGCONT'</code></a>.)</li> </ul> <p>The listener function is called without passing any arguments.</p> <pre><code class="language-js">rl.on('pause', () => { console.log('Readline paused.'); }); </code></pre> <h3>Event: 'resume'<span><a class="mark" href="#readline_event_resume" id="readline_event_resume">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.5</span> </div> <p>The <code>'resume'</code> event is emitted whenever the <code>input</code> stream is resumed.</p> <p>The listener function is called without passing any arguments.</p> <pre><code class="language-js">rl.on('resume', () => { console.log('Readline resumed.'); }); </code></pre> <h3>Event: 'SIGCONT'<span><a class="mark" href="#readline_event_sigcont" id="readline_event_sigcont">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.5</span> </div> <p>The <code>'SIGCONT'</code> event is emitted when a Node.js process previously moved into the background using <code><ctrl>-Z</code> (i.e. <code>SIGTSTP</code>) is then brought back to the foreground using <a href="http://man7.org/linux/man-pages/man1/fg.1p.html"><code>fg(1p)</code></a>.</p> <p>If the <code>input</code> stream was paused <em>before</em> the <code>SIGTSTP</code> request, this event will not be emitted.</p> <p>The listener function is invoked without passing any arguments.</p> <pre><code class="language-js">rl.on('SIGCONT', () => { // `prompt` will automatically resume the stream rl.prompt(); }); </code></pre> <p>The <code>'SIGCONT'</code> event is <em>not</em> supported on Windows.</p> <h3>Event: 'SIGINT'<span><a class="mark" href="#readline_event_sigint" id="readline_event_sigint">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <p>The <code>'SIGINT'</code> event is emitted whenever the <code>input</code> stream receives a <code><ctrl>-C</code> input, known typically as <code>SIGINT</code>. If there are no <code>'SIGINT'</code> event listeners registered when the <code>input</code> stream receives a <code>SIGINT</code>, the <code>'pause'</code> event will be emitted.</p> <p>The listener function is invoked without passing any arguments.</p> <pre><code class="language-js">rl.on('SIGINT', () => { rl.question('Are you sure you want to exit? ', (answer) => { if (answer.match(/^y(es)?$/i)) rl.pause(); }); }); </code></pre> <h3>Event: 'SIGTSTP'<span><a class="mark" href="#readline_event_sigtstp" id="readline_event_sigtstp">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.5</span> </div> <p>The <code>'SIGTSTP'</code> event is emitted when the <code>input</code> stream receives a <code><ctrl>-Z</code> input, typically known as <code>SIGTSTP</code>. If there are no <code>'SIGTSTP'</code> event listeners registered when the <code>input</code> stream receives a <code>SIGTSTP</code>, the Node.js process will be sent to the background.</p> <p>When the program is resumed using <a href="http://man7.org/linux/man-pages/man1/fg.1p.html"><code>fg(1p)</code></a>, the <code>'pause'</code> and <code>'SIGCONT'</code> events will be emitted. These can be used to resume the <code>input</code> stream.</p> <p>The <code>'pause'</code> and <code>'SIGCONT'</code> events will not be emitted if the <code>input</code> was paused before the process was sent to the background.</p> <p>The listener function is invoked without passing any arguments.</p> <pre><code class="language-js">rl.on('SIGTSTP', () => { // This will override SIGTSTP and prevent the program from going to the // background. console.log('Caught SIGTSTP.'); }); </code></pre> <p>The <code>'SIGTSTP'</code> event is <em>not</em> supported on Windows.</p> <h3>rl.close()<span><a class="mark" href="#readline_rl_close" id="readline_rl_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.98</span> </div> <p>The <code>rl.close()</code> method closes the <code>readline.Interface</code> instance and relinquishes control over the <code>input</code> and <code>output</code> streams. When called, the <code>'close'</code> event will be emitted.</p> <p>Calling <code>rl.close()</code> does not immediately stop other events (including <code>'line'</code>) from being emitted by the <code>readline.Interface</code> instance.</p> <h3>rl.pause()<span><a class="mark" href="#readline_rl_pause" id="readline_rl_pause">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.4</span> </div> <p>The <code>rl.pause()</code> method pauses the <code>input</code> stream, allowing it to be resumed later if necessary.</p> <p>Calling <code>rl.pause()</code> does not immediately pause other events (including <code>'line'</code>) from being emitted by the <code>readline.Interface</code> instance.</p> <h3>rl.prompt([preserveCursor])<span><a class="mark" href="#readline_rl_prompt_preservecursor" id="readline_rl_prompt_preservecursor">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.98</span> </div> <ul> <li><code>preserveCursor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, prevents the cursor placement from being reset to <code>0</code>.</li> </ul> <p>The <code>rl.prompt()</code> method writes the <code>readline.Interface</code> instances configured <code>prompt</code> to a new line in <code>output</code> in order to provide a user with a new location at which to provide input.</p> <p>When called, <code>rl.prompt()</code> will resume the <code>input</code> stream if it has been paused.</p> <p>If the <code>readline.Interface</code> was created with <code>output</code> set to <code>null</code> or <code>undefined</code> the prompt is not written.</p> <h3>rl.question(query, callback)<span><a class="mark" href="#readline_rl_question_query_callback" id="readline_rl_question_query_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.3</span> </div> <ul> <li><code>query</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A statement or query to write to <code>output</code>, prepended to the prompt.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that is invoked with the user's input in response to the <code>query</code>.</li> </ul> <p>The <code>rl.question()</code> method displays the <code>query</code> by writing it to the <code>output</code>, waits for user input to be provided on <code>input</code>, then invokes the <code>callback</code> function passing the provided input as the first argument.</p> <p>When called, <code>rl.question()</code> will resume the <code>input</code> stream if it has been paused.</p> <p>If the <code>readline.Interface</code> was created with <code>output</code> set to <code>null</code> or <code>undefined</code> the <code>query</code> is not written.</p> <p>Example usage:</p> <pre><code class="language-js">rl.question('What is your favorite food? ', (answer) => { console.log(`Oh, so your favorite food is ${answer}`); }); </code></pre> <p>The <code>callback</code> function passed to <code>rl.question()</code> does not follow the typical pattern of accepting an <code>Error</code> object or <code>null</code> as the first argument. The <code>callback</code> is called with the provided answer as the only argument.</p> <h3>rl.resume()<span><a class="mark" href="#readline_rl_resume" id="readline_rl_resume">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.4</span> </div> <p>The <code>rl.resume()</code> method resumes the <code>input</code> stream if it has been paused.</p> <h3>rl.setPrompt(prompt)<span><a class="mark" href="#readline_rl_setprompt_prompt" id="readline_rl_setprompt_prompt">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.98</span> </div> <ul> <li><code>prompt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>rl.setPrompt()</code> method sets the prompt that will be written to <code>output</code> whenever <code>rl.prompt()</code> is called.</p> <h3>rl.write(data[, key])<span><a class="mark" href="#readline_rl_write_data_key" id="readline_rl_write_data_key">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.98</span> </div> <ul> <li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li> <p><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>ctrl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to indicate the <code><ctrl></code> key.</li> <li><code>meta</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to indicate the <code><Meta></code> key.</li> <li><code>shift</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to indicate the <code><Shift></code> key.</li> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The name of the a key.</li> </ul> </li> </ul> <p>The <code>rl.write()</code> method will write either <code>data</code> or a key sequence identified by <code>key</code> to the <code>output</code>. The <code>key</code> argument is supported only if <code>output</code> is a <a href="tty.html">TTY</a> text terminal.</p> <p>If <code>key</code> is specified, <code>data</code> is ignored.</p> <p>When called, <code>rl.write()</code> will resume the <code>input</code> stream if it has been paused.</p> <p>If the <code>readline.Interface</code> was created with <code>output</code> set to <code>null</code> or <code>undefined</code> the <code>data</code> and <code>key</code> are not written.</p> <pre><code class="language-js">rl.write('Delete this!'); // Simulate Ctrl+u to delete the line written previously rl.write(null, { ctrl: true, name: 'u' }); </code></pre> <p>The <code>rl.write()</code> method will write the data to the <code>readline</code> <code>Interface</code>'s <code>input</code> <em>as if it were provided by the user</em>.</p> <h3>rl[Symbol.asyncIterator]()<span><a class="mark" href="#readline_rl_symbol_asynciterator" id="readline_rl_symbol_asynciterator">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v11.4.0</td> <td><p><span>Added in: v11.4.0</span></p></td></tr> <tr><td>v10.17.0</td> <td><p>Symbol.asyncIterator support is no longer experimental.</p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <ul> <li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a></li> </ul> <p>Create an <code>AsyncIterator</code> object that iterates through each line in the input stream as a string. This method allows asynchronous iteration of <code>readline.Interface</code> objects through <code>for</code>-<code>await</code>-<code>of</code> loops.</p> <p>Errors in the input stream are not forwarded.</p> <p>If the loop is terminated with <code>break</code>, <code>throw</code>, or <code>return</code>, <a href="#readline_rl_close"><code>rl.close()</code></a> will be called. In other words, iterating over a <code>readline.Interface</code> will always consume the input stream fully.</p> <p>A caveat with using this experimental API is that the performance is currently not on par with the traditional <code>'line'</code> event API, and thus it is not recommended for performance-sensitive applications. We expect this situation to improve in the future.</p> <pre><code class="language-js">async function processLineByLine() { const rl = readline.createInterface({ // ... }); for await (const line of rl) { // Each line in the readline input will be successively available here as // `line`. } } </code></pre> <h2>readline.clearLine(stream, dir)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/readline.js#L1164">[src]</a><span><a class="mark" href="#readline_readline_clearline_stream_dir" id="readline_readline_clearline_stream_dir">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><code>stream</code> <a href="#stream_class_stream_writable" class="type"><stream.Writable></a></li> <li> <p><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></p> <ul> <li><code>-1</code> - to the left from cursor</li> <li><code>1</code> - to the right from cursor</li> <li><code>0</code> - the entire line</li> </ul> </li> </ul> <p>The <code>readline.clearLine()</code> method clears current line of given <a href="tty.html">TTY</a> stream in a specified direction identified by <code>dir</code>.</p> <h2>readline.clearScreenDown(stream)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/readline.js#L1184">[src]</a><span><a class="mark" href="#readline_readline_clearscreendown_stream" id="readline_readline_clearscreendown_stream">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><code>stream</code> <a href="#stream_class_stream_writable" class="type"><stream.Writable></a></li> </ul> <p>The <code>readline.clearScreenDown()</code> method clears the given <a href="tty.html">TTY</a> stream from the current position of the cursor down.</p> <h2>readline.createInterface(options)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/readline.js#L74">[src]</a><span><a class="mark" href="#readline_readline_createinterface_options" id="readline_readline_createinterface_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.3.0, 6.11.4</td> <td><p>Remove max limit of <code>crlfDelay</code> option.</p></td></tr> <tr><td>v6.6.0</td> <td><p>The <code>crlfDelay</code> option is supported now.</p></td></tr> <tr><td>v6.3.0</td> <td><p>The <code>prompt</code> option is supported now.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The <code>historySize</code> option can be <code>0</code> now.</p></td></tr> <tr><td>v0.1.98</td> <td><p><span>Added in: v0.1.98</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>input</code> <a href="#stream_class_stream_readable" class="type"><stream.Readable></a> The <a href="#stream_readable_streams">Readable</a> stream to listen to. This option is <em>required</em>.</li> <li><code>output</code> <a href="#stream_class_stream_writable" class="type"><stream.Writable></a> The <a href="#stream_writable_streams">Writable</a> stream to write readline data to.</li> <li><code>completer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An optional function used for Tab autocompletion.</li> <li><code>terminal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the <code>input</code> and <code>output</code> streams should be treated like a TTY, and have ANSI/VT100 escape codes written to it. <strong>Default:</strong> checking <code>isTTY</code> on the <code>output</code> stream upon instantiation.</li> <li><code>historySize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Maximum number of history lines retained. To disable the history set this value to <code>0</code>. This option makes sense only if <code>terminal</code> is set to <code>true</code> by the user or by an internal <code>output</code> check, otherwise the history caching mechanism is not initialized at all. <strong>Default:</strong> <code>30</code>.</li> <li><code>prompt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The prompt string to use. <strong>Default:</strong> <code>'> '</code>.</li> <li><code>crlfDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If the delay between <code>\r</code> and <code>\n</code> exceeds <code>crlfDelay</code> milliseconds, both <code>\r</code> and <code>\n</code> will be treated as separate end-of-line input. <code>crlfDelay</code> will be coerced to a number no less than <code>100</code>. It can be set to <code>Infinity</code>, in which case <code>\r</code> followed by <code>\n</code> will always be considered a single newline (which may be reasonable for <a href="#readline_example_read_file_stream_line_by_line">reading files</a> with <code>\r\n</code> line delimiter). <strong>Default:</strong> <code>100</code>.</li> <li><code>removeHistoryDuplicates</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, when a new input line added to the history list duplicates an older one, this removes the older line from the list. <strong>Default:</strong> <code>false</code>.</li> <li><code>escapeCodeTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The duration <code>readline</code> will wait for a character (when reading an ambiguous key sequence in milliseconds one that can both form a complete key sequence using the input read so far and can take additional input to complete a longer key sequence). <strong>Default:</strong> <code>500</code>.</li> </ul> </li> </ul> <p>The <code>readline.createInterface()</code> method creates a new <code>readline.Interface</code> instance.</p> <pre><code class="language-js">const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); </code></pre> <p>Once the <code>readline.Interface</code> instance is created, the most common case is to listen for the <code>'line'</code> event:</p> <pre><code class="language-js">rl.on('line', (line) => { console.log(`Received: ${line}`); }); </code></pre> <p>If <code>terminal</code> is <code>true</code> for this instance then the <code>output</code> stream will get the best compatibility if it defines an <code>output.columns</code> property and emits a <code>'resize'</code> event on the <code>output</code> if or when the columns ever change (<a href="#process_process_stdout"><code>process.stdout</code></a> does this automatically when it is a TTY).</p> <h3>Use of the <code>completer</code> Function<span><a class="mark" href="#readline_use_of_the_completer_function" id="readline_use_of_the_completer_function">#</a></span></h3> <p>The <code>completer</code> function takes the current line entered by the user as an argument, and returns an <code>Array</code> with 2 entries:</p> <ul> <li>An <code>Array</code> with matching entries for the completion.</li> <li>The substring that was used for the matching.</li> </ul> <p>For instance: <code>[[substr1, substr2, ...], originalsubstring]</code>.</p> <pre><code class="language-js">function completer(line) { const completions = '.help .error .exit .quit .q'.split(' '); const hits = completions.filter((c) => c.startsWith(line)); // show all completions if none found return [hits.length ? hits : completions, line]; } </code></pre> <p>The <code>completer</code> function can be called asynchronously if it accepts two arguments:</p> <pre><code class="language-js">function completer(linePartial, callback) { callback(null, [['123'], linePartial]); } </code></pre> <h2>readline.cursorTo(stream, x, y)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/readline.js#L1119">[src]</a><span><a class="mark" href="#readline_readline_cursorto_stream_x_y" id="readline_readline_cursorto_stream_x_y">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><code>stream</code> <a href="#stream_class_stream_writable" class="type"><stream.Writable></a></li> <li><code>x</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>y</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <code>readline.cursorTo()</code> method moves cursor to the specified position in a given <a href="tty.html">TTY</a> <code>stream</code>.</p> <h2>readline.emitKeypressEvents(stream[, interface])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/readline.js#L1044">[src]</a><span><a class="mark" href="#readline_readline_emitkeypressevents_stream_interface" id="readline_readline_emitkeypressevents_stream_interface">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><code>stream</code> <a href="#stream_class_stream_readable" class="type"><stream.Readable></a></li> <li><code>interface</code> <a href="#readline_class_interface" class="type"><readline.Interface></a></li> </ul> <p>The <code>readline.emitKeypressEvents()</code> method causes the given <a href="#stream_readable_streams">Readable</a> stream to begin emitting <code>'keypress'</code> events corresponding to received input.</p> <p>Optionally, <code>interface</code> specifies a <code>readline.Interface</code> instance for which autocompletion is disabled when copy-pasted input is detected.</p> <p>If the <code>stream</code> is a <a href="tty.html">TTY</a>, then it must be in raw mode.</p> <p>This is automatically called by any readline instance on its <code>input</code> if the <code>input</code> is a terminal. Closing the <code>readline</code> instance does not stop the <code>input</code> from emitting <code>'keypress'</code> events.</p> <pre><code class="language-js">readline.emitKeypressEvents(process.stdin); if (process.stdin.isTTY) process.stdin.setRawMode(true); </code></pre> <h2>readline.moveCursor(stream, dx, dy)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/readline.js#L1140">[src]</a><span><a class="mark" href="#readline_readline_movecursor_stream_dx_dy" id="readline_readline_movecursor_stream_dx_dy">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><code>stream</code> <a href="#stream_class_stream_writable" class="type"><stream.Writable></a></li> <li><code>dx</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>dy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <code>readline.moveCursor()</code> method moves the cursor <em>relative</em> to its current position in a given <a href="tty.html">TTY</a> <code>stream</code>.</p> <h2>Example: Tiny CLI<span><a class="mark" href="#readline_example_tiny_cli" id="readline_example_tiny_cli">#</a></span></h2> <p>The following example illustrates the use of <code>readline.Interface</code> class to implement a small command-line interface:</p> <pre><code class="language-js">const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, prompt: 'OHAI> ' }); rl.prompt(); rl.on('line', (line) => { switch (line.trim()) { case 'hello': console.log('world!'); break; default: console.log(`Say what? I might have heard '${line.trim()}'`); break; } rl.prompt(); }).on('close', () => { console.log('Have a great day!'); process.exit(0); }); </code></pre> <h2>Example: Read File Stream Line-by-Line<span><a class="mark" href="#readline_example_read_file_stream_line_by_line" id="readline_example_read_file_stream_line_by_line">#</a></span></h2> <p>A common use case for <code>readline</code> is to consume an input file one line at a time. The easiest way to do so is leveraging the <a href="#fs_class_fs_readstream"><code>fs.ReadStream</code></a> API as well as a <code>for</code>-<code>await</code>-<code>of</code> loop:</p> <pre><code class="language-js">const fs = require('fs'); const readline = require('readline'); async function processLineByLine() { const fileStream = fs.createReadStream('input.txt'); const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity }); // Note: we use the crlfDelay option to recognize all instances of CR LF // ('\r\n') in input.txt as a single line break. for await (const line of rl) { // Each line in input.txt will be successively available here as `line`. console.log(`Line from file: ${line}`); } } processLineByLine(); </code></pre> <p>Alternatively, one could use the <a href="#readline_event_line"><code>'line'</code></a> event:</p> <pre><code class="language-js">const fs = require('fs'); const readline = require('readline'); const rl = readline.createInterface({ input: fs.createReadStream('sample.txt'), crlfDelay: Infinity }); rl.on('line', (line) => { console.log(`Line from file: ${line}`); }); </code></pre> <p>Currently, <code>for</code>-<code>await</code>-<code>of</code> loop can be a bit slower. If <code>async</code> / <code>await</code> flow and speed are both essential, a mixed approach can be applied:</p> <pre><code class="language-js">const { once } = require('events'); const { createReadStream } = require('fs'); const { createInterface } = require('readline'); (async function processLineByLine() { try { const rl = createInterface({ input: createReadStream('big-file.txt'), crlfDelay: Infinity }); rl.on('line', (line) => { // Process the line. }); await once(rl, 'close'); console.log('File processed.'); } catch (err) { console.error(err); } })(); </code></pre> <h1>REPL<span><a class="mark" href="#repl_repl" id="repl_repl">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>repl</code> module provides a Read-Eval-Print-Loop (REPL) implementation that is available both as a standalone program or includible in other applications. It can be accessed using:</p> <pre><code class="language-js">const repl = require('repl'); </code></pre> <h2>Design and Features<span><a class="mark" href="#repl_design_and_features" id="repl_design_and_features">#</a></span></h2> <p>The <code>repl</code> module exports the <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> class. While running, instances of <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> will accept individual lines of user input, evaluate those according to a user-defined evaluation function, then output the result. Input and output may be from <code>stdin</code> and <code>stdout</code>, respectively, or may be connected to any Node.js <a href="stream.html">stream</a>.</p> <p>Instances of <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> support automatic completion of inputs, simplistic Emacs-style line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session state, error recovery, and customizable evaluation functions.</p> <h3>Commands and Special Keys<span><a class="mark" href="#repl_commands_and_special_keys" id="repl_commands_and_special_keys">#</a></span></h3> <p>The following special commands are supported by all REPL instances:</p> <ul> <li><code>.break</code> - When in the process of inputting a multi-line expression, entering the <code>.break</code> command (or pressing the <code><ctrl>-C</code> key combination) will abort further input or processing of that expression.</li> <li><code>.clear</code> - Resets the REPL <code>context</code> to an empty object and clears any multi-line expression currently being input.</li> <li><code>.exit</code> - Close the I/O stream, causing the REPL to exit.</li> <li><code>.help</code> - Show this list of special commands.</li> <li><code>.save</code> - Save the current REPL session to a file: <code>> .save ./file/to/save.js</code></li> <li><code>.load</code> - Load a file into the current REPL session. <code>> .load ./file/to/load.js</code></li> <li><code>.editor</code> - Enter editor mode (<code><ctrl>-D</code> to finish, <code><ctrl>-C</code> to cancel).</li> </ul> <!-- eslint-skip --> <pre><code class="language-js">> .editor // Entering editor mode (^D to finish, ^C to cancel) function welcome(name) { return `Hello ${name}!`; } welcome('Node.js User'); // ^D 'Hello Node.js User!' > </code></pre> <p>The following key combinations in the REPL have these special effects:</p> <ul> <li><code><ctrl>-C</code> - When pressed once, has the same effect as the <code>.break</code> command. When pressed twice on a blank line, has the same effect as the <code>.exit</code> command.</li> <li><code><ctrl>-D</code> - Has the same effect as the <code>.exit</code> command.</li> <li><code><tab></code> - When pressed on a blank line, displays global and local (scope) variables. When pressed while entering other input, displays relevant autocompletion options.</li> </ul> <h3>Default Evaluation<span><a class="mark" href="#repl_default_evaluation" id="repl_default_evaluation">#</a></span></h3> <p>By default, all instances of <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> use an evaluation function that evaluates JavaScript expressions and provides access to Node.js' built-in modules. This default behavior can be overridden by passing in an alternative evaluation function when the <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> instance is created.</p> <h4>JavaScript Expressions<span><a class="mark" href="#repl_javascript_expressions" id="repl_javascript_expressions">#</a></span></h4> <p>The default evaluator supports direct evaluation of JavaScript expressions:</p> <!-- eslint-skip --> <pre><code class="language-js">> 1 + 1 2 > const m = 2 undefined > m + 1 3 </code></pre> <p>Unless otherwise scoped within blocks or functions, variables declared either implicitly or using the <code>const</code>, <code>let</code>, or <code>var</code> keywords are declared at the global scope.</p> <h4>Global and Local Scope<span><a class="mark" href="#repl_global_and_local_scope" id="repl_global_and_local_scope">#</a></span></h4> <p>The default evaluator provides access to any variables that exist in the global scope. It is possible to expose a variable to the REPL explicitly by assigning it to the <code>context</code> object associated with each <code>REPLServer</code>:</p> <pre><code class="language-js">const repl = require('repl'); const msg = 'message'; repl.start('> ').context.m = msg; </code></pre> <p>Properties in the <code>context</code> object appear as local within the REPL:</p> <!-- eslint-skip --> <pre><code class="language-js">$ node repl_test.js > m 'message' </code></pre> <p>Context properties are not read-only by default. To specify read-only globals, context properties must be defined using <code>Object.defineProperty()</code>:</p> <pre><code class="language-js">const repl = require('repl'); const msg = 'message'; const r = repl.start('> '); Object.defineProperty(r.context, 'm', { configurable: false, enumerable: true, value: msg }); </code></pre> <h4>Accessing Core Node.js Modules<span><a class="mark" href="#repl_accessing_core_node_js_modules" id="repl_accessing_core_node_js_modules">#</a></span></h4> <p>The default evaluator will automatically load Node.js core modules into the REPL environment when used. For instance, unless otherwise declared as a global or scoped variable, the input <code>fs</code> will be evaluated on-demand as <code>global.fs = require('fs')</code>.</p> <!-- eslint-skip --> <pre><code class="language-js">> fs.createReadStream('./some/file'); </code></pre> <h4>Global Uncaught Exceptions<span><a class="mark" href="#repl_global_uncaught_exceptions" id="repl_global_uncaught_exceptions">#</a></span></h4> <p>The REPL uses the <a href="domain.html"><code>domain</code></a> module to catch all uncaught exceptions for that REPL session.</p> <p>This use of the <a href="domain.html"><code>domain</code></a> module in the REPL has these side effects:</p> <ul> <li>Uncaught exceptions do not emit the <a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a> event.</li> <li>Trying to use <a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> throws an <a href="#errors_err_domain_cannot_set_uncaught_exception_capture"><code>ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</code></a> error.</li> </ul> <h4>Assignment of the <code>_</code> (underscore) variable<span><a class="mark" href="#repl_assignment_of_the_underscore_variable" id="repl_assignment_of_the_underscore_variable">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.8.0</td> <td><p>Added <code>_error</code> support.</p></td></tr> </tbody></table> </details> </div> <p>The default evaluator will, by default, assign the result of the most recently evaluated expression to the special variable <code>_</code> (underscore). Explicitly setting <code>_</code> to a value will disable this behavior.</p> <!-- eslint-skip --> <pre><code class="language-js">> [ 'a', 'b', 'c' ] [ 'a', 'b', 'c' ] > _.length 3 > _ += 1 Expression assignment to _ now disabled. 4 > 1 + 1 2 > _ 4 </code></pre> <p>Similarly, <code>_error</code> will refer to the last seen error, if there was any. Explicitly setting <code>_error</code> to a value will disable this behavior.</p> <!-- eslint-skip --> <pre><code class="language-js">> throw new Error('foo'); Error: foo > _error.message 'foo' </code></pre> <h4><code>await</code> keyword<span><a class="mark" href="#repl_await_keyword" id="repl_await_keyword">#</a></span></h4> <p>With the <a href="#cli_experimental_repl_await"><code>--experimental-repl-await</code></a> command line option specified, experimental support for the <code>await</code> keyword is enabled.</p> <!-- eslint-skip --> <pre><code class="language-js">> await Promise.resolve(123) 123 > await Promise.reject(new Error('REPL await')) Error: REPL await at repl:1:45 > const timeout = util.promisify(setTimeout); undefined > const old = Date.now(); await timeout(1000); console.log(Date.now() - old); 1002 undefined </code></pre> <h3>Custom Evaluation Functions<span><a class="mark" href="#repl_custom_evaluation_functions" id="repl_custom_evaluation_functions">#</a></span></h3> <p>When a new <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> is created, a custom evaluation function may be provided. This can be used, for instance, to implement fully customized REPL applications.</p> <p>The following illustrates a hypothetical example of a REPL that performs translation of text from one language to another:</p> <pre><code class="language-js">const repl = require('repl'); const { Translator } = require('translator'); const myTranslator = new Translator('en', 'fr'); function myEval(cmd, context, filename, callback) { callback(null, myTranslator.translate(cmd)); } repl.start({ prompt: '> ', eval: myEval }); </code></pre> <h4>Recoverable Errors<span><a class="mark" href="#repl_recoverable_errors" id="repl_recoverable_errors">#</a></span></h4> <p>As a user is typing input into the REPL prompt, pressing the <code><enter></code> key will send the current line of input to the <code>eval</code> function. In order to support multi-line input, the eval function can return an instance of <code>repl.Recoverable</code> to the provided callback function:</p> <pre><code class="language-js">function myEval(cmd, context, filename, callback) { let result; try { result = vm.runInThisContext(cmd); } catch (e) { if (isRecoverableError(e)) { return callback(new repl.Recoverable(e)); } } callback(null, result); } function isRecoverableError(error) { if (error.name === 'SyntaxError') { return /^(Unexpected end of input|Unexpected token)/.test(error.message); } return false; } </code></pre> <h3>Customizing REPL Output<span><a class="mark" href="#repl_customizing_repl_output" id="repl_customizing_repl_output">#</a></span></h3> <p>By default, <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> instances format output using the <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> method before writing the output to the provided <code>Writable</code> stream (<code>process.stdout</code> by default). The <code>useColors</code> boolean option can be specified at construction to instruct the default writer to use ANSI style codes to colorize the output from the <code>util.inspect()</code> method.</p> <p>It is possible to fully customize the output of a <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> instance by passing a new function in using the <code>writer</code> option on construction. The following example, for instance, simply converts any input text to upper case:</p> <pre><code class="language-js">const repl = require('repl'); const r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter }); function myEval(cmd, context, filename, callback) { callback(null, cmd); } function myWriter(output) { return output.toUpperCase(); } </code></pre> <h2>Class: REPLServer<span><a class="mark" href="#repl_class_replserver" id="repl_class_replserver">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.91</span> </div> <p>The <code>repl.REPLServer</code> class inherits from the <a href="#readline_class_interface"><code>readline.Interface</code></a> class. Instances of <code>repl.REPLServer</code> are created using the <code>repl.start()</code> method and <em>should not</em> be created directly using the JavaScript <code>new</code> keyword.</p> <h3>Event: 'exit'<span><a class="mark" href="#repl_event_exit" id="repl_event_exit">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <p>The <code>'exit'</code> event is emitted when the REPL is exited either by receiving the <code>.exit</code> command as input, the user pressing <code><ctrl>-C</code> twice to signal <code>SIGINT</code>, or by pressing <code><ctrl>-D</code> to signal <code>'end'</code> on the input stream. The listener callback is invoked without any arguments.</p> <pre><code class="language-js">replServer.on('exit', () => { console.log('Received "exit" event from repl!'); process.exit(); }); </code></pre> <h3>Event: 'reset'<span><a class="mark" href="#repl_event_reset" id="repl_event_reset">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.0</span> </div> <p>The <code>'reset'</code> event is emitted when the REPL's context is reset. This occurs whenever the <code>.clear</code> command is received as input <em>unless</em> the REPL is using the default evaluator and the <code>repl.REPLServer</code> instance was created with the <code>useGlobal</code> option set to <code>true</code>. The listener callback will be called with a reference to the <code>context</code> object as the only argument.</p> <p>This can be used primarily to re-initialize REPL context to some pre-defined state:</p> <pre><code class="language-js">const repl = require('repl'); function initializeContext(context) { context.m = 'test'; } const r = repl.start({ prompt: '> ' }); initializeContext(r.context); r.on('reset', initializeContext); </code></pre> <p>When this code is executed, the global <code>'m'</code> variable can be modified but then reset to its initial value using the <code>.clear</code> command:</p> <!-- eslint-skip --> <pre><code class="language-js">$ ./node example.js > m 'test' > m = 1 1 > m 1 > .clear Clearing context... > m 'test' > </code></pre> <h3>replServer.defineCommand(keyword, cmd)<span><a class="mark" href="#repl_replserver_definecommand_keyword_cmd" id="repl_replserver_definecommand_keyword_cmd">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span> </div> <ul> <li><code>keyword</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The command keyword (<em>without</em> a leading <code>.</code> character).</li> <li><code>cmd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to invoke when the command is processed.</li> </ul> <p>The <code>replServer.defineCommand()</code> method is used to add new <code>.</code>-prefixed commands to the REPL instance. Such commands are invoked by typing a <code>.</code> followed by the <code>keyword</code>. The <code>cmd</code> is either a <code>Function</code> or an <code>Object</code> with the following properties:</p> <ul> <li><code>help</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Help text to be displayed when <code>.help</code> is entered (Optional).</li> <li><code>action</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to execute, optionally accepting a single string argument.</li> </ul> <p>The following example shows two new commands added to the REPL instance:</p> <pre><code class="language-js">const repl = require('repl'); const replServer = repl.start({ prompt: '> ' }); replServer.defineCommand('sayhello', { help: 'Say hello', action(name) { this.clearBufferedCommand(); console.log(`Hello, ${name}!`); this.displayPrompt(); } }); replServer.defineCommand('saybye', function saybye() { console.log('Goodbye!'); this.close(); }); </code></pre> <p>The new commands can then be used from within the REPL instance:</p> <pre><code class="language-txt">> .sayhello Node.js User Hello, Node.js User! > .saybye Goodbye! </code></pre> <h3>replServer.displayPrompt([preserveCursor])<span><a class="mark" href="#repl_replserver_displayprompt_preservecursor" id="repl_replserver_displayprompt_preservecursor">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.91</span> </div> <ul> <li><code>preserveCursor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>replServer.displayPrompt()</code> method readies the REPL instance for input from the user, printing the configured <code>prompt</code> to a new line in the <code>output</code> and resuming the <code>input</code> to accept new input.</p> <p>When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'.</p> <p>When <code>preserveCursor</code> is <code>true</code>, the cursor placement will not be reset to <code>0</code>.</p> <p>The <code>replServer.displayPrompt</code> method is primarily intended to be called from within the action function for commands registered using the <code>replServer.defineCommand()</code> method.</p> <h3>replServer.clearBufferedCommand()<span><a class="mark" href="#repl_replserver_clearbufferedcommand" id="repl_replserver_clearbufferedcommand">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.0.0</span> </div> <p>The <code>replServer.clearBufferedCommand()</code> method clears any command that has been buffered but not yet executed. This method is primarily intended to be called from within the action function for commands registered using the <code>replServer.defineCommand()</code> method.</p> <h3>replServer.parseREPLKeyword(keyword[, rest])<span><a class="mark" href="#repl_replserver_parsereplkeyword_keyword_rest" id="repl_replserver_parsereplkeyword_keyword_rest">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.8.9</span><span>Deprecated since: v9.0.0</span> </div> <ul> <li><code>keyword</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> the potential keyword to parse and execute</li> <li><code>rest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> any parameters to the keyword command</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated.</div><p></p> <p>An internal method used to parse and execute <code>REPLServer</code> keywords. Returns <code>true</code> if <code>keyword</code> is a valid keyword, otherwise <code>false</code>.</p> <h2>repl.start([options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/repl.js#L759">[src]</a><span><a class="mark" href="#repl_repl_start_options" id="repl_repl_start_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>REPL_MAGIC_MODE</code> <code>replMode</code> was removed.</p></td></tr> <tr><td>v5.8.0</td> <td><p>The <code>options</code> parameter is optional now.</p></td></tr> <tr><td>v0.1.91</td> <td><p><span>Added in: v0.1.91</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>prompt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The input prompt to display. <strong>Default:</strong> <code>'> '</code> (with a trailing space).</li> <li><code>input</code> <a href="#stream_class_stream_readable" class="type"><stream.Readable></a> The <code>Readable</code> stream from which REPL input will be read. <strong>Default:</strong> <code>process.stdin</code>.</li> <li><code>output</code> <a href="#stream_class_stream_writable" class="type"><stream.Writable></a> The <code>Writable</code> stream to which REPL output will be written. <strong>Default:</strong> <code>process.stdout</code>.</li> <li><code>terminal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the <code>output</code> should be treated as a TTY terminal, and have ANSI/VT100 escape codes written to it. <strong>Default:</strong> checking the value of the <code>isTTY</code> property on the <code>output</code> stream upon instantiation.</li> <li><code>eval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to be used when evaluating each given line of input. <strong>Default:</strong> an async wrapper for the JavaScript <code>eval()</code> function. An <code>eval</code> function can error with <code>repl.Recoverable</code> to indicate the input was incomplete and prompt for additional lines.</li> <li><code>useColors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the default <code>writer</code> function should include ANSI color styling to REPL output. If a custom <code>writer</code> function is provided then this has no effect. <strong>Default:</strong> the REPL instances <code>terminal</code> value.</li> <li><code>useGlobal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the default evaluation function will use the JavaScript <code>global</code> as the context as opposed to creating a new separate context for the REPL instance. The node CLI REPL sets this value to <code>true</code>. <strong>Default:</strong> <code>false</code>.</li> <li><code>ignoreUndefined</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the default writer will not output the return value of a command if it evaluates to <code>undefined</code>. <strong>Default:</strong> <code>false</code>.</li> <li><code>writer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to invoke to format the output of each command before writing to <code>output</code>. <strong>Default:</strong> <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a>.</li> <li><code>completer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An optional function used for custom Tab auto completion. See <a href="#readline_use_of_the_completer_function"><code>readline.InterfaceCompleter</code></a> for an example.</li> <li> <p><code>replMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default (sloppy) mode. Acceptable values are:</p> <ul> <li><code>repl.REPL_MODE_SLOPPY</code> - evaluates expressions in sloppy mode.</li> <li><code>repl.REPL_MODE_STRICT</code> - evaluates expressions in strict mode. This is equivalent to prefacing every repl statement with <code>'use strict'</code>.</li> </ul> </li> <li><code>breakEvalOnSigint</code> - Stop evaluating the current piece of code when <code>SIGINT</code> is received, i.e. <code>Ctrl+C</code> is pressed. This cannot be used together with a custom <code>eval</code> function. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="#repl_class_replserver" class="type"><repl.REPLServer></a></li> </ul> <p>The <code>repl.start()</code> method creates and starts a <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> instance.</p> <p>If <code>options</code> is a string, then it specifies the input prompt:</p> <pre><code class="language-js">const repl = require('repl'); // a Unix style prompt repl.start('$ '); </code></pre> <h2>The Node.js REPL<span><a class="mark" href="#repl_the_node_js_repl" id="repl_the_node_js_repl">#</a></span></h2> <p>Node.js itself uses the <code>repl</code> module to provide its own interactive interface for executing JavaScript. This can be used by executing the Node.js binary without passing any arguments (or by passing the <code>-i</code> argument):</p> <!-- eslint-skip --> <pre><code class="language-js">$ node > const a = [1, 2, 3]; undefined > a [ 1, 2, 3 ] > a.forEach((v) => { ... console.log(v); ... }); 1 2 3 </code></pre> <h3>Environment Variable Options<span><a class="mark" href="#repl_environment_variable_options" id="repl_environment_variable_options">#</a></span></h3> <p>Various behaviors of the Node.js REPL can be customized using the following environment variables:</p> <ul> <li><code>NODE_REPL_HISTORY</code> - When a valid path is given, persistent REPL history will be saved to the specified file rather than <code>.node_repl_history</code> in the user's home directory. Setting this value to <code>''</code> (an empty string) will disable persistent REPL history. Whitespace will be trimmed from the value. On Windows platforms environment variables with empty values are invalid so set this variable to one or more spaces to disable persistent REPL history.</li> <li><code>NODE_REPL_HISTORY_SIZE</code> - Controls how many lines of history will be persisted if history is available. Must be a positive number. <strong>Default:</strong> <code>1000</code>.</li> <li><code>NODE_REPL_MODE</code> - May be either <code>'sloppy'</code> or <code>'strict'</code>. <strong>Default:</strong> <code>'sloppy'</code>, which will allow non-strict mode code to be run.</li> </ul> <h3>Persistent History<span><a class="mark" href="#repl_persistent_history" id="repl_persistent_history">#</a></span></h3> <p>By default, the Node.js REPL will persist history between <code>node</code> REPL sessions by saving inputs to a <code>.node_repl_history</code> file located in the user's home directory. This can be disabled by setting the environment variable <code>NODE_REPL_HISTORY=''</code>.</p> <h3>Using the Node.js REPL with advanced line-editors<span><a class="mark" href="#repl_using_the_node_js_repl_with_advanced_line_editors" id="repl_using_the_node_js_repl_with_advanced_line_editors">#</a></span></h3> <p>For advanced line-editors, start Node.js with the environment variable <code>NODE_NO_READLINE=1</code>. This will start the main and debugger REPL in canonical terminal settings, which will allow use with <code>rlwrap</code>.</p> <p>For example, the following can be added to a <code>.bashrc</code> file:</p> <pre><code class="language-text">alias node="env NODE_NO_READLINE=1 rlwrap node" </code></pre> <h3>Starting multiple REPL instances against a single running instance<span><a class="mark" href="#repl_starting_multiple_repl_instances_against_a_single_running_instance" id="repl_starting_multiple_repl_instances_against_a_single_running_instance">#</a></span></h3> <p>It is possible to create and run multiple REPL instances against a single running instance of Node.js that share a single <code>global</code> object but have separate I/O interfaces.</p> <p>The following example, for instance, provides separate REPLs on <code>stdin</code>, a Unix socket, and a TCP socket:</p> <pre><code class="language-js">const net = require('net'); const repl = require('repl'); let connections = 0; repl.start({ prompt: 'Node.js via stdin> ', input: process.stdin, output: process.stdout }); net.createServer((socket) => { connections += 1; repl.start({ prompt: 'Node.js via Unix socket> ', input: socket, output: socket }).on('exit', () => { socket.end(); }); }).listen('/tmp/node-repl-sock'); net.createServer((socket) => { connections += 1; repl.start({ prompt: 'Node.js via TCP socket> ', input: socket, output: socket }).on('exit', () => { socket.end(); }); }).listen(5001); </code></pre> <p>Running this application from the command line will start a REPL on stdin. Other REPL clients may connect through the Unix socket or TCP socket. <code>telnet</code>, for instance, is useful for connecting to TCP sockets, while <code>socat</code> can be used to connect to both Unix and TCP sockets.</p> <p>By starting a REPL from a Unix socket-based server instead of stdin, it is possible to connect to a long-running Node.js process without restarting it.</p> <p>For an example of running a "full-featured" (<code>terminal</code>) REPL over a <code>net.Server</code> and <code>net.Socket</code> instance, see: <a href="https://gist.github.com/TooTallNate/2209310">https://gist.github.com/TooTallNate/2209310</a>.</p> <p>For an example of running a REPL instance over <a href="https://curl.haxx.se/docs/manpage.html"></a><a href="http://man7.org/linux/man-pages/man1/curl.1.html"><code>curl(1)</code></a>, see: <a href="https://gist.github.com/TooTallNate/2053342">https://gist.github.com/TooTallNate/2053342</a>.</p> <h1>Stream<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/stream.js#L30">[src]</a><span><a class="mark" href="#stream_stream" id="stream_stream">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>A stream is an abstract interface for working with streaming data in Node.js. The <code>stream</code> module provides a base API that makes it easy to build objects that implement the stream interface.</p> <p>There are many stream objects provided by Node.js. For instance, a <a href="#http_class_http_incomingmessage">request to an HTTP server</a> and <a href="#process_process_stdout"><code>process.stdout</code></a> are both stream instances.</p> <p>Streams can be readable, writable, or both. All streams are instances of <a href="#events_class_eventemitter"><code>EventEmitter</code></a>.</p> <p>The <code>stream</code> module can be accessed using:</p> <pre><code class="language-js">const stream = require('stream'); </code></pre> <p>While it is important to understand how streams work, the <code>stream</code> module itself is most useful for developers that are creating new types of stream instances. Developers who are primarily <em>consuming</em> stream objects will rarely need to use the <code>stream</code> module directly.</p> <h2>Organization of this Document<span><a class="mark" href="#stream_organization_of_this_document" id="stream_organization_of_this_document">#</a></span></h2> <p>This document is divided into two primary sections with a third section for additional notes. The first section explains the elements of the stream API that are required to <em>use</em> streams within an application. The second section explains the elements of the API that are required to <em>implement</em> new types of streams.</p> <h2>Types of Streams<span><a class="mark" href="#stream_types_of_streams" id="stream_types_of_streams">#</a></span></h2> <p>There are four fundamental stream types within Node.js:</p> <ul> <li><a href="#stream_class_stream_writable"><code>Writable</code></a> - streams to which data can be written (for example, <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a>).</li> <li><a href="#stream_class_stream_readable"><code>Readable</code></a> - streams from which data can be read (for example, <a href="#fs_fs_createreadstream_path_options"><code>fs.createReadStream()</code></a>).</li> <li><a href="#stream_class_stream_duplex"><code>Duplex</code></a> - streams that are both <code>Readable</code> and <code>Writable</code> (for example, <a href="#net_class_net_socket"><code>net.Socket</code></a>).</li> <li><a href="#stream_class_stream_transform"><code>Transform</code></a> - <code>Duplex</code> streams that can modify or transform the data as it is written and read (for example, <a href="#zlib_zlib_createdeflate_options"><code>zlib.createDeflate()</code></a>).</li> </ul> <p>Additionally, this module includes the utility functions <a href="#stream_stream_pipeline_streams_callback">pipeline</a>, <a href="#stream_stream_finished_stream_callback">finished</a> and <a href="#readable.from">Readable.from</a>.</p> <h3>Object Mode<span><a class="mark" href="#stream_object_mode" id="stream_object_mode">#</a></span></h3> <p>All streams created by Node.js APIs operate exclusively on strings and <code>Buffer</code> (or <code>Uint8Array</code>) objects. It is possible, however, for stream implementations to work with other types of JavaScript values (with the exception of <code>null</code>, which serves a special purpose within streams). Such streams are considered to operate in "object mode".</p> <p>Stream instances are switched into object mode using the <code>objectMode</code> option when the stream is created. Attempting to switch an existing stream into object mode is not safe.</p> <h3>Buffering<span><a class="mark" href="#stream_buffering" id="stream_buffering">#</a></span></h3> <p>Both <a href="#stream_class_stream_writable"><code>Writable</code></a> and <a href="#stream_class_stream_readable"><code>Readable</code></a> streams will store data in an internal buffer that can be retrieved using <code>writable.writableBuffer</code> or <code>readable.readableBuffer</code>, respectively.</p> <p>The amount of data potentially buffered depends on the <code>highWaterMark</code> option passed into the stream's constructor. For normal streams, the <code>highWaterMark</code> option specifies a <a href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding">total number of bytes</a>. For streams operating in object mode, the <code>highWaterMark</code> specifies a total number of objects.</p> <p>Data is buffered in <code>Readable</code> streams when the implementation calls <a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not call <a href="#stream_readable_read_size"><code>stream.read()</code></a>, the data will sit in the internal queue until it is consumed.</p> <p>Once the total size of the internal read buffer reaches the threshold specified by <code>highWaterMark</code>, the stream will temporarily stop reading data from the underlying resource until the data currently buffered can be consumed (that is, the stream will stop calling the internal <code>readable._read()</code> method that is used to fill the read buffer).</p> <p>Data is buffered in <code>Writable</code> streams when the <a href="#stream_writable_write_chunk_encoding_callback"><code>writable.write(chunk)</code></a> method is called repeatedly. While the total size of the internal write buffer is below the threshold set by <code>highWaterMark</code>, calls to <code>writable.write()</code> will return <code>true</code>. Once the size of the internal buffer reaches or exceeds the <code>highWaterMark</code>, <code>false</code> will be returned.</p> <p>A key goal of the <code>stream</code> API, particularly the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method, is to limit the buffering of data to acceptable levels such that sources and destinations of differing speeds will not overwhelm the available memory.</p> <p>Because <a href="#stream_class_stream_duplex"><code>Duplex</code></a> and <a href="#stream_class_stream_transform"><code>Transform</code></a> streams are both <code>Readable</code> and <code>Writable</code>, each maintains <em>two</em> separate internal buffers used for reading and writing, allowing each side to operate independently of the other while maintaining an appropriate and efficient flow of data. For example, <a href="#net_class_net_socket"><code>net.Socket</code></a> instances are <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams whose <code>Readable</code> side allows consumption of data received <em>from</em> the socket and whose <code>Writable</code> side allows writing data <em>to</em> the socket. Because data may be written to the socket at a faster or slower rate than data is received, it is important for each side to operate (and buffer) independently of the other.</p> <h2>API for Stream Consumers<span><a class="mark" href="#stream_api_for_stream_consumers" id="stream_api_for_stream_consumers">#</a></span></h2> <p>Almost all Node.js applications, no matter how simple, use streams in some manner. The following is an example of using streams in a Node.js application that implements an HTTP server:</p> <pre><code class="language-js">const http = require('http'); const server = http.createServer((req, res) => { // req is an http.IncomingMessage, which is a Readable Stream // res is an http.ServerResponse, which is a Writable Stream let body = ''; // Get the data as utf8 strings. // If an encoding is not set, Buffer objects will be received. req.setEncoding('utf8'); // Readable streams emit 'data' events once a listener is added req.on('data', (chunk) => { body += chunk; }); // the 'end' event indicates that the entire body has been received req.on('end', () => { try { const data = JSON.parse(body); // write back something interesting to the user: res.write(typeof data); res.end(); } catch (er) { // uh oh! bad json! res.statusCode = 400; return res.end(`error: ${er.message}`); } }); }); server.listen(1337); // $ curl localhost:1337 -d "{}" // object // $ curl localhost:1337 -d "\"foo\"" // string // $ curl localhost:1337 -d "not json" // error: Unexpected token o in JSON at position 1 </code></pre> <p><a href="#stream_class_stream_writable"><code>Writable</code></a> streams (such as <code>res</code> in the example) expose methods such as <code>write()</code> and <code>end()</code> that are used to write data onto the stream.</p> <p><a href="#stream_class_stream_readable"><code>Readable</code></a> streams use the <a href="#events_class_eventemitter"><code>EventEmitter</code></a> API for notifying application code when data is available to be read off the stream. That available data can be read from the stream in multiple ways.</p> <p>Both <a href="#stream_class_stream_writable"><code>Writable</code></a> and <a href="#stream_class_stream_readable"><code>Readable</code></a> streams use the <a href="#events_class_eventemitter"><code>EventEmitter</code></a> API in various ways to communicate the current state of the stream.</p> <p><a href="#stream_class_stream_duplex"><code>Duplex</code></a> and <a href="#stream_class_stream_transform"><code>Transform</code></a> streams are both <a href="#stream_class_stream_writable"><code>Writable</code></a> and <a href="#stream_class_stream_readable"><code>Readable</code></a>.</p> <p>Applications that are either writing data to or consuming data from a stream are not required to implement the stream interfaces directly and will generally have no reason to call <code>require('stream')</code>.</p> <p>Developers wishing to implement new types of streams should refer to the section <a href="#stream_api_for_stream_implementers">API for Stream Implementers</a>.</p> <h3>Writable Streams<span><a class="mark" href="#stream_writable_streams" id="stream_writable_streams">#</a></span></h3> <p>Writable streams are an abstraction for a <em>destination</em> to which data is written.</p> <p>Examples of <a href="#stream_class_stream_writable"><code>Writable</code></a> streams include:</p> <ul> <li><a href="#http_class_http_clientrequest">HTTP requests, on the client</a></li> <li><a href="#http_class_http_serverresponse">HTTP responses, on the server</a></li> <li><a href="#fs_class_fs_writestream">fs write streams</a></li> <li><a href="zlib.html">zlib streams</a></li> <li><a href="crypto.html">crypto streams</a></li> <li><a href="#net_class_net_socket">TCP sockets</a></li> <li><a href="#child_process_subprocess_stdin">child process stdin</a></li> <li><a href="#process_process_stdout"><code>process.stdout</code></a>, <a href="#process_process_stderr"><code>process.stderr</code></a></li> </ul> <p>Some of these examples are actually <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams that implement the <a href="#stream_class_stream_writable"><code>Writable</code></a> interface.</p> <p>All <a href="#stream_class_stream_writable"><code>Writable</code></a> streams implement the interface defined by the <code>stream.Writable</code> class.</p> <p>While specific instances of <a href="#stream_class_stream_writable"><code>Writable</code></a> streams may differ in various ways, all <code>Writable</code> streams follow the same fundamental usage pattern as illustrated in the example below:</p> <pre><code class="language-js">const myStream = getWritableStreamSomehow(); myStream.write('some data'); myStream.write('some more data'); myStream.end('done writing data'); </code></pre> <h4>Class: stream.Writable<span><a class="mark" href="#stream_class_stream_writable" id="stream_class_stream_writable">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <h5>Event: 'close'<span><a class="mark" href="#stream_event_close" id="stream_event_close">#</a></span></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr> <tr><td>v0.9.4</td> <td><p><span>Added in: v0.9.4</span></p></td></tr> </tbody></table> </details> </div> <p>The <code>'close'</code> event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates that no more events will be emitted, and no further computation will occur.</p> <p>A <a href="#stream_class_stream_writable"><code>Writable</code></a> stream will always emit the <code>'close'</code> event if it is created with the <code>emitClose</code> option.</p> <h5>Event: 'drain'<span><a class="mark" href="#stream_event_drain" id="stream_event_drain">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <p>If a call to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write(chunk)</code></a> returns <code>false</code>, the <code>'drain'</code> event will be emitted when it is appropriate to resume writing data to the stream.</p> <pre><code class="language-js">// Write the data to the supplied writable stream one million times. // Be attentive to back-pressure. function writeOneMillionTimes(writer, data, encoding, callback) { let i = 1000000; write(); function write() { let ok = true; do { i--; if (i === 0) { // last time! writer.write(data, encoding, callback); } else { // see if we should continue, or wait // don't pass the callback, because we're not done yet. ok = writer.write(data, encoding); } } while (i > 0 && ok); if (i > 0) { // had to stop early! // write some more once it drains writer.once('drain', write); } } } </code></pre> <h5>Event: 'error'<span><a class="mark" href="#stream_event_error" id="stream_event_error">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>The <code>'error'</code> event is emitted if an error occurred while writing or piping data. The listener callback is passed a single <code>Error</code> argument when called.</p> <p>The stream is not closed when the <code>'error'</code> event is emitted.</p> <h5>Event: 'finish'<span><a class="mark" href="#stream_event_finish" id="stream_event_finish">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <p>The <code>'finish'</code> event is emitted after the <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> method has been called, and all data has been flushed to the underlying system.</p> <pre><code class="language-js">const writer = getWritableStreamSomehow(); for (let i = 0; i < 100; i++) { writer.write(`hello, #${i}!\n`); } writer.end('This is the end\n'); writer.on('finish', () => { console.log('All writes are now complete.'); }); </code></pre> <h5>Event: 'pipe'<span><a class="mark" href="#stream_event_pipe" id="stream_event_pipe">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><code>src</code> <a href="#stream_class_stream_readable" class="type"><stream.Readable></a> source stream that is piping to this writable</li> </ul> <p>The <code>'pipe'</code> event is emitted when the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method is called on a readable stream, adding this writable to its set of destinations.</p> <pre><code class="language-js">const writer = getWritableStreamSomehow(); const reader = getReadableStreamSomehow(); writer.on('pipe', (src) => { console.log('Something is piping into the writer.'); assert.equal(src, reader); }); reader.pipe(writer); </code></pre> <h5>Event: 'unpipe'<span><a class="mark" href="#stream_event_unpipe" id="stream_event_unpipe">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><code>src</code> <a href="#stream_class_stream_readable" class="type"><stream.Readable></a> The source stream that <a href="#stream_readable_unpipe_destination">unpiped</a> this writable</li> </ul> <p>The <code>'unpipe'</code> event is emitted when the <a href="#stream_readable_unpipe_destination"><code>stream.unpipe()</code></a> method is called on a <a href="#stream_class_stream_readable"><code>Readable</code></a> stream, removing this <a href="#stream_class_stream_writable"><code>Writable</code></a> from its set of destinations.</p> <p>This is also emitted in case this <a href="#stream_class_stream_writable"><code>Writable</code></a> stream emits an error when a <a href="#stream_class_stream_readable"><code>Readable</code></a> stream pipes into it.</p> <pre><code class="language-js">const writer = getWritableStreamSomehow(); const reader = getReadableStreamSomehow(); writer.on('unpipe', (src) => { console.log('Something has stopped piping into the writer.'); assert.equal(src, reader); }); reader.pipe(writer); reader.unpipe(writer); </code></pre> <h5>writable.cork()<span><a class="mark" href="#stream_writable_cork" id="stream_writable_cork">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.11.2</span> </div> <p>The <code>writable.cork()</code> method forces all written data to be buffered in memory. The buffered data will be flushed when either the <a href="#stream_writable_uncork"><code>stream.uncork()</code></a> or <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> methods are called.</p> <p>The primary intent of <code>writable.cork()</code> is to avoid a situation where writing many small chunks of data to a stream do not cause a backup in the internal buffer that would have an adverse impact on performance. In such situations, implementations that implement the <code>writable._writev()</code> method can perform buffered writes in a more optimized manner.</p> <p>See also: <a href="#stream_writable_uncork"><code>writable.uncork()</code></a>.</p> <h5>writable.destroy([error])<span><a class="mark" href="#stream_writable_destroy_error" id="stream_writable_destroy_error">#</a></span></h5> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Destroy the stream, and emit the passed <code>'error'</code> and a <code>'close'</code> event. After this call, the writable stream has ended and subsequent calls to <code>write()</code> or <code>end()</code> will result in an <code>ERR_STREAM_DESTROYED</code> error. Implementors should not override this method, but instead implement <a href="#stream_writable_destroy_err_callback"><code>writable._destroy()</code></a>.</p> <h5>writable.end([chunk][, encoding][, callback])<span><a class="mark" href="#stream_writable_end_chunk_encoding_callback" id="stream_writable_end_chunk_encoding_callback">#</a></span></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>This method now returns a reference to <code>writable</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> <tr><td>v0.9.4</td> <td><p><span>Added in: v0.9.4</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional data to write. For streams not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or <code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value other than <code>null</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding if <code>chunk</code> is a string</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Optional callback for when the stream is finished</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Calling the <code>writable.end()</code> method signals that no more data will be written to the <a href="#stream_class_stream_writable"><code>Writable</code></a>. The optional <code>chunk</code> and <code>encoding</code> arguments allow one final additional chunk of data to be written immediately before closing the stream. If provided, the optional <code>callback</code> function is attached as a listener for the <a href="#stream_event_finish"><code>'finish'</code></a> event.</p> <p>Calling the <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> method after calling <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> will raise an error.</p> <pre><code class="language-js">// write 'hello, ' and then end with 'world!' const fs = require('fs'); const file = fs.createWriteStream('example.txt'); file.write('hello, '); file.end('world!'); // writing more now is not allowed! </code></pre> <h5>writable.setDefaultEncoding(encoding)<span><a class="mark" href="#stream_writable_setdefaultencoding_encoding" id="stream_writable_setdefaultencoding_encoding">#</a></span></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.1.0</td> <td><p>This method now returns a reference to <code>writable</code>.</p></td></tr> <tr><td>v0.11.15</td> <td><p><span>Added in: v0.11.15</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The new default encoding</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>The <code>writable.setDefaultEncoding()</code> method sets the default <code>encoding</code> for a <a href="#stream_class_stream_writable"><code>Writable</code></a> stream.</p> <h5>writable.uncork()<span><a class="mark" href="#stream_writable_uncork" id="stream_writable_uncork">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.11.2</span> </div> <p>The <code>writable.uncork()</code> method flushes all data buffered since <a href="#stream_writable_cork"><code>stream.cork()</code></a> was called.</p> <p>When using <a href="#stream_writable_cork"><code>writable.cork()</code></a> and <code>writable.uncork()</code> to manage the buffering of writes to a stream, it is recommended that calls to <code>writable.uncork()</code> be deferred using <code>process.nextTick()</code>. Doing so allows batching of all <code>writable.write()</code> calls that occur within a given Node.js event loop phase.</p> <pre><code class="language-js">stream.cork(); stream.write('some '); stream.write('data '); process.nextTick(() => stream.uncork()); </code></pre> <p>If the <a href="#stream_writable_cork"><code>writable.cork()</code></a> method is called multiple times on a stream, the same number of calls to <code>writable.uncork()</code> must be called to flush the buffered data.</p> <pre><code class="language-js">stream.cork(); stream.write('some '); stream.cork(); stream.write('data '); process.nextTick(() => { stream.uncork(); // The data will not be flushed until uncork() is called a second time. stream.uncork(); }); </code></pre> <p>See also: <a href="#stream_writable_cork"><code>writable.cork()</code></a>.</p> <h5>writable.writable<span><a class="mark" href="#stream_writable_writable" id="stream_writable_writable">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.8.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Is <code>true</code> if it is safe to call [<code>writable.write()</code>][].</p> <h5>writable.writableHighWaterMark<span><a class="mark" href="#stream_writable_writablehighwatermark" id="stream_writable_writablehighwatermark">#</a></span></h5> <div class="api_metadata"> <span>Added in: v9.3.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Return the value of <code>highWaterMark</code> passed when constructing this <code>Writable</code>.</p> <h5>writable.writableLength<span><a class="mark" href="#stream_writable_writablelength" id="stream_writable_writablelength">#</a></span></h5> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <p>This property contains the number of bytes (or objects) in the queue ready to be written. The value provides introspection data regarding the status of the <code>highWaterMark</code>.</p> <h5>writable.write(chunk[, encoding][, callback])<span><a class="mark" href="#stream_writable_write_chunk_encoding_callback" id="stream_writable_write_chunk_encoding_callback">#</a></span></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> <tr><td>v6.0.0</td> <td><p>Passing <code>null</code> as the <code>chunk</code> parameter will always be considered invalid now, even in object mode.</p></td></tr> <tr><td>v0.9.4</td> <td><p><span>Added in: v0.9.4</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional data to write. For streams not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or <code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value other than <code>null</code>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding, if <code>chunk</code> is a string</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback for when this chunk of data is flushed</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>false</code> if the stream wishes for the calling code to wait for the <code>'drain'</code> event to be emitted before continuing to write additional data; otherwise <code>true</code>.</li> </ul> <p>The <code>writable.write()</code> method writes some data to the stream, and calls the supplied <code>callback</code> once the data has been fully handled. If an error occurs, the <code>callback</code> <em>may or may not</em> be called with the error as its first argument. To reliably detect write errors, add a listener for the <code>'error'</code> event.</p> <p>The return value is <code>true</code> if the internal buffer is less than the <code>highWaterMark</code> configured when the stream was created after admitting <code>chunk</code>. If <code>false</code> is returned, further attempts to write data to the stream should stop until the <a href="#stream_event_drain"><code>'drain'</code></a> event is emitted.</p> <p>While a stream is not draining, calls to <code>write()</code> will buffer <code>chunk</code>, and return false. Once all currently buffered chunks are drained (accepted for delivery by the operating system), the <code>'drain'</code> event will be emitted. It is recommended that once <code>write()</code> returns false, no more chunks be written until the <code>'drain'</code> event is emitted. While calling <code>write()</code> on a stream that is not draining is allowed, Node.js will buffer all written chunks until maximum memory usage occurs, at which point it will abort unconditionally. Even before it aborts, high memory usage will cause poor garbage collector performance and high RSS (which is not typically released back to the system, even after the memory is no longer required). Since TCP sockets may never drain if the remote peer does not read the data, writing a socket that is not draining may lead to a remotely exploitable vulnerability.</p> <p>Writing data while the stream is not draining is particularly problematic for a <a href="#stream_class_stream_transform"><code>Transform</code></a>, because the <code>Transform</code> streams are paused by default until they are piped or a <code>'data'</code> or <code>'readable'</code> event handler is added.</p> <p>If the data to be written can be generated or fetched on demand, it is recommended to encapsulate the logic into a <a href="#stream_class_stream_readable"><code>Readable</code></a> and use <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a>. However, if calling <code>write()</code> is preferred, it is possible to respect backpressure and avoid memory issues using the <a href="#stream_event_drain"><code>'drain'</code></a> event:</p> <pre><code class="language-js">function write(data, cb) { if (!stream.write(data)) { stream.once('drain', cb); } else { process.nextTick(cb); } } // Wait for cb to be called before doing any other write. write('hello', () => { console.log('Write completed, do more writes now.'); }); </code></pre> <p>A <code>Writable</code> stream in object mode will always ignore the <code>encoding</code> argument.</p> <h3>Readable Streams<span><a class="mark" href="#stream_readable_streams" id="stream_readable_streams">#</a></span></h3> <p>Readable streams are an abstraction for a <em>source</em> from which data is consumed.</p> <p>Examples of <code>Readable</code> streams include:</p> <ul> <li><a href="#http_class_http_incomingmessage">HTTP responses, on the client</a></li> <li><a href="#http_class_http_incomingmessage">HTTP requests, on the server</a></li> <li><a href="#fs_class_fs_readstream">fs read streams</a></li> <li><a href="zlib.html">zlib streams</a></li> <li><a href="crypto.html">crypto streams</a></li> <li><a href="#net_class_net_socket">TCP sockets</a></li> <li><a href="#child_process_subprocess_stdout">child process stdout and stderr</a></li> <li><a href="#process_process_stdin"><code>process.stdin</code></a></li> </ul> <p>All <a href="#stream_class_stream_readable"><code>Readable</code></a> streams implement the interface defined by the <code>stream.Readable</code> class.</p> <h4>Two Reading Modes<span><a class="mark" href="#stream_two_reading_modes" id="stream_two_reading_modes">#</a></span></h4> <p><code>Readable</code> streams effectively operate in one of two modes: flowing and paused. These modes are separate from <a href="#stream_object_mode">object mode</a>. A <a href="#stream_class_stream_readable"><code>Readable</code></a> stream can be in object mode or not, regardless of whether it is in flowing mode or paused mode.</p> <ul> <li> <p>In flowing mode, data is read from the underlying system automatically and provided to an application as quickly as possible using events via the <a href="#events_class_eventemitter"><code>EventEmitter</code></a> interface.</p> </li> <li> <p>In paused mode, the <a href="#stream_readable_read_size"><code>stream.read()</code></a> method must be called explicitly to read chunks of data from the stream.</p> </li> </ul> <p>All <a href="#stream_class_stream_readable"><code>Readable</code></a> streams begin in paused mode but can be switched to flowing mode in one of the following ways:</p> <ul> <li>Adding a <a href="#stream_event_data"><code>'data'</code></a> event handler.</li> <li>Calling the <a href="#stream_readable_resume"><code>stream.resume()</code></a> method.</li> <li>Calling the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method to send the data to a <a href="#stream_class_stream_writable"><code>Writable</code></a>.</li> </ul> <p>The <code>Readable</code> can switch back to paused mode using one of the following:</p> <ul> <li>If there are no pipe destinations, by calling the <a href="#stream_readable_pause"><code>stream.pause()</code></a> method.</li> <li>If there are pipe destinations, by removing all pipe destinations. Multiple pipe destinations may be removed by calling the <a href="#stream_readable_unpipe_destination"><code>stream.unpipe()</code></a> method.</li> </ul> <p>The important concept to remember is that a <code>Readable</code> will not generate data until a mechanism for either consuming or ignoring that data is provided. If the consuming mechanism is disabled or taken away, the <code>Readable</code> will <em>attempt</em> to stop generating the data.</p> <p>For backward compatibility reasons, removing <a href="#stream_event_data"><code>'data'</code></a> event handlers will <strong>not</strong> automatically pause the stream. Also, if there are piped destinations, then calling <a href="#stream_readable_pause"><code>stream.pause()</code></a> will not guarantee that the stream will <em>remain</em> paused once those destinations drain and ask for more data.</p> <p>If a <a href="#stream_class_stream_readable"><code>Readable</code></a> is switched into flowing mode and there are no consumers available to handle the data, that data will be lost. This can occur, for instance, when the <code>readable.resume()</code> method is called without a listener attached to the <code>'data'</code> event, or when a <code>'data'</code> event handler is removed from the stream.</p> <p>Adding a <a href="#stream_event_readable"><code>'readable'</code></a> event handler automatically make the stream to stop flowing, and the data to be consumed via <a href="#stream_readable_read_size"><code>readable.read()</code></a>. If the <a href="#stream_event_readable"><code>'readable'</code></a> event handler is removed, then the stream will start flowing again if there is a <a href="#stream_event_data"><code>'data'</code></a> event handler.</p> <h4>Three States<span><a class="mark" href="#stream_three_states" id="stream_three_states">#</a></span></h4> <p>The "two modes" of operation for a <code>Readable</code> stream are a simplified abstraction for the more complicated internal state management that is happening within the <code>Readable</code> stream implementation.</p> <p>Specifically, at any given point in time, every <code>Readable</code> is in one of three possible states:</p> <ul> <li><code>readable.readableFlowing === null</code></li> <li><code>readable.readableFlowing === false</code></li> <li><code>readable.readableFlowing === true</code></li> </ul> <p>When <code>readable.readableFlowing</code> is <code>null</code>, no mechanism for consuming the stream's data is provided. Therefore, the stream will not generate data. While in this state, attaching a listener for the <code>'data'</code> event, calling the <code>readable.pipe()</code> method, or calling the <code>readable.resume()</code> method will switch <code>readable.readableFlowing</code> to <code>true</code>, causing the <code>Readable</code> to begin actively emitting events as data is generated.</p> <p>Calling <code>readable.pause()</code>, <code>readable.unpipe()</code>, or receiving backpressure will cause the <code>readable.readableFlowing</code> to be set as <code>false</code>, temporarily halting the flowing of events but <em>not</em> halting the generation of data. While in this state, attaching a listener for the <code>'data'</code> event will not switch <code>readable.readableFlowing</code> to <code>true</code>.</p> <pre><code class="language-js">const { PassThrough, Writable } = require('stream'); const pass = new PassThrough(); const writable = new Writable(); pass.pipe(writable); pass.unpipe(writable); // readableFlowing is now false pass.on('data', (chunk) => { console.log(chunk.toString()); }); pass.write('ok'); // will not emit 'data' pass.resume(); // must be called to make stream emit 'data' </code></pre> <p>While <code>readable.readableFlowing</code> is <code>false</code>, data may be accumulating within the stream's internal buffer.</p> <h4>Choose One API Style<span><a class="mark" href="#stream_choose_one_api_style" id="stream_choose_one_api_style">#</a></span></h4> <p>The <code>Readable</code> stream API evolved across multiple Node.js versions and provides multiple methods of consuming stream data. In general, developers should choose <em>one</em> of the methods of consuming data and <em>should never</em> use multiple methods to consume data from a single stream. Specifically, using a combination of <code>on('data')</code>, <code>on('readable')</code>, <code>pipe()</code>, or async iterators could lead to unintuitive behavior.</p> <p>Use of the <code>readable.pipe()</code> method is recommended for most users as it has been implemented to provide the easiest way of consuming stream data. Developers that require more fine-grained control over the transfer and generation of data can use the <a href="#events_class_eventemitter"><code>EventEmitter</code></a> and <code>readable.on('readable')</code>/<code>readable.read()</code> or the <code>readable.pause()</code>/<code>readable.resume()</code> APIs.</p> <h4>Class: stream.Readable<span><a class="mark" href="#stream_class_stream_readable" id="stream_class_stream_readable">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <h5>Event: 'close'<span><a class="mark" href="#stream_event_close_1" id="stream_event_close_1">#</a></span></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr> <tr><td>v0.9.4</td> <td><p><span>Added in: v0.9.4</span></p></td></tr> </tbody></table> </details> </div> <p>The <code>'close'</code> event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates that no more events will be emitted, and no further computation will occur.</p> <p>A <a href="#stream_class_stream_readable"><code>Readable</code></a> stream will always emit the <code>'close'</code> event if it is created with the <code>emitClose</code> option.</p> <h5>Event: 'data'<span><a class="mark" href="#stream_event_data" id="stream_event_data">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><code>chunk</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or <code>Buffer</code>. For streams that are in object mode, the chunk can be any JavaScript value other than <code>null</code>.</li> </ul> <p>The <code>'data'</code> event is emitted whenever the stream is relinquishing ownership of a chunk of data to a consumer. This may occur whenever the stream is switched in flowing mode by calling <code>readable.pipe()</code>, <code>readable.resume()</code>, or by attaching a listener callback to the <code>'data'</code> event. The <code>'data'</code> event will also be emitted whenever the <code>readable.read()</code> method is called and a chunk of data is available to be returned.</p> <p>Attaching a <code>'data'</code> event listener to a stream that has not been explicitly paused will switch the stream into flowing mode. Data will then be passed as soon as it is available.</p> <p>The listener callback will be passed the chunk of data as a string if a default encoding has been specified for the stream using the <code>readable.setEncoding()</code> method; otherwise the data will be passed as a <code>Buffer</code>.</p> <pre><code class="language-js">const readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { console.log(`Received ${chunk.length} bytes of data.`); }); </code></pre> <h5>Event: 'end'<span><a class="mark" href="#stream_event_end" id="stream_event_end">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <p>The <code>'end'</code> event is emitted when there is no more data to be consumed from the stream.</p> <p>The <code>'end'</code> event <strong>will not be emitted</strong> unless the data is completely consumed. This can be accomplished by switching the stream into flowing mode, or by calling <a href="#stream_readable_read_size"><code>stream.read()</code></a> repeatedly until all data has been consumed.</p> <pre><code class="language-js">const readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { console.log(`Received ${chunk.length} bytes of data.`); }); readable.on('end', () => { console.log('There will be no more data.'); }); </code></pre> <h5>Event: 'error'<span><a class="mark" href="#stream_event_error_1" id="stream_event_error_1">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>The <code>'error'</code> event may be emitted by a <code>Readable</code> implementation at any time. Typically, this may occur if the underlying stream is unable to generate data due to an underlying internal failure, or when a stream implementation attempts to push an invalid chunk of data.</p> <p>The listener callback will be passed a single <code>Error</code> object.</p> <h5>Event: 'readable'<span><a class="mark" href="#stream_event_readable" id="stream_event_readable">#</a></span></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>'readable'</code> is always emitted in the next tick after <code>.push()</code> is called</p></td></tr> <tr><td>v10.0.0</td> <td><p>Using <code>'readable'</code> requires calling <code>.read()</code>.</p></td></tr> <tr><td>v0.9.4</td> <td><p><span>Added in: v0.9.4</span></p></td></tr> </tbody></table> </details> </div> <p>The <code>'readable'</code> event is emitted when there is data available to be read from the stream. In some cases, attaching a listener for the <code>'readable'</code> event will cause some amount of data to be read into an internal buffer.</p> <pre><code class="language-javascript">const readable = getReadableStreamSomehow(); readable.on('readable', function() { // there is some data to read now let data; while (data = this.read()) { console.log(data); } }); </code></pre> <p>The <code>'readable'</code> event will also be emitted once the end of the stream data has been reached but before the <code>'end'</code> event is emitted.</p> <p>Effectively, the <code>'readable'</code> event indicates that the stream has new information: either new data is available or the end of the stream has been reached. In the former case, <a href="#stream_readable_read_size"><code>stream.read()</code></a> will return the available data. In the latter case, <a href="#stream_readable_read_size"><code>stream.read()</code></a> will return <code>null</code>. For instance, in the following example, <code>foo.txt</code> is an empty file:</p> <pre><code class="language-js">const fs = require('fs'); const rr = fs.createReadStream('foo.txt'); rr.on('readable', () => { console.log(`readable: ${rr.read()}`); }); rr.on('end', () => { console.log('end'); }); </code></pre> <p>The output of running this script is:</p> <pre><code class="language-txt">$ node test.js readable: null end </code></pre> <p>In general, the <code>readable.pipe()</code> and <code>'data'</code> event mechanisms are easier to understand than the <code>'readable'</code> event. However, handling <code>'readable'</code> might result in increased throughput.</p> <p>If both <code>'readable'</code> and <a href="#stream_event_data"><code>'data'</code></a> are used at the same time, <code>'readable'</code> takes precedence in controlling the flow, i.e. <code>'data'</code> will be emitted only when <a href="#stream_readable_read_size"><code>stream.read()</code></a> is called. The <code>readableFlowing</code> property would become <code>false</code>. If there are <code>'data'</code> listeners when <code>'readable'</code> is removed, the stream will start flowing, i.e. <code>'data'</code> events will be emitted without calling <code>.resume()</code>.</p> <h5>readable.destroy([error])<span><a class="mark" href="#stream_readable_destroy_error" id="stream_readable_destroy_error">#</a></span></h5> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> Error which will be passed as payload in <code>'error'</code> event</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Destroy the stream, and emit <code>'error'</code> and <code>'close'</code>. After this call, the readable stream will release any internal resources and subsequent calls to <code>push()</code> will be ignored. Implementors should not override this method, but instead implement <a href="#stream_readable_destroy_err_callback"><code>readable._destroy()</code></a>.</p> <h5>readable.isPaused()<span><a class="mark" href="#stream_readable_ispaused" id="stream_readable_ispaused">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>readable.isPaused()</code> method returns the current operating state of the <code>Readable</code>. This is used primarily by the mechanism that underlies the <code>readable.pipe()</code> method. In most typical cases, there will be no reason to use this method directly.</p> <pre><code class="language-js">const readable = new stream.Readable(); readable.isPaused(); // === false readable.pause(); readable.isPaused(); // === true readable.resume(); readable.isPaused(); // === false </code></pre> <h5>readable.pause()<span><a class="mark" href="#stream_readable_pause" id="stream_readable_pause">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>The <code>readable.pause()</code> method will cause a stream in flowing mode to stop emitting <a href="#stream_event_data"><code>'data'</code></a> events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.</p> <pre><code class="language-js">const readable = getReadableStreamSomehow(); readable.on('data', (chunk) => { console.log(`Received ${chunk.length} bytes of data.`); readable.pause(); console.log('There will be no additional data for 1 second.'); setTimeout(() => { console.log('Now data will start flowing again.'); readable.resume(); }, 1000); }); </code></pre> <p>The <code>readable.pause()</code> method has no effect if there is a <code>'readable'</code> event listener.</p> <h5>readable.pipe(destination[, options])<span><a class="mark" href="#stream_readable_pipe_destination_options" id="stream_readable_pipe_destination_options">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><code>destination</code> <a href="#stream_class_stream_writable" class="type"><stream.Writable></a> The destination for writing data</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Pipe options</p> <ul> <li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> End the writer when the reader ends. <strong>Default:</strong> <code>true</code>.</li> </ul> </li> <li>Returns: <a href="#stream_class_stream_writable" class="type"><stream.Writable></a> The <em>destination</em>, allowing for a chain of pipes if it is a <a href="#stream_class_stream_duplex"><code>Duplex</code></a> or a <a href="#stream_class_stream_transform"><code>Transform</code></a> stream</li> </ul> <p>The <code>readable.pipe()</code> method attaches a <a href="#stream_class_stream_writable"><code>Writable</code></a> stream to the <code>readable</code>, causing it to switch automatically into flowing mode and push all of its data to the attached <a href="#stream_class_stream_writable"><code>Writable</code></a>. The flow of data will be automatically managed so that the destination <code>Writable</code> stream is not overwhelmed by a faster <code>Readable</code> stream.</p> <p>The following example pipes all of the data from the <code>readable</code> into a file named <code>file.txt</code>:</p> <pre><code class="language-js">const fs = require('fs'); const readable = getReadableStreamSomehow(); const writable = fs.createWriteStream('file.txt'); // All the data from readable goes into 'file.txt' readable.pipe(writable); </code></pre> <p>It is possible to attach multiple <code>Writable</code> streams to a single <code>Readable</code> stream.</p> <p>The <code>readable.pipe()</code> method returns a reference to the <em>destination</em> stream making it possible to set up chains of piped streams:</p> <pre><code class="language-js">const fs = require('fs'); const r = fs.createReadStream('file.txt'); const z = zlib.createGzip(); const w = fs.createWriteStream('file.txt.gz'); r.pipe(z).pipe(w); </code></pre> <p>By default, <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> is called on the destination <code>Writable</code> stream when the source <code>Readable</code> stream emits <a href="#stream_event_end"><code>'end'</code></a>, so that the destination is no longer writable. To disable this default behavior, the <code>end</code> option can be passed as <code>false</code>, causing the destination stream to remain open:</p> <pre><code class="language-js">reader.pipe(writer, { end: false }); reader.on('end', () => { writer.end('Goodbye\n'); }); </code></pre> <p>One important caveat is that if the <code>Readable</code> stream emits an error during processing, the <code>Writable</code> destination <em>is not closed</em> automatically. If an error occurs, it will be necessary to <em>manually</em> close each stream in order to prevent memory leaks.</p> <p>The <a href="#process_process_stderr"><code>process.stderr</code></a> and <a href="#process_process_stdout"><code>process.stdout</code></a> <code>Writable</code> streams are never closed until the Node.js process exits, regardless of the specified options.</p> <h5>readable.read([size])<span><a class="mark" href="#stream_readable_read_size" id="stream_readable_read_size">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optional argument to specify how much data to read.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>The <code>readable.read()</code> method pulls some data out of the internal buffer and returns it. If no data available to be read, <code>null</code> is returned. By default, the data will be returned as a <code>Buffer</code> object unless an encoding has been specified using the <code>readable.setEncoding()</code> method or the stream is operating in object mode.</p> <p>The optional <code>size</code> argument specifies a specific number of bytes to read. If <code>size</code> bytes are not available to be read, <code>null</code> will be returned <em>unless</em> the stream has ended, in which case all of the data remaining in the internal buffer will be returned.</p> <p>If the <code>size</code> argument is not specified, all of the data contained in the internal buffer will be returned.</p> <p>The <code>size</code> argument must be less than or equal to 1 GB.</p> <p>The <code>readable.read()</code> method should only be called on <code>Readable</code> streams operating in paused mode. In flowing mode, <code>readable.read()</code> is called automatically until the internal buffer is fully drained.</p> <pre><code class="language-js">const readable = getReadableStreamSomehow(); readable.on('readable', () => { let chunk; while (null !== (chunk = readable.read())) { console.log(`Received ${chunk.length} bytes of data.`); } }); </code></pre> <p>Note that the <code>while</code> loop is necessary when processing data with <code>readable.read()</code>. Only after <code>readable.read()</code> returns <code>null</code>, <a href=""><code>'readable'</code></a> will be emitted.</p> <p>A <code>Readable</code> stream in object mode will always return a single item from a call to <a href="#stream_readable_read_size"><code>readable.read(size)</code></a>, regardless of the value of the <code>size</code> argument.</p> <p>If the <code>readable.read()</code> method returns a chunk of data, a <code>'data'</code> event will also be emitted.</p> <p>Calling <a href="#stream_readable_read_size"><code>stream.read([size])</code></a> after the <a href="#stream_event_end"><code>'end'</code></a> event has been emitted will return <code>null</code>. No runtime error will be raised.</p> <h5>readable.readable<span><a class="mark" href="#stream_readable_readable" id="stream_readable_readable">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.8.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Is <code>true</code> if it is safe to call [<code>readable.read()</code>][].</p> <h5>readable.readableFlowing<span><a class="mark" href="#stream_readable_readableflowing" id="stream_readable_readableflowing">#</a></span></h5> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>This property reflects the current state of a <code>Readable</code> stream as described in the <a href="#stream_three_states">Stream Three States</a> section.</p> <h5>readable.readableHighWaterMark<span><a class="mark" href="#stream_readable_readablehighwatermark" id="stream_readable_readablehighwatermark">#</a></span></h5> <div class="api_metadata"> <span>Added in: v9.3.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Returns the value of <code>highWaterMark</code> passed when constructing this <code>Readable</code>.</p> <h5>readable.readableLength<span><a class="mark" href="#stream_readable_readablelength" id="stream_readable_readablelength">#</a></span></h5> <div class="api_metadata"> <span>Added in: v9.4.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>This property contains the number of bytes (or objects) in the queue ready to be read. The value provides introspection data regarding the status of the <code>highWaterMark</code>.</p> <h5>readable.resume()<span><a class="mark" href="#stream_readable_resume" id="stream_readable_resume">#</a></span></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>resume()</code> has no effect if there is a <code>'readable'</code> event listening.</p></td></tr> <tr><td>v0.9.4</td> <td><p><span>Added in: v0.9.4</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>The <code>readable.resume()</code> method causes an explicitly paused <code>Readable</code> stream to resume emitting <a href="#stream_event_data"><code>'data'</code></a> events, switching the stream into flowing mode.</p> <p>The <code>readable.resume()</code> method can be used to fully consume the data from a stream without actually processing any of that data:</p> <pre><code class="language-js">getReadableStreamSomehow() .resume() .on('end', () => { console.log('Reached the end, but did not read anything.'); }); </code></pre> <p>The <code>readable.resume()</code> method has no effect if there is a <code>'readable'</code> event listener.</p> <h5>readable.setEncoding(encoding)<span><a class="mark" href="#stream_readable_setencoding_encoding" id="stream_readable_setencoding_encoding">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The encoding to use.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>The <code>readable.setEncoding()</code> method sets the character encoding for data read from the <code>Readable</code> stream.</p> <p>By default, no encoding is assigned and stream data will be returned as <code>Buffer</code> objects. Setting an encoding causes the stream data to be returned as strings of the specified encoding rather than as <code>Buffer</code> objects. For instance, calling <code>readable.setEncoding('utf8')</code> will cause the output data to be interpreted as UTF-8 data, and passed as strings. Calling <code>readable.setEncoding('hex')</code> will cause the data to be encoded in hexadecimal string format.</p> <p>The <code>Readable</code> stream will properly handle multi-byte characters delivered through the stream that would otherwise become improperly decoded if simply pulled from the stream as <code>Buffer</code> objects.</p> <pre><code class="language-js">const readable = getReadableStreamSomehow(); readable.setEncoding('utf8'); readable.on('data', (chunk) => { assert.equal(typeof chunk, 'string'); console.log('Got %d characters of string data:', chunk.length); }); </code></pre> <h5>readable.unpipe([destination])<span><a class="mark" href="#stream_readable_unpipe_destination" id="stream_readable_unpipe_destination">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><code>destination</code> <a href="#stream_class_stream_writable" class="type"><stream.Writable></a> Optional specific stream to unpipe</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>The <code>readable.unpipe()</code> method detaches a <code>Writable</code> stream previously attached using the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method.</p> <p>If the <code>destination</code> is not specified, then <em>all</em> pipes are detached.</p> <p>If the <code>destination</code> is specified, but no pipe is set up for it, then the method does nothing.</p> <pre><code class="language-js">const fs = require('fs'); const readable = getReadableStreamSomehow(); const writable = fs.createWriteStream('file.txt'); // All the data from readable goes into 'file.txt', // but only for the first second readable.pipe(writable); setTimeout(() => { console.log('Stop writing to file.txt.'); readable.unpipe(writable); console.log('Manually close the file stream.'); writable.end(); }, 1000); </code></pre> <h5>readable.unshift(chunk)<span><a class="mark" href="#stream_readable_unshift_chunk" id="stream_readable_unshift_chunk">#</a></span></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> <tr><td>v0.9.11</td> <td><p><span>Added in: v0.9.11</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>chunk</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Chunk of data to unshift onto the read queue. For streams not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or <code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value other than <code>null</code>.</li> </ul> <p>The <code>readable.unshift()</code> method pushes a chunk of data back into the internal buffer. This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party.</p> <p>The <code>stream.unshift(chunk)</code> method cannot be called after the <a href="#stream_event_end"><code>'end'</code></a> event has been emitted or a runtime error will be thrown.</p> <p>Developers using <code>stream.unshift()</code> often should consider switching to use of a <a href="#stream_class_stream_transform"><code>Transform</code></a> stream instead. See the <a href="#stream_api_for_stream_implementers">API for Stream Implementers</a> section for more information.</p> <pre><code class="language-js">// Pull off a header delimited by \n\n // use unshift() if we get too much // Call the callback with (error, header, stream) const { StringDecoder } = require('string_decoder'); function parseHeader(stream, callback) { stream.on('error', callback); stream.on('readable', onReadable); const decoder = new StringDecoder('utf8'); let header = ''; function onReadable() { let chunk; while (null !== (chunk = stream.read())) { const str = decoder.write(chunk); if (str.match(/\n\n/)) { // found the header boundary const split = str.split(/\n\n/); header += split.shift(); const remaining = split.join('\n\n'); const buf = Buffer.from(remaining, 'utf8'); stream.removeListener('error', callback); // remove the 'readable' listener before unshifting stream.removeListener('readable', onReadable); if (buf.length) stream.unshift(buf); // now the body of the message can be read from the stream. callback(null, header, stream); } else { // still reading the header. header += str; } } } } </code></pre> <p>Unlike <a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>, <code>stream.unshift(chunk)</code> will not end the reading process by resetting the internal reading state of the stream. This can cause unexpected results if <code>readable.unshift()</code> is called during a read (i.e. from within a <a href="#stream_readable_read_size_1"><code>stream._read()</code></a> implementation on a custom stream). Following the call to <code>readable.unshift()</code> with an immediate <a href="#stream_readable_push_chunk_encoding"><code>stream.push('')</code></a> will reset the reading state appropriately, however it is best to simply avoid calling <code>readable.unshift()</code> while in the process of performing a read.</p> <h5>readable.wrap(stream)<span><a class="mark" href="#stream_readable_wrap_stream" id="stream_readable_wrap_stream">#</a></span></h5> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><code>stream</code> <a href="#stream_stream" class="type"><Stream></a> An "old style" readable stream</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a></li> </ul> <p>Prior to Node.js 0.10, streams did not implement the entire <code>stream</code> module API as it is currently defined. (See <a href="#stream_compatibility_with_older_node_js_versions">Compatibility</a> for more information.)</p> <p>When using an older Node.js library that emits <a href="#stream_event_data"><code>'data'</code></a> events and has a <a href="#stream_readable_pause"><code>stream.pause()</code></a> method that is advisory only, the <code>readable.wrap()</code> method can be used to create a <a href="#stream_class_stream_readable"><code>Readable</code></a> stream that uses the old stream as its data source.</p> <p>It will rarely be necessary to use <code>readable.wrap()</code> but the method has been provided as a convenience for interacting with older Node.js applications and libraries.</p> <pre><code class="language-js">const { OldReader } = require('./old-api-module.js'); const { Readable } = require('stream'); const oreader = new OldReader(); const myReader = new Readable().wrap(oreader); myReader.on('readable', () => { myReader.read(); // etc. }); </code></pre> <h5>readable[Symbol.asyncIterator]()<span><a class="mark" href="#stream_readable_symbol_asynciterator" id="stream_readable_symbol_asynciterator">#</a></span></h5> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.17.0</td> <td><p>Symbol.asyncIterator support is no longer experimental.</p></td></tr> <tr><td>v10.0.0</td> <td><p><span>Added in: v10.0.0</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <ul> <li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type"><AsyncIterator></a> to fully consume the stream.</li> </ul> <pre><code class="language-js">const fs = require('fs'); async function print(readable) { readable.setEncoding('utf8'); let data = ''; for await (const k of readable) { data += k; } console.log(data); } print(fs.createReadStream('file')).catch(console.log); </code></pre> <p>If the loop terminates with a <code>break</code> or a <code>throw</code>, the stream will be destroyed. In other terms, iterating over a stream will consume the stream fully. The stream will be read in chunks of size equal to the <code>highWaterMark</code> option. In the code example above, data will be in a single chunk if the file has less then 64kb of data because no <code>highWaterMark</code> option is provided to <a href="#fs_fs_createreadstream_path_options"><code>fs.createReadStream()</code></a>.</p> <h3>Duplex and Transform Streams<span><a class="mark" href="#stream_duplex_and_transform_streams" id="stream_duplex_and_transform_streams">#</a></span></h3> <h4>Class: stream.Duplex<span><a class="mark" href="#stream_class_stream_duplex" id="stream_class_stream_duplex">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.8.0</td> <td><p>Instances of <code>Duplex</code> now return <code>true</code> when checking <code>instanceof stream.Writable</code>.</p></td></tr> <tr><td>v0.9.4</td> <td><p><span>Added in: v0.9.4</span></p></td></tr> </tbody></table> </details> </div> <p>Duplex streams are streams that implement both the <a href="#stream_class_stream_readable"><code>Readable</code></a> and <a href="#stream_class_stream_writable"><code>Writable</code></a> interfaces.</p> <p>Examples of <code>Duplex</code> streams include:</p> <ul> <li><a href="#net_class_net_socket">TCP sockets</a></li> <li><a href="zlib.html">zlib streams</a></li> <li><a href="crypto.html">crypto streams</a></li> </ul> <h4>Class: stream.Transform<span><a class="mark" href="#stream_class_stream_transform" id="stream_class_stream_transform">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <p>Transform streams are <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams where the output is in some way related to the input. Like all <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams, <code>Transform</code> streams implement both the <a href="#stream_class_stream_readable"><code>Readable</code></a> and <a href="#stream_class_stream_writable"><code>Writable</code></a> interfaces.</p> <p>Examples of <code>Transform</code> streams include:</p> <ul> <li><a href="zlib.html">zlib streams</a></li> <li><a href="crypto.html">crypto streams</a></li> </ul> <h5>transform.destroy([error])<span><a class="mark" href="#stream_transform_destroy_error" id="stream_transform_destroy_error">#</a></span></h5> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>Destroy the stream, and emit <code>'error'</code>. After this call, the transform stream would release any internal resources. Implementors should not override this method, but instead implement <a href="#stream_readable_destroy_err_callback"><code>readable._destroy()</code></a>. The default implementation of <code>_destroy()</code> for <code>Transform</code> also emit <code>'close'</code>.</p> <h3>stream.finished(stream, callback)<span><a class="mark" href="#stream_stream_finished_stream_callback" id="stream_stream_finished_stream_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>stream</code> <a href="#stream_stream" class="type"><Stream></a> A readable and/or writable stream.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that takes an optional error argument.</li> </ul> <p>A function to get notified when a stream is no longer readable, writable or has experienced an error or a premature close event.</p> <pre><code class="language-js">const { finished } = require('stream'); const rs = fs.createReadStream('archive.tar'); finished(rs, (err) => { if (err) { console.error('Stream failed.', err); } else { console.log('Stream is done reading.'); } }); rs.resume(); // drain the stream </code></pre> <p>Especially useful in error handling scenarios where a stream is destroyed prematurely (like an aborted HTTP request), and will not emit <code>'end'</code> or <code>'finish'</code>.</p> <p>The <code>finished</code> API is promisify-able as well;</p> <pre><code class="language-js">const finished = util.promisify(stream.finished); const rs = fs.createReadStream('archive.tar'); async function run() { await finished(rs); console.log('Stream is done reading.'); } run().catch(console.error); rs.resume(); // drain the stream </code></pre> <h3>stream.pipeline(...streams[, callback])<span><a class="mark" href="#stream_stream_pipeline_streams_callback" id="stream_stream_pipeline_streams_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>...streams</code> <a href="#stream_stream" class="type"><Stream></a> Two or more streams to pipe between.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that takes an optional error argument.</li> </ul> <p>A module method to pipe between streams forwarding errors and properly cleaning up and provide a callback when the pipeline is complete.</p> <pre><code class="language-js">const { pipeline } = require('stream'); const fs = require('fs'); const zlib = require('zlib'); // Use the pipeline API to easily pipe a series of streams // together and get notified when the pipeline is fully done. // A pipeline to gzip a potentially huge tar file efficiently: pipeline( fs.createReadStream('archive.tar'), zlib.createGzip(), fs.createWriteStream('archive.tar.gz'), (err) => { if (err) { console.error('Pipeline failed.', err); } else { console.log('Pipeline succeeded.'); } } ); </code></pre> <p>The <code>pipeline</code> API is promisify-able as well:</p> <pre><code class="language-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('Pipeline succeeded.'); } run().catch(console.error); </code></pre> <h3>Readable.from(iterable, [options])<span><a class="mark" href="#stream_readable_from_iterable_options" id="stream_readable_from_iterable_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v12.3.0, v10.17.0</span> </div> <ul> <li><code>iterable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> Object implementing the <code>Symbol.asyncIterator</code> or <code>Symbol.iterator</code> iterable protocol.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Options provided to <code>new stream.Readable([options])</code>. By default, <code>Readable.from()</code> will set <code>options.objectMode</code> to <code>true</code>, unless this is explicitly opted out by setting <code>options.objectMode</code> to <code>false</code>.</li> </ul> <p>A utility method for creating Readable Streams out of iterators.</p> <pre><code class="language-js">const { Readable } = require('stream'); async function * generate() { yield 'hello'; yield 'streams'; } const readable = Readable.from(generate()); readable.on('data', (chunk) => { console.log(chunk); }); </code></pre> <h2>API for Stream Implementers<span><a class="mark" href="#stream_api_for_stream_implementers" id="stream_api_for_stream_implementers">#</a></span></h2> <p>The <code>stream</code> module API has been designed to make it possible to easily implement streams using JavaScript's prototypal inheritance model.</p> <p>First, a stream developer would declare a new JavaScript class that extends one of the four basic stream classes (<code>stream.Writable</code>, <code>stream.Readable</code>, <code>stream.Duplex</code>, or <code>stream.Transform</code>), making sure they call the appropriate parent class constructor:</p> <!-- eslint-disable no-useless-constructor --> <pre><code class="language-js">const { Writable } = require('stream'); class MyWritable extends Writable { constructor(options) { super(options); // ... } } </code></pre> <p>The new stream class must then implement one or more specific methods, depending on the type of stream being created, as detailed in the chart below:</p> <table><thead><tr><th>Use-case</th><th>Class</th><th>Method(s) to implement</th></tr></thead><tbody><tr><td>Reading only</td><td><a href="#stream_class_stream_readable"><code>Readable</code></a></td><td><code><a href="#stream_readable_read_size_1">_read</a></code></td></tr><tr><td>Writing only</td><td><a href="#stream_class_stream_writable"><code>Writable</code></a></td><td><code><a href="#stream_writable_write_chunk_encoding_callback_1">_write</a></code>, <code><a href="#stream_writable_writev_chunks_callback">_writev</a></code>, <code><a href="#stream_writable_final_callback">_final</a></code></td></tr><tr><td>Reading and writing</td><td><a href="#stream_class_stream_duplex"><code>Duplex</code></a></td><td><code><a href="#stream_readable_read_size_1">_read</a></code>, <code><a href="#stream_writable_write_chunk_encoding_callback_1">_write</a></code>, <code><a href="#stream_writable_writev_chunks_callback">_writev</a></code>, <code><a href="#stream_writable_final_callback">_final</a></code></td></tr><tr><td>Operate on written data, then read the result</td><td><a href="#stream_class_stream_transform"><code>Transform</code></a></td><td><code><a href="#stream_transform_transform_chunk_encoding_callback">_transform</a></code>, <code><a href="#stream_transform_flush_callback">_flush</a></code>, <code><a href="#stream_writable_final_callback">_final</a></code></td></tr></tbody></table> <p>The implementation code for a stream should <em>never</em> call the "public" methods of a stream that are intended for use by consumers (as described in the <a href="#stream_api_for_stream_consumers">API for Stream Consumers</a> section). Doing so may lead to adverse side effects in application code consuming the stream.</p> <h3>Simplified Construction<span><a class="mark" href="#stream_simplified_construction" id="stream_simplified_construction">#</a></span></h3> <div class="api_metadata"> <span>Added in: v1.2.0</span> </div> <p>For many simple cases, it is possible to construct a stream without relying on inheritance. This can be accomplished by directly creating instances of the <code>stream.Writable</code>, <code>stream.Readable</code>, <code>stream.Duplex</code> or <code>stream.Transform</code> objects and passing appropriate methods as constructor options.</p> <pre><code class="language-js">const { Writable } = require('stream'); const myWritable = new Writable({ write(chunk, encoding, callback) { // ... } }); </code></pre> <h3>Implementing a Writable Stream<span><a class="mark" href="#stream_implementing_a_writable_stream" id="stream_implementing_a_writable_stream">#</a></span></h3> <p>The <code>stream.Writable</code> class is extended to implement a <a href="#stream_class_stream_writable"><code>Writable</code></a> stream.</p> <p>Custom <code>Writable</code> streams <em>must</em> call the <code>new stream.Writable([options])</code> constructor and implement the <code>writable._write()</code> method. The <code>writable._writev()</code> method <em>may</em> also be implemented.</p> <h4>Constructor: new stream.Writable([options])<span><a class="mark" href="#stream_constructor_new_stream_writable_options" id="stream_constructor_new_stream_writable_options">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.16.0</td> <td><p>Add <code>autoDestroy</code> option to automatically <code>destroy()</code> the stream when it emits <code>'finish'</code> or errors</p></td></tr> <tr><td>v10.0.0</td> <td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy</p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Buffer level when <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> starts returning <code>false</code>. <strong>Default:</strong> <code>16384</code> (16kb), or <code>16</code> for <code>objectMode</code> streams.</li> <li><code>decodeStrings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether to encode <code>string</code>s passed to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> to <code>Buffer</code>s (with the encoding specified in the <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> call) before passing them to <a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write()</code></a>. Other types of data are not converted (i.e. <code>Buffer</code>s are not decoded into <code>string</code>s). Setting to false will prevent <code>string</code>s from being converted. <strong>Default:</strong> <code>true</code>.</li> <li><code>defaultEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The default encoding that is used when no encoding is specified as an argument to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>. <strong>Default:</strong> <code>'utf8'</code>.</li> <li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not the <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write(anyObj)</code></a> is a valid operation. When set, it becomes possible to write JavaScript values other than string, <code>Buffer</code> or <code>Uint8Array</code> if supported by the stream implementation. <strong>Default:</strong> <code>false</code>.</li> <li><code>emitClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether or not the stream should emit <code>'close'</code> after it has been destroyed. <strong>Default:</strong> <code>true</code>.</li> <li><code>write</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write()</code></a> method.</li> <li><code>writev</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#stream_writable_writev_chunks_callback"><code>stream._writev()</code></a> method.</li> <li><code>destroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#stream_writable_destroy_err_callback"><code>stream._destroy()</code></a> method.</li> <li><code>final</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#stream_writable_final_callback"><code>stream._final()</code></a> method.</li> <li><code>autoDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this stream should automatically call <code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> </ul> <!-- eslint-disable no-useless-constructor --> <pre><code class="language-js">const { Writable } = require('stream'); class MyWritable extends Writable { constructor(options) { // Calls the stream.Writable() constructor super(options); // ... } } </code></pre> <p>Or, when using pre-ES6 style constructors:</p> <pre><code class="language-js">const { Writable } = require('stream'); const util = require('util'); function MyWritable(options) { if (!(this instanceof MyWritable)) return new MyWritable(options); Writable.call(this, options); } util.inherits(MyWritable, Writable); </code></pre> <p>Or, using the Simplified Constructor approach:</p> <pre><code class="language-js">const { Writable } = require('stream'); const myWritable = new Writable({ write(chunk, encoding, callback) { // ... }, writev(chunks, callback) { // ... } }); </code></pre> <h4>writable._write(chunk, encoding, callback)<span><a class="mark" href="#stream_writable_write_chunk_encoding_callback_1" id="stream_writable_write_chunk_encoding_callback_1">#</a></span></h4> <ul> <li><code>chunk</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The <code>Buffer</code> to be written, converted from the <code>string</code> passed to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>. If the stream's <code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If the chunk is a string, then <code>encoding</code> is the character encoding of that string. If chunk is a <code>Buffer</code>, or if the stream is operating in object mode, <code>encoding</code> may be ignored.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call this function (optionally with an error argument) when processing is complete for the supplied chunk.</li> </ul> <p>All <code>Writable</code> stream implementations must provide a <a href="#stream_writable_write_chunk_encoding_callback_1"><code>writable._write()</code></a> method to send data to the underlying resource.</p> <p><a href="#stream_class_stream_transform"><code>Transform</code></a> streams provide their own implementation of the <a href="#stream_writable_write_chunk_encoding_callback_1"><code>writable._write()</code></a>.</p> <p>This function MUST NOT be called by application code directly. It should be implemented by child classes, and called by the internal <code>Writable</code> class methods only.</p> <p>The <code>callback</code> method must be called to signal either that the write completed successfully or failed with an error. The first argument passed to the <code>callback</code> must be the <code>Error</code> object if the call failed or <code>null</code> if the write succeeded.</p> <p>All calls to <code>writable.write()</code> that occur between the time <code>writable._write()</code> is called and the <code>callback</code> is called will cause the written data to be buffered. When the <code>callback</code> is invoked, the stream might emit a <a href="#stream_event_drain"><code>'drain'</code></a> event. If a stream implementation is capable of processing multiple chunks of data at once, the <code>writable._writev()</code> method should be implemented.</p> <p>If the <code>decodeStrings</code> property is explicitly set to <code>false</code> in the constructor options, then <code>chunk</code> will remain the same object that is passed to <code>.write()</code>, and may be a string rather than a <code>Buffer</code>. This is to support implementations that have an optimized handling for certain string data encodings. In that case, the <code>encoding</code> argument will indicate the character encoding of the string. Otherwise, the <code>encoding</code> argument can be safely ignored.</p> <p>The <code>writable._write()</code> method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs.</p> <h4>writable._writev(chunks, callback)<span><a class="mark" href="#stream_writable_writev_chunks_callback" id="stream_writable_writev_chunks_callback">#</a></span></h4> <ul> <li><code>chunks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> The chunks to be written. Each chunk has following format: <code>{ chunk: ..., encoding: ... }</code>.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function (optionally with an error argument) to be invoked when processing is complete for the supplied chunks.</li> </ul> <p>This function MUST NOT be called by application code directly. It should be implemented by child classes, and called by the internal <code>Writable</code> class methods only.</p> <p>The <code>writable._writev()</code> method may be implemented in addition to <code>writable._write()</code> in stream implementations that are capable of processing multiple chunks of data at once. If implemented, the method will be called with all chunks of data currently buffered in the write queue.</p> <p>The <code>writable._writev()</code> method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs.</p> <h4>writable._destroy(err, callback)<span><a class="mark" href="#stream_writable_destroy_err_callback" id="stream_writable_destroy_err_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> A possible error.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that takes an optional error argument.</li> </ul> <p>The <code>_destroy()</code> method is called by <a href="#stream_writable_destroy_error"><code>writable.destroy()</code></a>. It can be overridden by child classes but it <strong>must not</strong> be called directly.</p> <h4>writable._final(callback)<span><a class="mark" href="#stream_writable_final_callback" id="stream_writable_final_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Call this function (optionally with an error argument) when finished writing any remaining data.</li> </ul> <p>The <code>_final()</code> method <strong>must not</strong> be called directly. It may be implemented by child classes, and if so, will be called by the internal <code>Writable</code> class methods only.</p> <p>This optional function will be called before the stream closes, delaying the <code>'finish'</code> event until <code>callback</code> is called. This is useful to close resources or write buffered data before a stream ends.</p> <h4>Errors While Writing<span><a class="mark" href="#stream_errors_while_writing" id="stream_errors_while_writing">#</a></span></h4> <p>It is recommended that errors occurring during the processing of the <code>writable._write()</code> and <code>writable._writev()</code> methods are reported by invoking the callback and passing the error as the first argument. This will cause an <code>'error'</code> event to be emitted by the <code>Writable</code>. Throwing an <code>Error</code> from within <code>writable._write()</code> can result in unexpected and inconsistent behavior depending on how the stream is being used. Using the callback ensures consistent and predictable handling of errors.</p> <p>If a <code>Readable</code> stream pipes into a <code>Writable</code> stream when <code>Writable</code> emits an error, the <code>Readable</code> stream will be unpiped.</p> <pre><code class="language-js">const { Writable } = require('stream'); const myWritable = new Writable({ write(chunk, encoding, callback) { if (chunk.toString().indexOf('a') >= 0) { callback(new Error('chunk is invalid')); } else { callback(); } } }); </code></pre> <h4>An Example Writable Stream<span><a class="mark" href="#stream_an_example_writable_stream" id="stream_an_example_writable_stream">#</a></span></h4> <p>The following illustrates a rather simplistic (and somewhat pointless) custom <code>Writable</code> stream implementation. While this specific <code>Writable</code> stream instance is not of any real particular usefulness, the example illustrates each of the required elements of a custom <a href="#stream_class_stream_writable"><code>Writable</code></a> stream instance:</p> <pre><code class="language-js">const { Writable } = require('stream'); class MyWritable extends Writable { _write(chunk, encoding, callback) { if (chunk.toString().indexOf('a') >= 0) { callback(new Error('chunk is invalid')); } else { callback(); } } } </code></pre> <h4>Decoding buffers in a Writable Stream<span><a class="mark" href="#stream_decoding_buffers_in_a_writable_stream" id="stream_decoding_buffers_in_a_writable_stream">#</a></span></h4> <p>Decoding buffers is a common task, for instance, when using transformers whose input is a string. This is not a trivial process when using multi-byte characters encoding, such as UTF-8. The following example shows how to decode multi-byte strings using <code>StringDecoder</code> and <a href="#stream_class_stream_writable"><code>Writable</code></a>.</p> <pre><code class="language-js">const { Writable } = require('stream'); const { StringDecoder } = require('string_decoder'); class StringWritable extends Writable { constructor(options) { super(options); this._decoder = new StringDecoder(options && options.defaultEncoding); this.data = ''; } _write(chunk, encoding, callback) { if (encoding === 'buffer') { chunk = this._decoder.write(chunk); } this.data += chunk; callback(); } _final(callback) { this.data += this._decoder.end(); callback(); } } const euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from); const w = new StringWritable(); w.write('currency: '); w.write(euro[0]); w.end(euro[1]); console.log(w.data); // currency: € </code></pre> <h3>Implementing a Readable Stream<span><a class="mark" href="#stream_implementing_a_readable_stream" id="stream_implementing_a_readable_stream">#</a></span></h3> <p>The <code>stream.Readable</code> class is extended to implement a <a href="#stream_class_stream_readable"><code>Readable</code></a> stream.</p> <p>Custom <code>Readable</code> streams <em>must</em> call the <code>new stream.Readable([options])</code> constructor and implement the <code>readable._read()</code> method.</p> <h4>new stream.Readable([options])<span><a class="mark" href="#stream_new_stream_readable_options" id="stream_new_stream_readable_options">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.16.0</td> <td><p>Add <code>autoDestroy</code> option to automatically <code>destroy()</code> the stream when it emits <code>'end'</code> or errors</p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum <a href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding">number of bytes</a> to store in the internal buffer before ceasing to read from the underlying resource. <strong>Default:</strong> <code>16384</code> (16kb), or <code>16</code> for <code>objectMode</code> streams.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If specified, then buffers will be decoded to strings using the specified encoding. <strong>Default:</strong> <code>null</code>.</li> <li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this stream should behave as a stream of objects. Meaning that <a href="#stream_readable_read_size"><code>stream.read(n)</code></a> returns a single value instead of a <code>Buffer</code> of size <code>n</code>. <strong>Default:</strong> <code>false</code>.</li> <li><code>read</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#stream_readable_read_size_1"><code>stream._read()</code></a> method.</li> <li><code>destroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#stream_readable_destroy_err_callback"><code>stream._destroy()</code></a> method.</li> <li><code>autoDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Whether this stream should automatically call <code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> </ul> <!-- eslint-disable no-useless-constructor --> <pre><code class="language-js">const { Readable } = require('stream'); class MyReadable extends Readable { constructor(options) { // Calls the stream.Readable(options) constructor super(options); // ... } } </code></pre> <p>Or, when using pre-ES6 style constructors:</p> <pre><code class="language-js">const { Readable } = require('stream'); const util = require('util'); function MyReadable(options) { if (!(this instanceof MyReadable)) return new MyReadable(options); Readable.call(this, options); } util.inherits(MyReadable, Readable); </code></pre> <p>Or, using the Simplified Constructor approach:</p> <pre><code class="language-js">const { Readable } = require('stream'); const myReadable = new Readable({ read(size) { // ... } }); </code></pre> <h4>readable._read(size)<span><a class="mark" href="#stream_readable_read_size_1" id="stream_readable_read_size_1">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>call <code>_read()</code> only once per microtick</p></td></tr> <tr><td>v0.9.4</td> <td><p><span>Added in: v0.9.4</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Number of bytes to read asynchronously</li> </ul> <p>This function MUST NOT be called by application code directly. It should be implemented by child classes, and called by the internal <code>Readable</code> class methods only.</p> <p>All <code>Readable</code> stream implementations must provide an implementation of the <code>readable._read()</code> method to fetch data from the underlying resource.</p> <p>When <code>readable._read()</code> is called, if data is available from the resource, the implementation should begin pushing that data into the read queue using the <a href="#stream_readable_push_chunk_encoding"><code>this.push(dataChunk)</code></a> method. <code>_read()</code> should continue reading from the resource and pushing data until <code>readable.push()</code> returns <code>false</code>. Only when <code>_read()</code> is called again after it has stopped should it resume pushing additional data onto the queue.</p> <p>Once the <code>readable._read()</code> method has been called, it will not be called again until the <a href="#stream_readable_push_chunk_encoding"><code>readable.push()</code></a> method is called. <code>readable._read()</code> is guaranteed to be called only once within a synchronous execution, i.e. a microtick.</p> <p>The <code>size</code> argument is advisory. For implementations where a "read" is a single operation that returns data can use the <code>size</code> argument to determine how much data to fetch. Other implementations may ignore this argument and simply provide data whenever it becomes available. There is no need to "wait" until <code>size</code> bytes are available before calling <a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>.</p> <p>The <code>readable._read()</code> method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs.</p> <h4>readable._destroy(err, callback)<span><a class="mark" href="#stream_readable_destroy_err_callback" id="stream_readable_destroy_err_callback">#</a></span></h4> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> A possible error.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that takes an optional error argument.</li> </ul> <p>The <code>_destroy()</code> method is called by <a href="#stream_readable_destroy_error"><code>readable.destroy()</code></a>. It can be overridden by child classes but it <strong>must not</strong> be called directly.</p> <h4>readable.push(chunk[, encoding])<span><a class="mark" href="#stream_readable_push_chunk_encoding" id="stream_readable_push_chunk_encoding">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr> </tbody></table> </details> </div> <ul> <li><code>chunk</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Chunk of data to push into the read queue. For streams not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or <code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Encoding of string chunks. Must be a valid <code>Buffer</code> encoding, such as <code>'utf8'</code> or <code>'ascii'</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if additional chunks of data may continue to be pushed; <code>false</code> otherwise.</li> </ul> <p>When <code>chunk</code> is a <code>Buffer</code>, <code>Uint8Array</code> or <code>string</code>, the <code>chunk</code> of data will be added to the internal queue for users of the stream to consume. Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF), after which no more data can be written.</p> <p>When the <code>Readable</code> is operating in paused mode, the data added with <code>readable.push()</code> can be read out by calling the <a href="#stream_readable_read_size"><code>readable.read()</code></a> method when the <a href="#stream_event_readable"><code>'readable'</code></a> event is emitted.</p> <p>When the <code>Readable</code> is operating in flowing mode, the data added with <code>readable.push()</code> will be delivered by emitting a <code>'data'</code> event.</p> <p>The <code>readable.push()</code> method is designed to be as flexible as possible. For example, when wrapping a lower-level source that provides some form of pause/resume mechanism, and a data callback, the low-level source can be wrapped by the custom <code>Readable</code> instance:</p> <pre><code class="language-js">// source is an object with readStop() and readStart() methods, // and an `ondata` member that gets called when it has data, and // an `onend` member that gets called when the data is over. class SourceWrapper extends Readable { constructor(options) { super(options); this._source = getLowlevelSourceObject(); // Every time there's data, push it into the internal buffer. this._source.ondata = (chunk) => { // if push() returns false, then stop reading from source if (!this.push(chunk)) this._source.readStop(); }; // When the source ends, push the EOF-signaling `null` chunk this._source.onend = () => { this.push(null); }; } // _read will be called when the stream wants to pull more data in // the advisory size argument is ignored in this case. _read(size) { this._source.readStart(); } } </code></pre> <p>The <code>readable.push()</code> method is intended be called only by <code>Readable</code> implementers, and only from within the <code>readable._read()</code> method.</p> <p>For streams not operating in object mode, if the <code>chunk</code> parameter of <code>readable.push()</code> is <code>undefined</code>, it will be treated as empty string or buffer. See <a href="#stream_readable_push"><code>readable.push('')</code></a> for more information.</p> <h4>Errors While Reading<span><a class="mark" href="#stream_errors_while_reading" id="stream_errors_while_reading">#</a></span></h4> <p>It is recommended that errors occurring during the processing of the <code>readable._read()</code> method are emitted using the <code>'error'</code> event rather than being thrown. Throwing an <code>Error</code> from within <code>readable._read()</code> can result in unexpected and inconsistent behavior depending on whether the stream is operating in flowing or paused mode. Using the <code>'error'</code> event ensures consistent and predictable handling of errors.</p> <!-- eslint-disable no-useless-return --> <pre><code class="language-js">const { Readable } = require('stream'); const myReadable = new Readable({ read(size) { if (checkSomeErrorCondition()) { process.nextTick(() => this.emit('error', err)); return; } // do some work } }); </code></pre> <h4>An Example Counting Stream<span><a class="mark" href="#stream_an_example_counting_stream" id="stream_an_example_counting_stream">#</a></span></h4> <p>The following is a basic example of a <code>Readable</code> stream that emits the numerals from 1 to 1,000,000 in ascending order, and then ends.</p> <pre><code class="language-js">const { Readable } = require('stream'); class Counter extends Readable { constructor(opt) { super(opt); this._max = 1000000; this._index = 1; } _read() { const i = this._index++; if (i > this._max) this.push(null); else { const str = String(i); const buf = Buffer.from(str, 'ascii'); this.push(buf); } } } </code></pre> <h3>Implementing a Duplex Stream<span><a class="mark" href="#stream_implementing_a_duplex_stream" id="stream_implementing_a_duplex_stream">#</a></span></h3> <p>A <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream is one that implements both <a href="#stream_class_stream_readable"><code>Readable</code></a> and <a href="#stream_class_stream_writable"><code>Writable</code></a>, such as a TCP socket connection.</p> <p>Because JavaScript does not have support for multiple inheritance, the <code>stream.Duplex</code> class is extended to implement a <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream (as opposed to extending the <code>stream.Readable</code> <em>and</em> <code>stream.Writable</code> classes).</p> <p>The <code>stream.Duplex</code> class prototypically inherits from <code>stream.Readable</code> and parasitically from <code>stream.Writable</code>, but <code>instanceof</code> will work properly for both base classes due to overriding <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance"><code>Symbol.hasInstance</code></a> on <code>stream.Writable</code>.</p> <p>Custom <code>Duplex</code> streams <em>must</em> call the <code>new stream.Duplex([options])</code> constructor and implement <em>both</em> the <code>readable._read()</code> and <code>writable._write()</code> methods.</p> <h4>new stream.Duplex(options)<span><a class="mark" href="#stream_new_stream_duplex_options" id="stream_new_stream_duplex_options">#</a></span></h4> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.4.0</td> <td><p>The <code>readableHighWaterMark</code> and <code>writableHighWaterMark</code> options are supported now.</p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Passed to both <code>Writable</code> and <code>Readable</code> constructors. Also has the following fields:</p> <ul> <li><code>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to <code>false</code>, then the stream will automatically end the writable side when the readable side ends. <strong>Default:</strong> <code>true</code>.</li> <li><code>readableObjectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Sets <code>objectMode</code> for readable side of the stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li> <li><code>writableObjectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Sets <code>objectMode</code> for writable side of the stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li> <li><code>readableHighWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets <code>highWaterMark</code> for the readable side of the stream. Has no effect if <code>highWaterMark</code> is provided.</li> <li><code>writableHighWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Sets <code>highWaterMark</code> for the writable side of the stream. Has no effect if <code>highWaterMark</code> is provided.</li> </ul> </li> </ul> <!-- eslint-disable no-useless-constructor --> <pre><code class="language-js">const { Duplex } = require('stream'); class MyDuplex extends Duplex { constructor(options) { super(options); // ... } } </code></pre> <p>Or, when using pre-ES6 style constructors:</p> <pre><code class="language-js">const { Duplex } = require('stream'); const util = require('util'); function MyDuplex(options) { if (!(this instanceof MyDuplex)) return new MyDuplex(options); Duplex.call(this, options); } util.inherits(MyDuplex, Duplex); </code></pre> <p>Or, using the Simplified Constructor approach:</p> <pre><code class="language-js">const { Duplex } = require('stream'); const myDuplex = new Duplex({ read(size) { // ... }, write(chunk, encoding, callback) { // ... } }); </code></pre> <h4>An Example Duplex Stream<span><a class="mark" href="#stream_an_example_duplex_stream" id="stream_an_example_duplex_stream">#</a></span></h4> <p>The following illustrates a simple example of a <code>Duplex</code> stream that wraps a hypothetical lower-level source object to which data can be written, and from which data can be read, albeit using an API that is not compatible with Node.js streams. The following illustrates a simple example of a <code>Duplex</code> stream that buffers incoming written data via the <a href="#stream_class_stream_writable"><code>Writable</code></a> interface that is read back out via the <a href="#stream_class_stream_readable"><code>Readable</code></a> interface.</p> <pre><code class="language-js">const { Duplex } = require('stream'); const kSource = Symbol('source'); class MyDuplex extends Duplex { constructor(source, options) { super(options); this[kSource] = source; } _write(chunk, encoding, callback) { // The underlying source only deals with strings if (Buffer.isBuffer(chunk)) chunk = chunk.toString(); this[kSource].writeSomeData(chunk); callback(); } _read(size) { this[kSource].fetchSomeData(size, (data, encoding) => { this.push(Buffer.from(data, encoding)); }); } } </code></pre> <p>The most important aspect of a <code>Duplex</code> stream is that the <code>Readable</code> and <code>Writable</code> sides operate independently of one another despite co-existing within a single object instance.</p> <h4>Object Mode Duplex Streams<span><a class="mark" href="#stream_object_mode_duplex_streams" id="stream_object_mode_duplex_streams">#</a></span></h4> <p>For <code>Duplex</code> streams, <code>objectMode</code> can be set exclusively for either the <code>Readable</code> or <code>Writable</code> side using the <code>readableObjectMode</code> and <code>writableObjectMode</code> options respectively.</p> <p>In the following example, for instance, a new <code>Transform</code> stream (which is a type of <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream) is created that has an object mode <code>Writable</code> side that accepts JavaScript numbers that are converted to hexadecimal strings on the <code>Readable</code> side.</p> <pre><code class="language-js">const { Transform } = require('stream'); // All Transform streams are also Duplex Streams const myTransform = new Transform({ writableObjectMode: true, transform(chunk, encoding, callback) { // Coerce the chunk to a number if necessary chunk |= 0; // Transform the chunk into something else. const data = chunk.toString(16); // Push the data onto the readable queue. callback(null, '0'.repeat(data.length % 2) + data); } }); myTransform.setEncoding('ascii'); myTransform.on('data', (chunk) => console.log(chunk)); myTransform.write(1); // Prints: 01 myTransform.write(10); // Prints: 0a myTransform.write(100); // Prints: 64 </code></pre> <h3>Implementing a Transform Stream<span><a class="mark" href="#stream_implementing_a_transform_stream" id="stream_implementing_a_transform_stream">#</a></span></h3> <p>A <a href="#stream_class_stream_transform"><code>Transform</code></a> stream is a <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream where the output is computed in some way from the input. Examples include <a href="zlib.html">zlib</a> streams or <a href="crypto.html">crypto</a> streams that compress, encrypt, or decrypt data.</p> <p>There is no requirement that the output be the same size as the input, the same number of chunks, or arrive at the same time. For example, a <code>Hash</code> stream will only ever have a single chunk of output which is provided when the input is ended. A <code>zlib</code> stream will produce output that is either much smaller or much larger than its input.</p> <p>The <code>stream.Transform</code> class is extended to implement a <a href="#stream_class_stream_transform"><code>Transform</code></a> stream.</p> <p>The <code>stream.Transform</code> class prototypically inherits from <code>stream.Duplex</code> and implements its own versions of the <code>writable._write()</code> and <code>readable._read()</code> methods. Custom <code>Transform</code> implementations <em>must</em> implement the <a href="#stream_transform_transform_chunk_encoding_callback"><code>transform._transform()</code></a> method and <em>may</em> also implement the <a href="#stream_transform_flush_callback"><code>transform._flush()</code></a> method.</p> <p>Care must be taken when using <code>Transform</code> streams in that data written to the stream can cause the <code>Writable</code> side of the stream to become paused if the output on the <code>Readable</code> side is not consumed.</p> <h4>new stream.Transform([options])<span><a class="mark" href="#stream_new_stream_transform_options" id="stream_new_stream_transform_options">#</a></span></h4> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Passed to both <code>Writable</code> and <code>Readable</code> constructors. Also has the following fields:</p> <ul> <li><code>transform</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#stream_transform_transform_chunk_encoding_callback"><code>stream._transform()</code></a> method.</li> <li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Implementation for the <a href="#stream_transform_flush_callback"><code>stream._flush()</code></a> method.</li> </ul> </li> </ul> <!-- eslint-disable no-useless-constructor --> <pre><code class="language-js">const { Transform } = require('stream'); class MyTransform extends Transform { constructor(options) { super(options); // ... } } </code></pre> <p>Or, when using pre-ES6 style constructors:</p> <pre><code class="language-js">const { Transform } = require('stream'); const util = require('util'); function MyTransform(options) { if (!(this instanceof MyTransform)) return new MyTransform(options); Transform.call(this, options); } util.inherits(MyTransform, Transform); </code></pre> <p>Or, using the Simplified Constructor approach:</p> <pre><code class="language-js">const { Transform } = require('stream'); const myTransform = new Transform({ transform(chunk, encoding, callback) { // ... } }); </code></pre> <h4>Events: 'finish' and 'end'<span><a class="mark" href="#stream_events_finish_and_end" id="stream_events_finish_and_end">#</a></span></h4> <p>The <a href="#stream_event_finish"><code>'finish'</code></a> and <a href="#stream_event_end"><code>'end'</code></a> events are from the <code>stream.Writable</code> and <code>stream.Readable</code> classes, respectively. The <code>'finish'</code> event is emitted after <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> is called and all chunks have been processed by <a href="#stream_transform_transform_chunk_encoding_callback"><code>stream._transform()</code></a>. The <code>'end'</code> event is emitted after all data has been output, which occurs after the callback in <a href="#stream_transform_flush_callback"><code>transform._flush()</code></a> has been called.</p> <h4>transform._flush(callback)<span><a class="mark" href="#stream_transform_flush_callback" id="stream_transform_flush_callback">#</a></span></h4> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function (optionally with an error argument and data) to be called when remaining data has been flushed.</li> </ul> <p>This function MUST NOT be called by application code directly. It should be implemented by child classes, and called by the internal <code>Readable</code> class methods only.</p> <p>In some cases, a transform operation may need to emit an additional bit of data at the end of the stream. For example, a <code>zlib</code> compression stream will store an amount of internal state used to optimally compress the output. When the stream ends, however, that additional data needs to be flushed so that the compressed data will be complete.</p> <p>Custom <a href="#stream_class_stream_transform"><code>Transform</code></a> implementations <em>may</em> implement the <code>transform._flush()</code> method. This will be called when there is no more written data to be consumed, but before the <a href="#stream_event_end"><code>'end'</code></a> event is emitted signaling the end of the <a href="#stream_class_stream_readable"><code>Readable</code></a> stream.</p> <p>Within the <code>transform._flush()</code> implementation, the <code>readable.push()</code> method may be called zero or more times, as appropriate. The <code>callback</code> function must be called when the flush operation is complete.</p> <p>The <code>transform._flush()</code> method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs.</p> <h4>transform._transform(chunk, encoding, callback)<span><a class="mark" href="#stream_transform_transform_chunk_encoding_callback" id="stream_transform_transform_chunk_encoding_callback">#</a></span></h4> <ul> <li><code>chunk</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The <code>Buffer</code> to be transformed, converted from the <code>string</code> passed to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>. If the stream's <code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>.</li> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> If the chunk is a string, then this is the encoding type. If chunk is a buffer, then this is the special value - 'buffer', ignore it in this case.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function (optionally with an error argument and data) to be called after the supplied <code>chunk</code> has been processed.</li> </ul> <p>This function MUST NOT be called by application code directly. It should be implemented by child classes, and called by the internal <code>Readable</code> class methods only.</p> <p>All <code>Transform</code> stream implementations must provide a <code>_transform()</code> method to accept input and produce output. The <code>transform._transform()</code> implementation handles the bytes being written, computes an output, then passes that output off to the readable portion using the <code>readable.push()</code> method.</p> <p>The <code>transform.push()</code> method may be called zero or more times to generate output from a single input chunk, depending on how much is to be output as a result of the chunk.</p> <p>It is possible that no output is generated from any given chunk of input data.</p> <p>The <code>callback</code> function must be called only when the current chunk is completely consumed. The first argument passed to the <code>callback</code> must be an <code>Error</code> object if an error occurred while processing the input or <code>null</code> otherwise. If a second argument is passed to the <code>callback</code>, it will be forwarded on to the <code>readable.push()</code> method. In other words, the following are equivalent:</p> <pre><code class="language-js">transform.prototype._transform = function(data, encoding, callback) { this.push(data); callback(); }; transform.prototype._transform = function(data, encoding, callback) { callback(null, data); }; </code></pre> <p>The <code>transform._transform()</code> method is prefixed with an underscore because it is internal to the class that defines it, and should never be called directly by user programs.</p> <p><code>transform._transform()</code> is never called in parallel; streams implement a queue mechanism, and to receive the next chunk, <code>callback</code> must be called, either synchronously or asynchronously.</p> <h4>Class: stream.PassThrough<span><a class="mark" href="#stream_class_stream_passthrough" id="stream_class_stream_passthrough">#</a></span></h4> <p>The <code>stream.PassThrough</code> class is a trivial implementation of a <a href="#stream_class_stream_transform"><code>Transform</code></a> stream that simply passes the input bytes across to the output. Its purpose is primarily for examples and testing, but there are some use cases where <code>stream.PassThrough</code> is useful as a building block for novel sorts of streams.</p> <h2>Additional Notes<span><a class="mark" href="#stream_additional_notes" id="stream_additional_notes">#</a></span></h2> <h3>Streams Compatibility with Async Generators and Async Iterators<span><a class="mark" href="#stream_streams_compatibility_with_async_generators_and_async_iterators" id="stream_streams_compatibility_with_async_generators_and_async_iterators">#</a></span></h3> <p>With the support of async generators and iterators in JavaScript, async generators are effectively a first-class language-level stream construct at this point.</p> <p>Some common interop cases of using Node.js streams with async generators and async iterators are provided below.</p> <h4>Consuming Readable Streams with Async Iterators<span><a class="mark" href="#stream_consuming_readable_streams_with_async_iterators" id="stream_consuming_readable_streams_with_async_iterators">#</a></span></h4> <pre><code class="language-js">(async function() { for await (const chunk of readable) { console.log(chunk); } })(); </code></pre> <h4>Creating Readable Streams with Async Generators<span><a class="mark" href="#stream_creating_readable_streams_with_async_generators" id="stream_creating_readable_streams_with_async_generators">#</a></span></h4> <p>We can construct a Node.js Readable Stream from an asynchronous generator using the <code>Readable.from</code> utility method:</p> <pre><code class="language-js">const { Readable } = require('stream'); async function * generate() { yield 'a'; yield 'b'; yield 'c'; } const readable = Readable.from(generate()); readable.on('data', (chunk) => { console.log(chunk); }); </code></pre> <h4>Piping to Writable Streams from Async Iterators<span><a class="mark" href="#stream_piping_to_writable_streams_from_async_iterators" id="stream_piping_to_writable_streams_from_async_iterators">#</a></span></h4> <p>In the scenario of writing to a writeable stream from an async iterator, it is important to ensure the correct handling of backpressure and errors.</p> <pre><code class="language-js">const { once } = require('events'); const writeable = fs.createWriteStream('./file'); (async function() { for await (const chunk of iterator) { // Handle backpressure on write if (!writeable.write(value)) await once(writeable, 'drain'); } writeable.end(); // Ensure completion without errors await once(writeable, 'finish'); })(); </code></pre> <p>In the above, errors on the write stream would be caught and thrown by the two <code>once</code> listeners, since <code>once</code> will also handle <code>'error'</code> events.</p> <p>Alternatively the readable stream could be wrapped with <code>Readable.from</code> and then piped via <code>.pipe</code>:</p> <pre><code class="language-js">const { once } = require('events'); const writeable = fs.createWriteStream('./file'); (async function() { const readable = Readable.from(iterator); readable.pipe(writeable); // Ensure completion without errors await once(writeable, 'finish'); })(); </code></pre> <h3>Compatibility with Older Node.js Versions<span><a class="mark" href="#stream_compatibility_with_older_node_js_versions" id="stream_compatibility_with_older_node_js_versions">#</a></span></h3> <p>Prior to Node.js 0.10, the <code>Readable</code> stream interface was simpler, but also less powerful and less useful.</p> <ul> <li>Rather than waiting for calls to the <a href="#stream_readable_read_size"><code>stream.read()</code></a> method, <a href="#stream_event_data"><code>'data'</code></a> events would begin emitting immediately. Applications that would need to perform some amount of work to decide how to handle data were required to store read data into buffers so the data would not be lost.</li> <li>The <a href="#stream_readable_pause"><code>stream.pause()</code></a> method was advisory, rather than guaranteed. This meant that it was still necessary to be prepared to receive <a href="#stream_event_data"><code>'data'</code></a> events <em>even when the stream was in a paused state</em>.</li> </ul> <p>In Node.js 0.10, the <a href="#stream_class_stream_readable"><code>Readable</code></a> class was added. For backward compatibility with older Node.js programs, <code>Readable</code> streams switch into "flowing mode" when a <a href="#stream_event_data"><code>'data'</code></a> event handler is added, or when the <a href="#stream_readable_resume"><code>stream.resume()</code></a> method is called. The effect is that, even when not using the new <a href="#stream_readable_read_size"><code>stream.read()</code></a> method and <a href="#stream_event_readable"><code>'readable'</code></a> event, it is no longer necessary to worry about losing <a href="#stream_event_data"><code>'data'</code></a> chunks.</p> <p>While most applications will continue to function normally, this introduces an edge case in the following conditions:</p> <ul> <li>No <a href="#stream_event_data"><code>'data'</code></a> event listener is added.</li> <li>The <a href="#stream_readable_resume"><code>stream.resume()</code></a> method is never called.</li> <li>The stream is not piped to any writable destination.</li> </ul> <p>For example, consider the following code:</p> <pre><code class="language-js">// WARNING! BROKEN! net.createServer((socket) => { // we add an 'end' listener, but never consume the data socket.on('end', () => { // It will never get here. socket.end('The message was received but was not processed.\n'); }); }).listen(1337); </code></pre> <p>Prior to Node.js 0.10, the incoming message data would be simply discarded. However, in Node.js 0.10 and beyond, the socket remains paused forever.</p> <p>The workaround in this situation is to call the <a href="#stream_readable_resume"><code>stream.resume()</code></a> method to begin the flow of data:</p> <pre><code class="language-js">// Workaround net.createServer((socket) => { socket.on('end', () => { socket.end('The message was received but was not processed.\n'); }); // start the flow of data, discarding it. socket.resume(); }).listen(1337); </code></pre> <p>In addition to new <code>Readable</code> streams switching into flowing mode, pre-0.10 style streams can be wrapped in a <code>Readable</code> class using the <a href="#stream_readable_wrap_stream"><code>readable.wrap()</code></a> method.</p> <h3><code>readable.read(0)</code><span><a class="mark" href="#stream_readable_read_0" id="stream_readable_read_0">#</a></span></h3> <p>There are some cases where it is necessary to trigger a refresh of the underlying readable stream mechanisms, without actually consuming any data. In such cases, it is possible to call <code>readable.read(0)</code>, which will always return <code>null</code>.</p> <p>If the internal read buffer is below the <code>highWaterMark</code>, and the stream is not currently reading, then calling <code>stream.read(0)</code> will trigger a low-level <a href="#stream_readable_read_size_1"><code>stream._read()</code></a> call.</p> <p>While most applications will almost never need to do this, there are situations within Node.js where this is done, particularly in the <code>Readable</code> stream class internals.</p> <h3><code>readable.push('')</code><span><a class="mark" href="#stream_readable_push" id="stream_readable_push">#</a></span></h3> <p>Use of <code>readable.push('')</code> is not recommended.</p> <p>Pushing a zero-byte string, <code>Buffer</code> or <code>Uint8Array</code> to a stream that is not in object mode has an interesting side effect. Because it <em>is</em> a call to <a href="#stream_readable_push_chunk_encoding"><code>readable.push()</code></a>, the call will end the reading process. However, because the argument is an empty string, no data is added to the readable buffer so there is nothing for a user to consume.</p> <h3><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code><span><a class="mark" href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding" id="stream_highwatermark_discrepancy_after_calling_readable_setencoding">#</a></span></h3> <p>The use of <code>readable.setEncoding()</code> will change the behavior of how the <code>highWaterMark</code> operates in non-object mode.</p> <p>Typically, the size of the current buffer is measured against the <code>highWaterMark</code> in <em>bytes</em>. However, after <code>setEncoding()</code> is called, the comparison function will begin to measure the buffer's size in <em>characters</em>.</p> <p>This is not a problem in common cases with <code>latin1</code> or <code>ascii</code>. But it is advised to be mindful about this behavior when working with strings that could contain multi-byte characters.</p> <h1>String Decoder<span><a class="mark" href="#string_decoder_string_decoder" id="string_decoder_string_decoder">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>string_decoder</code> module provides an API for decoding <code>Buffer</code> objects into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 characters. It can be accessed using:</p> <pre><code class="language-js">const { StringDecoder } = require('string_decoder'); </code></pre> <p>The following example shows the basic use of the <code>StringDecoder</code> class.</p> <pre><code class="language-js">const { StringDecoder } = require('string_decoder'); const decoder = new StringDecoder('utf8'); const cent = Buffer.from([0xC2, 0xA2]); console.log(decoder.write(cent)); const euro = Buffer.from([0xE2, 0x82, 0xAC]); console.log(decoder.write(euro)); </code></pre> <p>When a <code>Buffer</code> instance is written to the <code>StringDecoder</code> instance, an internal buffer is used to ensure that the decoded string does not contain any incomplete multibyte characters. These are held in the buffer until the next call to <code>stringDecoder.write()</code> or until <code>stringDecoder.end()</code> is called.</p> <p>In the following example, the three UTF-8 encoded bytes of the European Euro symbol (<code>€</code>) are written over three separate operations:</p> <pre><code class="language-js">const { StringDecoder } = require('string_decoder'); const decoder = new StringDecoder('utf8'); decoder.write(Buffer.from([0xE2])); decoder.write(Buffer.from([0x82])); console.log(decoder.end(Buffer.from([0xAC]))); </code></pre> <h2>Class: StringDecoder<span><a class="mark" href="#string_decoder_class_stringdecoder" id="string_decoder_class_stringdecoder">#</a></span></h2> <h3>new StringDecoder([encoding])<span><a class="mark" href="#string_decoder_new_stringdecoder_encoding" id="string_decoder_new_stringdecoder_encoding">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The character encoding the <code>StringDecoder</code> will use. <strong>Default:</strong> <code>'utf8'</code>.</li> </ul> <p>Creates a new <code>StringDecoder</code> instance.</p> <h3>stringDecoder.end([buffer])<span><a class="mark" href="#string_decoder_stringdecoder_end_buffer" id="string_decoder_stringdecoder_end_buffer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.3</span> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> A <code>Buffer</code>, or <code>TypedArray</code>, or <code>DataView</code> containing the bytes to decode.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns any remaining input stored in the internal buffer as a string. Bytes representing incomplete UTF-8 and UTF-16 characters will be replaced with substitution characters appropriate for the character encoding.</p> <p>If the <code>buffer</code> argument is provided, one final call to <code>stringDecoder.write()</code> is performed before returning the remaining input.</p> <h3>stringDecoder.write(buffer)<span><a class="mark" href="#string_decoder_stringdecoder_write_buffer" id="string_decoder_stringdecoder_write_buffer">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>Each invalid character is now replaced by a single replacement character instead of one for each individual byte.</p></td></tr> <tr><td>v0.1.99</td> <td><p><span>Added in: v0.1.99</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> A <code>Buffer</code>, or <code>TypedArray</code>, or <code>DataView</code> containing the bytes to decode.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns a decoded string, ensuring that any incomplete multibyte characters at the end of the <code>Buffer</code>, or <code>TypedArray</code>, or <code>DataView</code> are omitted from the returned string and stored in an internal buffer for the next call to <code>stringDecoder.write()</code> or <code>stringDecoder.end()</code>.</p> <h1>Timers<span><a class="mark" href="#timers_timers" id="timers_timers">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>timer</code> module exposes a global API for scheduling functions to be called at some future period of time. Because the timer functions are globals, there is no need to call <code>require('timers')</code> to use the API.</p> <p>The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around <a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/">the Node.js Event Loop</a>.</p> <h2>Class: Immediate<span><a class="mark" href="#timers_class_immediate" id="timers_class_immediate">#</a></span></h2> <p>This object is created internally and is returned from <a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a>. It can be passed to <a href="#timers_clearimmediate_immediate"><code>clearImmediate()</code></a> in order to cancel the scheduled actions.</p> <p>By default, when an immediate is scheduled, the Node.js event loop will continue running as long as the immediate is active. The <code>Immediate</code> object returned by <a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a> exports both <code>immediate.ref()</code> and <code>immediate.unref()</code> functions that can be used to control this default behavior.</p> <h3>immediate.ref()<span><a class="mark" href="#timers_immediate_ref" id="timers_immediate_ref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.7.0</span> </div> <ul> <li>Returns: <a href="#timers_class_immediate" class="type"><Immediate></a> a reference to <code>immediate</code></li> </ul> <p>When called, requests that the Node.js event loop <em>not</em> exit so long as the <code>Immediate</code> is active. Calling <code>immediate.ref()</code> multiple times will have no effect.</p> <p>By default, all <code>Immediate</code> objects are "ref'ed", making it normally unnecessary to call <code>immediate.ref()</code> unless <code>immediate.unref()</code> had been called previously.</p> <h3>immediate.unref()<span><a class="mark" href="#timers_immediate_unref" id="timers_immediate_unref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.7.0</span> </div> <ul> <li>Returns: <a href="#timers_class_immediate" class="type"><Immediate></a> a reference to <code>immediate</code></li> </ul> <p>When called, the active <code>Immediate</code> object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the <code>Immediate</code> object's callback is invoked. Calling <code>immediate.unref()</code> multiple times will have no effect.</p> <h2>Class: Timeout<span><a class="mark" href="#timers_class_timeout" id="timers_class_timeout">#</a></span></h2> <p>This object is created internally and is returned from <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a> and <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>. It can be passed to either <a href="#timers_cleartimeout_timeout"><code>clearTimeout()</code></a> or <a href="#timers_clearinterval_timeout"><code>clearInterval()</code></a> in order to cancel the scheduled actions.</p> <p>By default, when a timer is scheduled using either <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a> or <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>, the Node.js event loop will continue running as long as the timer is active. Each of the <code>Timeout</code> objects returned by these functions export both <code>timeout.ref()</code> and <code>timeout.unref()</code> functions that can be used to control this default behavior.</p> <h3>timeout.ref()<span><a class="mark" href="#timers_timeout_ref" id="timers_timeout_ref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <ul> <li>Returns: <a href="#timers_class_timeout" class="type"><Timeout></a> a reference to <code>timeout</code></li> </ul> <p>When called, requests that the Node.js event loop <em>not</em> exit so long as the <code>Timeout</code> is active. Calling <code>timeout.ref()</code> multiple times will have no effect.</p> <p>By default, all <code>Timeout</code> objects are "ref'ed", making it normally unnecessary to call <code>timeout.ref()</code> unless <code>timeout.unref()</code> had been called previously.</p> <h3>timeout.refresh()<span><a class="mark" href="#timers_timeout_refresh" id="timers_timeout_refresh">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.2.0</span> </div> <ul> <li>Returns: <a href="#timers_class_timeout" class="type"><Timeout></a> a reference to <code>timeout</code></li> </ul> <p>Sets the timer's start time to the current time, and reschedules the timer to call its callback at the previously specified duration adjusted to the current time. This is useful for refreshing a timer without allocating a new JavaScript object.</p> <p>Using this on a timer that has already called its callback will reactivate the timer.</p> <h3>timeout.unref()<span><a class="mark" href="#timers_timeout_unref" id="timers_timeout_unref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <ul> <li>Returns: <a href="#timers_class_timeout" class="type"><Timeout></a> a reference to <code>timeout</code></li> </ul> <p>When called, the active <code>Timeout</code> object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the <code>Timeout</code> object's callback is invoked. Calling <code>timeout.unref()</code> multiple times will have no effect.</p> <p>Calling <code>timeout.unref()</code> creates an internal timer that will wake the Node.js event loop. Creating too many of these can adversely impact performance of the Node.js application.</p> <h2>Scheduling Timers<span><a class="mark" href="#timers_scheduling_timers" id="timers_scheduling_timers">#</a></span></h2> <p>A timer in Node.js is an internal construct that calls a given function after a certain period of time. When a timer's function is called varies depending on which method was used to create the timer and what other work the Node.js event loop is doing.</p> <h3>setImmediate(callback[, ...args])<span><a class="mark" href="#timers_setimmediate_callback_args" id="timers_setimmediate_callback_args">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to call at the end of this turn of <a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/">the Node.js Event Loop</a></li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass when the <code>callback</code> is called.</li> <li>Returns: <a href="#timers_class_immediate" class="type"><Immediate></a> for use with <a href="#timers_clearimmediate_immediate"><code>clearImmediate()</code></a></li> </ul> <p>Schedules the "immediate" execution of the <code>callback</code> after I/O events' callbacks.</p> <p>When multiple calls to <code>setImmediate()</code> are made, the <code>callback</code> functions are queued for execution in the order in which they are created. The entire callback queue is processed every event loop iteration. If an immediate timer is queued from inside an executing callback, that timer will not be triggered until the next event loop iteration.</p> <p>If <code>callback</code> is not a function, a <a href="#errors_class_typeerror"><code>TypeError</code></a> will be thrown.</p> <p>This method has a custom variant for promises that is available using <a href="#util_util_promisify_original"><code>util.promisify()</code></a>:</p> <pre><code class="language-js">const util = require('util'); const setImmediatePromise = util.promisify(setImmediate); setImmediatePromise('foobar').then((value) => { // value === 'foobar' (passing values is optional) // This is executed after all I/O callbacks. }); // or with async function async function timerExample() { console.log('Before I/O callbacks'); await setImmediatePromise(); console.log('After I/O callbacks'); } timerExample(); </code></pre> <h3>setInterval(callback, delay[, ...args])<span><a class="mark" href="#timers_setinterval_callback_delay_args" id="timers_setinterval_callback_delay_args">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.0.1</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to call when the timer elapses.</li> <li><code>delay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds to wait before calling the <code>callback</code>.</li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass when the <code>callback</code> is called.</li> <li>Returns: <a href="#timers_class_timeout" class="type"><Timeout></a> for use with <a href="#timers_clearinterval_timeout"><code>clearInterval()</code></a></li> </ul> <p>Schedules repeated execution of <code>callback</code> every <code>delay</code> milliseconds.</p> <p>When <code>delay</code> is larger than <code>2147483647</code> or less than <code>1</code>, the <code>delay</code> will be set to <code>1</code>.</p> <p>If <code>callback</code> is not a function, a <a href="#errors_class_typeerror"><code>TypeError</code></a> will be thrown.</p> <h3>setTimeout(callback, delay[, ...args])<span><a class="mark" href="#timers_settimeout_callback_delay_args" id="timers_settimeout_callback_delay_args">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.0.1</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function to call when the timer elapses.</li> <li><code>delay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of milliseconds to wait before calling the <code>callback</code>.</li> <li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Optional arguments to pass when the <code>callback</code> is called.</li> <li>Returns: <a href="#timers_class_timeout" class="type"><Timeout></a> for use with <a href="#timers_cleartimeout_timeout"><code>clearTimeout()</code></a></li> </ul> <p>Schedules execution of a one-time <code>callback</code> after <code>delay</code> milliseconds.</p> <p>The <code>callback</code> will likely not be invoked in precisely <code>delay</code> milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering. The callback will be called as close as possible to the time specified.</p> <p>When <code>delay</code> is larger than <code>2147483647</code> or less than <code>1</code>, the <code>delay</code> will be set to <code>1</code>.</p> <p>If <code>callback</code> is not a function, a <a href="#errors_class_typeerror"><code>TypeError</code></a> will be thrown.</p> <p>This method has a custom variant for promises that is available using <a href="#util_util_promisify_original"><code>util.promisify()</code></a>:</p> <pre><code class="language-js">const util = require('util'); const setTimeoutPromise = util.promisify(setTimeout); setTimeoutPromise(40, 'foobar').then((value) => { // value === 'foobar' (passing values is optional) // This is executed after about 40 milliseconds. }); </code></pre> <h2>Cancelling Timers<span><a class="mark" href="#timers_cancelling_timers" id="timers_cancelling_timers">#</a></span></h2> <p>The <a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a>, <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>, and <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a> methods each return objects that represent the scheduled timers. These can be used to cancel the timer and prevent it from triggering.</p> <p>It is not possible to cancel timers that were created using the promisified variants of <a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a>, <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a>.</p> <h3>clearImmediate(immediate)<span><a class="mark" href="#timers_clearimmediate_immediate" id="timers_clearimmediate_immediate">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <ul> <li><code>immediate</code> <a href="#timers_class_immediate" class="type"><Immediate></a> An <code>Immediate</code> object as returned by <a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a>.</li> </ul> <p>Cancels an <code>Immediate</code> object created by <a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a>.</p> <h3>clearInterval(timeout)<span><a class="mark" href="#timers_clearinterval_timeout" id="timers_clearinterval_timeout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.0.1</span> </div> <ul> <li><code>timeout</code> <a href="#timers_class_timeout" class="type"><Timeout></a> A <code>Timeout</code> object as returned by <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>.</li> </ul> <p>Cancels a <code>Timeout</code> object created by <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>.</p> <h3>clearTimeout(timeout)<span><a class="mark" href="#timers_cleartimeout_timeout" id="timers_cleartimeout_timeout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.0.1</span> </div> <ul> <li><code>timeout</code> <a href="#timers_class_timeout" class="type"><Timeout></a> A <code>Timeout</code> object as returned by <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a>.</li> </ul> <p>Cancels a <code>Timeout</code> object created by <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a>.</p> <h1>TLS (SSL)<span><a class="mark" href="#tls_tls_ssl" id="tls_tls_ssl">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>tls</code> module provides an implementation of the Transport Layer Security (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. The module can be accessed using:</p> <pre><code class="language-js">const tls = require('tls'); </code></pre> <h2>TLS/SSL Concepts<span><a class="mark" href="#tls_tls_ssl_concepts" id="tls_tls_ssl_concepts">#</a></span></h2> <p>The TLS/SSL is a public/private key infrastructure (PKI). For most common cases, each client and server must have a <em>private key</em>.</p> <p>Private keys can be generated in multiple ways. The example below illustrates use of the OpenSSL command-line interface to generate a 2048-bit RSA private key:</p> <pre><code class="language-sh">openssl genrsa -out ryans-key.pem 2048 </code></pre> <p>With TLS/SSL, all servers (and some clients) must have a <em>certificate</em>. Certificates are <em>public keys</em> that correspond to a private key, and that are digitally signed either by a Certificate Authority or by the owner of the private key (such certificates are referred to as "self-signed"). The first step to obtaining a certificate is to create a <em>Certificate Signing Request</em> (CSR) file.</p> <p>The OpenSSL command-line interface can be used to generate a CSR for a private key:</p> <pre><code class="language-sh">openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem </code></pre> <p>Once the CSR file is generated, it can either be sent to a Certificate Authority for signing or used to generate a self-signed certificate.</p> <p>Creating a self-signed certificate using the OpenSSL command-line interface is illustrated in the example below:</p> <pre><code class="language-sh">openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem </code></pre> <p>Once the certificate is generated, it can be used to generate a <code>.pfx</code> or <code>.p12</code> file:</p> <pre><code class="language-sh">openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \ -certfile ca-cert.pem -out ryans.pfx </code></pre> <p>Where:</p> <ul> <li><code>in</code>: is the signed certificate</li> <li><code>inkey</code>: is the associated private key</li> <li><code>certfile</code>: is a concatenation of all Certificate Authority (CA) certs into a single file, e.g. <code>cat ca1-cert.pem ca2-cert.pem > ca-cert.pem</code></li> </ul> <h3>Perfect Forward Secrecy<span><a class="mark" href="#tls_perfect_forward_secrecy" id="tls_perfect_forward_secrecy">#</a></span></h3> <p>The term "<a href="https://en.wikipedia.org/wiki/Perfect_forward_secrecy">Forward Secrecy</a>" or "Perfect Forward Secrecy" describes a feature of key-agreement (i.e., key-exchange) methods. That is, the server and client keys are used to negotiate new temporary keys that are used specifically and only for the current communication session. Practically, this means that even if the server's private key is compromised, communication can only be decrypted by eavesdroppers if the attacker manages to obtain the key-pair specifically generated for the session.</p> <p>Perfect Forward Secrecy is achieved by randomly generating a key pair for key-agreement on every TLS/SSL handshake (in contrast to using the same key for all sessions). Methods implementing this technique are called "ephemeral".</p> <p>Currently two methods are commonly used to achieve Perfect Forward Secrecy (note the character "E" appended to the traditional abbreviations):</p> <ul> <li><a href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange">DHE</a> - An ephemeral version of the Diffie Hellman key-agreement protocol.</li> <li><a href="https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman">ECDHE</a> - An ephemeral version of the Elliptic Curve Diffie Hellman key-agreement protocol.</li> </ul> <p>Ephemeral methods may have some performance drawbacks, because key generation is expensive.</p> <p>To use Perfect Forward Secrecy using <code>DHE</code> with the <code>tls</code> module, it is required to generate Diffie-Hellman parameters and specify them with the <code>dhparam</code> option to <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>. The following illustrates the use of the OpenSSL command-line interface to generate such parameters:</p> <pre><code class="language-sh">openssl dhparam -outform PEM -out dhparam.pem 2048 </code></pre> <p>If using Perfect Forward Secrecy using <code>ECDHE</code>, Diffie-Hellman parameters are not required and a default ECDHE curve will be used. The <code>ecdhCurve</code> property can be used when creating a TLS Server to specify the list of names of supported curves to use, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a> for more info.</p> <h3>ALPN and SNI<span><a class="mark" href="#tls_alpn_and_sni" id="tls_alpn_and_sni">#</a></span></h3> <p>ALPN (Application-Layer Protocol Negotiation Extension) and SNI (Server Name Indication) are TLS handshake extensions:</p> <ul> <li>ALPN - Allows the use of one TLS server for multiple protocols (HTTP, HTTP/2)</li> <li>SNI - Allows the use of one TLS server for multiple hostnames with different SSL certificates.</li> </ul> <h3>Client-initiated renegotiation attack mitigation<span><a class="mark" href="#tls_client_initiated_renegotiation_attack_mitigation" id="tls_client_initiated_renegotiation_attack_mitigation">#</a></span></h3> <p>The TLS protocol allows clients to renegotiate certain aspects of the TLS session. Unfortunately, session renegotiation requires a disproportionate amount of server-side resources, making it a potential vector for denial-of-service attacks.</p> <p>To mitigate the risk, renegotiation is limited to three times every ten minutes. An <code>'error'</code> event is emitted on the <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instance when this threshold is exceeded. The limits are configurable:</p> <ul> <li><code>tls.CLIENT_RENEG_LIMIT</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of renegotiation requests. <strong>Default:</strong> <code>3</code>.</li> <li><code>tls.CLIENT_RENEG_WINDOW</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the time renegotiation window in seconds. <strong>Default:</strong> <code>600</code> (10 minutes).</li> </ul> <p>The default renegotiation limits should not be modified without a full understanding of the implications and risks.</p> <h3>Session Resumption<span><a class="mark" href="#tls_session_resumption" id="tls_session_resumption">#</a></span></h3> <p>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).</p> <p><strong><em>Session Identifiers</em></strong> 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 <a href="https://www.ietf.org/rfc/rfc2246.txt">RFC 2246</a> for more information, page 23 and 30.</p> <p>Resumption using session identifiers is supported by most web browsers when making HTTPS requests.</p> <p>For Node.js, clients must call <a href="#tls_tlssocket_getsession"><code>tls.TLSSocket.getSession()</code></a> after the <a href="#tls_event_secureconnect"><code>'secureConnect'</code></a> event to get the session data, and provide the data to the <code>session</code> option of <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> to reuse the session. Servers must implement handlers for the <a href="#tls_event_newsession"><code>'newSession'</code></a> and <a href="#tls_event_resumesession"><code>'resumeSession'</code></a> 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.</p> <p><strong><em>Session Tickets</em></strong> 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 <a href="https://tools.ietf.org/html/rfc5077">RFC 5077</a> for more information.</p> <p>Resumption using session tickets is becoming commonly supported by many web browsers when making HTTPS requests.</p> <p>For Node.js, clients use the same APIs for resumption with session identifiers as for resumption with session tickets. For debugging, if <a href="#tls_tlssocket_gettlsticket"><code>tls.TLSSocket.getTLSTicket()</code></a> returns a value, the session data contains a ticket, otherwise it contains client-side session state.</p> <p>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.</p> <p>Its possible to get the ticket keys by calling <a href="#tls_server_getticketkeys"><code>server.getTicketKeys()</code></a> 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 <code>ticketKeys</code> option of <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>. The keys should be regularly regenerated and server's keys can be reset with <a href="#tls_server_setticketkeys_keys"><code>server.setTicketKeys()</code></a>.</p> <p>Session ticket keys are cryptographic keys, and they <strong><em>must be stored securely</em></strong>. 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.</p> <p>If clients advertise support for tickets, the server will send them. The server can disable tickets by supplying <code>require('constants').SSL_OP_NO_TICKET</code> in <code>secureOptions</code>.</p> <p>Both session identifiers and session tickets timeout, causing the server to create new sessions. The timeout can be configured with the <code>sessionTimeout</code> option of <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>.</p> <p>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 <code>-reconnect</code> option to <code>openssl s_client</code>, for example:</p> <pre><code class="language-sh">$ openssl s_client -connect localhost:443 -reconnect </code></pre> <p>Read through the debug output. The first connection should say "New", for example:</p> <pre><code class="language-text">New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256 </code></pre> <p>Subsequent connections should say "Reused", for example:</p> <pre><code class="language-text">Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256 </code></pre> <h2>Modifying the Default TLS Cipher suite<span><a class="mark" href="#tls_modifying_the_default_tls_cipher_suite" id="tls_modifying_the_default_tls_cipher_suite">#</a></span></h2> <p>Node.js is built with a default suite of enabled and disabled TLS ciphers. Currently, the default cipher suite is:</p> <pre><code class="language-txt">ECDHE-RSA-AES128-GCM-SHA256: ECDHE-ECDSA-AES128-GCM-SHA256: ECDHE-RSA-AES256-GCM-SHA384: ECDHE-ECDSA-AES256-GCM-SHA384: DHE-RSA-AES128-GCM-SHA256: ECDHE-RSA-AES128-SHA256: DHE-RSA-AES128-SHA256: ECDHE-RSA-AES256-SHA384: DHE-RSA-AES256-SHA384: ECDHE-RSA-AES256-SHA256: DHE-RSA-AES256-SHA256: HIGH: !aNULL: !eNULL: !EXPORT: !DES: !RC4: !MD5: !PSK: !SRP: !CAMELLIA </code></pre> <p>This default can be replaced entirely using the <a href="#cli_tls_cipher_list_list"><code>--tls-cipher-list</code></a> command line switch (directly, or via the <a href="#cli_node_options_options"><code>NODE_OPTIONS</code></a> environment variable). For instance, the following makes <code>ECDHE-RSA-AES128-GCM-SHA256:!RC4</code> the default TLS cipher suite:</p> <pre><code class="language-sh">node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4" server.js export NODE_OPTIONS=--tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4" node server.js </code></pre> <p>The default can also be replaced on a per client or server basis using the <code>ciphers</code> option from <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>, which is also available in <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>, <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>, and when creating new <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a>s.</p> <p>Consult <a href="https://www.openssl.org/docs/man1.1.0/apps/ciphers.html#CIPHER-LIST-FORMAT">OpenSSL cipher list format documentation</a> for details on the format.</p> <p>The default cipher suite included within Node.js has been carefully selected to reflect current security best practices and risk mitigation. Changing the default cipher suite can have a significant impact on the security of an application. The <code>--tls-cipher-list</code> switch and <code>ciphers</code> option should by used only if absolutely necessary.</p> <p>The default cipher suite prefers GCM ciphers for <a href="https://www.chromium.org/Home/chromium-security/education/tls#TOC-Cipher-Suites">Chrome's 'modern cryptography' setting</a> and also prefers ECDHE and DHE ciphers for Perfect Forward Secrecy, while offering <em>some</em> backward compatibility.</p> <p>128 bit AES is preferred over 192 and 256 bit AES in light of <a href="https://www.schneier.com/blog/archives/2009/07/another_new_aes.html">specific attacks affecting larger AES key sizes</a>.</p> <p>Old clients that rely on insecure and deprecated RC4 or DES-based ciphers (like Internet Explorer 6) cannot complete the handshaking process with the default configuration. If these clients <em>must</em> be supported, the <a href="https://wiki.mozilla.org/Security/Server_Side_TLS">TLS recommendations</a> may offer a compatible cipher suite. For more details on the format, see the <a href="https://www.openssl.org/docs/man1.1.0/apps/ciphers.html#CIPHER-LIST-FORMAT">OpenSSL cipher list format documentation</a>.</p> <h2>Class: tls.Server<span><a class="mark" href="#tls_class_tls_server" id="tls_class_tls_server">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.2</span> </div> <p>The <code>tls.Server</code> class is a subclass of <code>net.Server</code> that accepts encrypted connections using TLS or SSL.</p> <h3>Event: 'keylog'<span><a class="mark" href="#tls_event_keylog" id="tls_event_keylog">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> </div> <ul> <li><code>line</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> Line of ASCII text, in NSS <code>SSLKEYLOGFILE</code> format.</li> <li><code>tlsSocket</code> <a href="#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a> The <code>tls.TLSSocket</code> instance on which it was generated.</li> </ul> <p>The <code>keylog</code> event is emitted when key material is generated or received by a connection to this server (typically before handshake has completed, but not necessarily). This keying material can be stored for debugging, as it allows captured TLS traffic to be decrypted. It may be emitted multiple times for each socket.</p> <p>A typical use case is to append received lines to a common text file, which is later used by software (such as Wireshark) to decrypt the traffic:</p> <pre><code class="language-js">const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' }); // ... server.on('keylog', (line, tlsSocket) => { if (tlsSocket.remoteAddress !== '...') return; // Only log keys for a particular IP logFile.write(line); }); </code></pre> <h3>Event: 'newSession'<span><a class="mark" href="#tls_event_newsession" id="tls_event_newsession">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.2</span> </div> <p>The <code>'newSession'</code> event is emitted upon creation of a new TLS session. This may be used to store sessions in external storage. The data should be provided to the <a href="#tls_event_resumesession"><code>'resumeSession'</code></a> callback.</p> <p>The listener callback is passed three arguments when called:</p> <ul> <li><code>sessionId</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> The TLS session identifier</li> <li><code>sessionData</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> The TLS session data</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function taking no arguments that must be invoked in order for data to be sent or received over the secure connection.</li> </ul> <p>Listening for this event will have an effect only on connections established after the addition of the event listener.</p> <h3>Event: 'OCSPRequest'<span><a class="mark" href="#tls_event_ocsprequest" id="tls_event_ocsprequest">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.13</span> </div> <p>The <code>'OCSPRequest'</code> event is emitted when the client sends a certificate status request. The listener callback is passed three arguments when called:</p> <ul> <li><code>certificate</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> The server certificate</li> <li><code>issuer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> The issuer's certificate</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function that must be invoked to provide the results of the OCSP request.</li> </ul> <p>The server's current certificate can be parsed to obtain the OCSP URL and certificate ID; after obtaining an OCSP response, <code>callback(null, resp)</code> is then invoked, where <code>resp</code> is a <code>Buffer</code> instance containing the OCSP response. Both <code>certificate</code> and <code>issuer</code> are <code>Buffer</code> DER-representations of the primary and issuer's certificates. These can be used to obtain the OCSP certificate ID and OCSP endpoint URL.</p> <p>Alternatively, <code>callback(null, null)</code> may be called, indicating that there was no OCSP response.</p> <p>Calling <code>callback(err)</code> will result in a <code>socket.destroy(err)</code> call.</p> <p>The typical flow of an OCSP Request is as follows:</p> <ol> <li>Client connects to the server and sends an <code>'OCSPRequest'</code> (via the status info extension in ClientHello).</li> <li>Server receives the request and emits the <code>'OCSPRequest'</code> event, calling the listener if registered.</li> <li>Server extracts the OCSP URL from either the <code>certificate</code> or <code>issuer</code> and performs an <a href="https://en.wikipedia.org/wiki/OCSP_stapling">OCSP request</a> to the CA.</li> <li>Server receives <code>'OCSPResponse'</code> from the CA and sends it back to the client via the <code>callback</code> argument</li> <li>Client validates the response and either destroys the socket or performs a handshake.</li> </ol> <p>The <code>issuer</code> can be <code>null</code> if the certificate is either self-signed or the issuer is not in the root certificates list. (An issuer may be provided via the <code>ca</code> option when establishing the TLS connection.)</p> <p>Listening for this event will have an effect only on connections established after the addition of the event listener.</p> <p>An npm module like <a href="https://www.npmjs.com/package/asn1.js">asn1.js</a> may be used to parse the certificates.</p> <h3>Event: 'resumeSession'<span><a class="mark" href="#tls_event_resumesession" id="tls_event_resumesession">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.2</span> </div> <p>The <code>'resumeSession'</code> event is emitted when the client requests to resume a previous TLS session. The listener callback is passed two arguments when called:</p> <ul> <li><code>sessionId</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> The TLS session identifier</li> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function to be called when the prior session has been recovered: <code>callback([err[, sessionData]])</code></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>sessionData</code> <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> </li> </ul> <p>The event listener should perform a lookup in external storage for the <code>sessionData</code> saved by the <a href="#tls_event_newsession"><code>'newSession'</code></a> event handler using the given <code>sessionId</code>. If found, call <code>callback(null, sessionData)</code> to resume the session. If not found, the session cannot be resumed. <code>callback()</code> must be called without <code>sessionData</code> so that the handshake can continue and a new session can be created. It is possible to call <code>callback(err)</code> to terminate the incoming connection and destroy the socket.</p> <p>Listening for this event will have an effect only on connections established after the addition of the event listener.</p> <p>The following illustrates resuming a TLS session:</p> <pre><code class="language-js">const tlsSessionStore = {}; server.on('newSession', (id, data, cb) => { tlsSessionStore[id.toString('hex')] = data; cb(); }); server.on('resumeSession', (id, cb) => { cb(null, tlsSessionStore[id.toString('hex')] || null); }); </code></pre> <h3>Event: 'secureConnection'<span><a class="mark" href="#tls_event_secureconnection" id="tls_event_secureconnection">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.2</span> </div> <p>The <code>'secureConnection'</code> event is emitted after the handshaking process for a new connection has successfully completed. The listener callback is passed a single argument when called:</p> <ul> <li><code>tlsSocket</code> <a href="#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a> The established TLS socket.</li> </ul> <p>The <code>tlsSocket.authorized</code> property is a <code>boolean</code> indicating whether the client has been verified by one of the supplied Certificate Authorities for the server. If <code>tlsSocket.authorized</code> is <code>false</code>, then <code>socket.authorizationError</code> is set to describe how authorization failed. Note that depending on the settings of the TLS server, unauthorized connections may still be accepted.</p> <p>The <code>tlsSocket.alpnProtocol</code> property is a string that contains the selected ALPN protocol. When ALPN has no selected protocol, <code>tlsSocket.alpnProtocol</code> equals <code>false</code>.</p> <p>The <code>tlsSocket.servername</code> property is a string containing the server name requested via SNI.</p> <h3>Event: 'tlsClientError'<span><a class="mark" href="#tls_event_tlsclienterror" id="tls_event_tlsclienterror">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.0.0</span> </div> <p>The <code>'tlsClientError'</code> event is emitted when an error occurs before a secure connection is established. The listener callback is passed two arguments when called:</p> <ul> <li><code>exception</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> The <code>Error</code> object describing the error</li> <li><code>tlsSocket</code> <a href="#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a> The <code>tls.TLSSocket</code> instance from which the error originated.</li> </ul> <h3>server.addContext(hostname, context)<span><a class="mark" href="#tls_server_addcontext_hostname_context" id="tls_server_addcontext_hostname_context">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.3</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A SNI hostname or wildcard (e.g. <code>'*'</code>)</li> <li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing any of the possible properties from the <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> <code>options</code> arguments (e.g. <code>key</code>, <code>cert</code>, <code>ca</code>, etc).</li> </ul> <p>The <code>server.addContext()</code> method adds a secure context that will be used if the client request's SNI name matches the supplied <code>hostname</code> (or wildcard).</p> <h3>server.address()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1475">[src]</a><span><a class="mark" href="#tls_server_address" id="tls_server_address">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.6.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns the bound address, the address family name, and port of the server as reported by the operating system. See <a href="#net_server_address"><code>net.Server.address()</code></a> for more information.</p> <h3>server.close([callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1562">[src]</a><span><a class="mark" href="#tls_server_close_callback" id="tls_server_close_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.2</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A listener callback that will be registered to listen for the server instance's <code>'close'</code> event.</li> <li>Returns: <a href="#tls_class_tls_server" class="type"><tls.Server></a></li> </ul> <p>The <code>server.close()</code> method stops the server from accepting new connections.</p> <p>This function operates asynchronously. The <code>'close'</code> event will be emitted when the server has no more open connections.</p> <h3>server.connections<span><a class="mark" href="#tls_server_connections" id="tls_server_connections">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.2</span><span>Deprecated since: v0.9.7</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#net_server_getconnections_callback"><code>server.getConnections()</code></a> instead.</div><p></p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Returns the current number of concurrent connections on the server.</p> <h3>server.getTicketKeys()<span><a class="mark" href="#tls_server_getticketkeys" id="tls_server_getticketkeys">#</a></span></h3> <div class="api_metadata"> <span>Added in: v3.0.0</span> </div> <ul> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> A 48-byte buffer containing the session ticket keys.</li> </ul> <p>Returns the session ticket keys.</p> <p>See <a href="#tls_session_resumption">Session Resumption</a> for more information.</p> <h3>server.listen()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/net.js#L1360">[src]</a><span><a class="mark" href="#tls_server_listen" id="tls_server_listen">#</a></span></h3> <p>Starts the server listening for encrypted connections. This method is identical to <a href="#net_server_listen"><code>server.listen()</code></a> from <a href="#net_class_net_server"><code>net.Server</code></a>.</p> <h3>server.setTicketKeys(keys)<span><a class="mark" href="#tls_server_setticketkeys_keys" id="tls_server_setticketkeys_keys">#</a></span></h3> <div class="api_metadata"> <span>Added in: v3.0.0</span> </div> <ul> <li><code>keys</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> A 48-byte buffer containing the session ticket keys.</li> </ul> <p>Sets the session ticket keys.</p> <p>Changes to the ticket keys are effective only for future server connections. Existing or currently pending server connections will use the previous keys.</p> <p>See <a href="#tls_session_resumption">Session Resumption</a> for more information.</p> <h2>Class: tls.TLSSocket<span><a class="mark" href="#tls_class_tls_tlssocket" id="tls_class_tls_tlssocket">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <p>The <code>tls.TLSSocket</code> is a subclass of <a href="#net_class_net_socket"><code>net.Socket</code></a> that performs transparent encryption of written data and all required TLS negotiation.</p> <p>Instances of <code>tls.TLSSocket</code> implement the duplex <a href="#stream_stream">Stream</a> interface.</p> <p>Methods that return TLS connection metadata (e.g. <a href="#tls_tlssocket_getpeercertificate_detailed"><code>tls.TLSSocket.getPeerCertificate()</code></a> will only return data while the connection is open.</p> <h3>new tls.TLSSocket(socket[, options])<span><a class="mark" href="#tls_new_tls_tlssocket_socket_options" id="tls_new_tls_tlssocket_socket_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v5.0.0</td> <td><p>ALPN options are supported now.</p></td></tr> <tr><td>v0.11.4</td> <td><p><span>Added in: v0.11.4</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>socket</code> <a href="#net_class_net_socket" class="type"><net.Socket></a> | <a href="#stream_class_stream_duplex" class="type"><stream.Duplex></a> On the server side, any <code>Duplex</code> stream. On the client side, any instance of <a href="#net_class_net_socket"><code>net.Socket</code></a> (for generic <code>Duplex</code> stream support on the client side, <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> must be used).</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>isServer</code>: The SSL/TLS protocol is asymmetrical, TLSSockets must know if they are to behave as a server or a client. If <code>true</code> the TLS socket will be instantiated as a server. <strong>Default:</strong> <code>false</code>.</li> <li><code>server</code> <a href="#net_class_net_server" class="type"><net.Server></a> A <a href="#net_class_net_server"><code>net.Server</code></a> instance.</li> <li><code>requestCert</code>: Whether to authenticate the remote peer by requesting a certificate. Clients always request a server certificate. Servers (<code>isServer</code> is true) may set <code>requestCert</code> to true to request a client certificate.</li> <li><code>rejectUnauthorized</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li> <li><code>ALPNProtocols</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li> <li><code>SNICallback</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li> <li><code>session</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> A <code>Buffer</code> instance containing a TLS session.</li> <li><code>requestOCSP</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the OCSP status request extension will be added to the client hello and an <code>'OCSPResponse'</code> event will be emitted on the socket before establishing a secure communication</li> <li><code>secureContext</code>: TLS context object created with <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>. If a <code>secureContext</code> is <em>not</em> provided, one will be created by passing the entire <code>options</code> object to <code>tls.createSecureContext()</code>.</li> <li>...: <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> options that are used if the <code>secureContext</code> option is missing. Otherwise, they are ignored.</li> </ul> </li> </ul> <p>Construct a new <code>tls.TLSSocket</code> object from an existing TCP socket.</p> <h3>Event: 'keylog'<span><a class="mark" href="#tls_event_keylog_1" id="tls_event_keylog_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.20.0</span> </div> <ul> <li><code>line</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> Line of ASCII text, in NSS <code>SSLKEYLOGFILE</code> format.</li> </ul> <p>The <code>keylog</code> event is emitted on a client <code>tls.TLSSocket</code> when key material is generated or received by the socket. This keying material can be stored for debugging, as it allows captured TLS traffic to be decrypted. It may be emitted multiple times, before or after the handshake completes.</p> <p>A typical use case is to append received lines to a common text file, which is later used by software (such as Wireshark) to decrypt the traffic:</p> <pre><code class="language-js">const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' }); // ... tlsSocket.on('keylog', (line) => logFile.write(line)); </code></pre> <h3>Event: 'OCSPResponse'<span><a class="mark" href="#tls_event_ocspresponse" id="tls_event_ocspresponse">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.13</span> </div> <p>The <code>'OCSPResponse'</code> event is emitted if the <code>requestOCSP</code> option was set when the <code>tls.TLSSocket</code> was created and an OCSP response has been received. The listener callback is passed a single argument when called:</p> <ul> <li><code>response</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> The server's OCSP response</li> </ul> <p>Typically, the <code>response</code> is a digitally signed object from the server's CA that contains information about server's certificate revocation status.</p> <h3>Event: 'secureConnect'<span><a class="mark" href="#tls_event_secureconnect" id="tls_event_secureconnect">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <p>The <code>'secureConnect'</code> event is emitted after the handshaking process for a new connection has successfully completed. The listener callback will be called regardless of whether or not the server's certificate has been authorized. It is the client's responsibility to check the <code>tlsSocket.authorized</code> property to determine if the server certificate was signed by one of the specified CAs. If <code>tlsSocket.authorized === false</code>, then the error can be found by examining the <code>tlsSocket.authorizationError</code> property. If ALPN was used, the <code>tlsSocket.alpnProtocol</code> property can be checked to determine the negotiated protocol.</p> <h3>tlsSocket.address()<span><a class="mark" href="#tls_tlssocket_address" id="tls_tlssocket_address">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns the bound <code>address</code>, the address <code>family</code> name, and <code>port</code> of the underlying socket as reported by the operating system: <code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code>.</p> <h3>tlsSocket.authorizationError<span><a class="mark" href="#tls_tlssocket_authorizationerror" id="tls_tlssocket_authorizationerror">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <p>Returns the reason why the peer's certificate was not been verified. This property is set only when <code>tlsSocket.authorized === false</code>.</p> <h3>tlsSocket.authorized<span><a class="mark" href="#tls_tlssocket_authorized" id="tls_tlssocket_authorized">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the peer certificate was signed by one of the CAs specified when creating the <code>tls.TLSSocket</code> instance, otherwise <code>false</code>.</p> <h3>tlsSocket.disableRenegotiation()<span><a class="mark" href="#tls_tlssocket_disablerenegotiation" id="tls_tlssocket_disablerenegotiation">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.4.0</span> </div> <p>Disables TLS renegotiation for this <code>TLSSocket</code> instance. Once called, attempts to renegotiate will trigger an <code>'error'</code> event on the <code>TLSSocket</code>.</p> <h3>tlsSocket.encrypted<span><a class="mark" href="#tls_tlssocket_encrypted" id="tls_tlssocket_encrypted">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <p>Always returns <code>true</code>. This may be used to distinguish TLS sockets from regular <code>net.Socket</code> instances.</p> <h3>tlsSocket.getCipher()<span><a class="mark" href="#tls_tlssocket_getcipher" id="tls_tlssocket_getcipher">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns an object representing the cipher name. The <code>version</code> key is a legacy field which always contains the value <code>'TLSv1/SSLv3'</code>.</p> <p>For example: <code>{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }</code>.</p> <p>See <code>SSL_CIPHER_get_name()</code> in <a href="https://www.openssl.org/docs/man1.1.0/ssl/SSL_CIPHER_get_name.html">https://www.openssl.org/docs/man1.1.0/ssl/SSL_CIPHER_get_name.html</a> for more information.</p> <h3>tlsSocket.getEphemeralKeyInfo()<span><a class="mark" href="#tls_tlssocket_getephemeralkeyinfo" id="tls_tlssocket_getephemeralkeyinfo">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.0.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns an object representing the type, name, and size of parameter of an ephemeral key exchange in <a href="#tls_perfect_forward_secrecy">Perfect Forward Secrecy</a> 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; <code>null</code> is returned if called on a server socket. The supported types are <code>'DH'</code> and <code>'ECDH'</code>. The <code>name</code> property is available only when type is <code>'ECDH'</code>.</p> <p>For example: <code>{ type: 'ECDH', name: 'prime256v1', size: 256 }</code>.</p> <h3>tlsSocket.getFinished()<span><a class="mark" href="#tls_tlssocket_getfinished" id="tls_tlssocket_getfinished">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.9.0</span> </div> <ul> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The latest <code>Finished</code> message that has been sent to the socket as part of a SSL/TLS handshake, or <code>undefined</code> if no <code>Finished</code> message has been sent yet.</li> </ul> <p>As the <code>Finished</code> messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.</p> <p>Corresponds to the <code>SSL_get_finished</code> routine in OpenSSL and may be used to implement the <code>tls-unique</code> channel binding from <a href="https://tools.ietf.org/html/rfc5929">RFC 5929</a>.</p> <h3>tlsSocket.getPeerCertificate([detailed])<span><a class="mark" href="#tls_tlssocket_getpeercertificate_detailed" id="tls_tlssocket_getpeercertificate_detailed">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><code>detailed</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Include the full certificate chain if <code>true</code>, otherwise include just the peer's certificate.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns an object representing the peer's certificate. The returned object has some properties corresponding to the fields of the certificate.</p> <p>If the full certificate chain was requested, each certificate will include an <code>issuerCertificate</code> property containing an object representing its issuer's certificate.</p> <pre><code class="language-text">{ subject: { C: 'UK', ST: 'Acknack Ltd', L: 'Rhys Jones', O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, issuer: { C: 'UK', ST: 'Acknack Ltd', L: 'Rhys Jones', O: 'node.js', OU: 'Test TLS Certificate', CN: 'localhost' }, issuerCertificate: { ... another certificate, possibly with an .issuerCertificate ... }, raw: < RAW DER buffer >, pubkey: < RAW DER buffer >, valid_from: 'Nov 11 09:52:22 2009 GMT', valid_to: 'Nov 6 09:52:22 2029 GMT', fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF', fingerprint256: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF:00:11:22:33:44:55:66:77:88:99:AA:BB', serialNumber: 'B9B0D332A1AA5635' } </code></pre> <p>If the peer does not provide a certificate, an empty object will be returned.</p> <h3>tlsSocket.getPeerFinished()<span><a class="mark" href="#tls_tlssocket_getpeerfinished" id="tls_tlssocket_getpeerfinished">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.9.0</span> </div> <ul> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a> The latest <code>Finished</code> message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or <code>undefined</code> if there is no <code>Finished</code> message so far.</li> </ul> <p>As the <code>Finished</code> messages are message digests of the complete handshake (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can be used for external authentication procedures when the authentication provided by SSL/TLS is not desired or is not enough.</p> <p>Corresponds to the <code>SSL_get_peer_finished</code> routine in OpenSSL and may be used to implement the <code>tls-unique</code> channel binding from <a href="https://tools.ietf.org/html/rfc5929">RFC 5929</a>.</p> <h3>tlsSocket.getProtocol()<span><a class="mark" href="#tls_tlssocket_getprotocol" id="tls_tlssocket_getprotocol">#</a></span></h3> <div class="api_metadata"> <span>Added in: v5.7.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a></li> </ul> <p>Returns a string containing the negotiated SSL/TLS protocol version of the current connection. The value <code>'unknown'</code> will be returned for connected sockets that have not completed the handshaking process. The value <code>null</code> will be returned for server sockets or disconnected client sockets.</p> <p>Protocol versions are:</p> <ul> <li><code>'TLSv1'</code></li> <li><code>'TLSv1.1'</code></li> <li><code>'TLSv1.2'</code></li> <li><code>'SSLv3'</code></li> </ul> <p>See <a href="https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_version.html">https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_version.html</a> for more information.</p> <h3>tlsSocket.getSession()<span><a class="mark" href="#tls_tlssocket_getsession" id="tls_tlssocket_getsession">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Returns the TLS session data or <code>undefined</code> if no session was negotiated. On the client, the data can be provided to the <code>session</code> option of <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> to resume the connection. On the server, it may be useful for debugging.</p> <p>See <a href="#tls_session_resumption">Session Resumption</a> for more information.</p> <h3>tlsSocket.getTLSTicket()<span><a class="mark" href="#tls_tlssocket_gettlsticket" id="tls_tlssocket_gettlsticket">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>For a client, returns the TLS session ticket if one is available, or <code>undefined</code>. For a server, always returns <code>undefined</code>.</p> <p>It may be useful for debugging.</p> <p>See <a href="#tls_session_resumption">Session Resumption</a> for more information.</p> <h3>tlsSocket.isSessionReused()<span><a class="mark" href="#tls_tlssocket_issessionreused" id="tls_tlssocket_issessionreused">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.6</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the session was reused, <code>false</code> otherwise.</li> </ul> <p>See <a href="#tls_session_resumption">Session Resumption</a> for more information.</p> <h3>tlsSocket.localAddress<span><a class="mark" href="#tls_tlssocket_localaddress" id="tls_tlssocket_localaddress">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the string representation of the local IP address.</p> <h3>tlsSocket.localPort<span><a class="mark" href="#tls_tlssocket_localport" id="tls_tlssocket_localport">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Returns the numeric representation of the local port.</p> <h3>tlsSocket.remoteAddress<span><a class="mark" href="#tls_tlssocket_remoteaddress" id="tls_tlssocket_remoteaddress">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the string representation of the remote IP address. For example, <code>'74.125.127.100'</code> or <code>'2001:4860:a005::68'</code>.</p> <h3>tlsSocket.remoteFamily<span><a class="mark" href="#tls_tlssocket_remotefamily" id="tls_tlssocket_remotefamily">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the string representation of the remote IP family. <code>'IPv4'</code> or <code>'IPv6'</code>.</p> <h3>tlsSocket.remotePort<span><a class="mark" href="#tls_tlssocket_remoteport" id="tls_tlssocket_remoteport">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Returns the numeric representation of the remote port. For example, <code>443</code>.</p> <h3>tlsSocket.renegotiate(options, callback)<span><a class="mark" href="#tls_tlssocket_renegotiate_options_callback" id="tls_tlssocket_renegotiate_options_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.8</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>rejectUnauthorized</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If not <code>false</code>, the server certificate is verified against the list of supplied CAs. An <code>'error'</code> event is emitted if verification fails; <code>err.code</code> contains the OpenSSL error code. <strong>Default:</strong> <code>true</code>.</li> <li><code>requestCert</code></li> </ul> </li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A function that will be called when the renegotiation request has been completed.</li> </ul> <p>The <code>tlsSocket.renegotiate()</code> method initiates a TLS renegotiation process. Upon completion, the <code>callback</code> function will be passed a single argument that is either an <code>Error</code> (if the request failed) or <code>null</code>.</p> <p>This method can be used to request a peer's certificate after the secure connection has been established.</p> <p>When running as the server, the socket will be destroyed with an error after <code>handshakeTimeout</code> timeout.</p> <h3>tlsSocket.setMaxSendFragment(size)<span><a class="mark" href="#tls_tlssocket_setmaxsendfragment_size" id="tls_tlssocket_setmaxsendfragment_size">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.11</span> </div> <ul> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The maximum TLS fragment size. The maximum value is <code>16384</code>. <strong>Default:</strong> <code>16384</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The <code>tlsSocket.setMaxSendFragment()</code> method sets the maximum TLS fragment size. Returns <code>true</code> if setting the limit succeeded; <code>false</code> otherwise.</p> <p>Smaller fragment sizes decrease the buffering latency on the client: larger fragments are buffered by the TLS layer until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips and their processing can be delayed due to packet loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.</p> <h2>tls.checkServerIdentity(hostname, cert)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/tls.js#L192">[src]</a><span><a class="mark" href="#tls_tls_checkserveridentity_hostname_cert" id="tls_tls_checkserveridentity_hostname_cert">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.8.4</span> </div> <ul> <li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The host name or IP address to verify the certificate against.</li> <li><code>cert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object representing the peer's certificate. The returned object has some properties corresponding to the fields of the certificate.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a></li> </ul> <p>Verifies the certificate <code>cert</code> is issued to <code>hostname</code>.</p> <p>Returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> object, populating it with <code>reason</code>, <code>host</code>, and <code>cert</code> on failure. On success, returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type"><undefined></a>.</p> <p>This function can be overwritten by providing alternative function as part of the <code>options.checkServerIdentity</code> option passed to <code>tls.connect()</code>. The overwriting function can call <code>tls.checkServerIdentity()</code> of course, to augment the checks done with additional verification.</p> <p>This function is only called if the certificate passed all other checks, such as being issued by trusted CA (<code>options.ca</code>).</p> <p>The cert object contains the parsed certificate and will have a structure similar to:</p> <pre><code class="language-text">{ subject: { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ], CN: '*.nodejs.org' }, issuer: { C: 'GB', ST: 'Greater Manchester', L: 'Salford', O: 'COMODO CA Limited', CN: 'COMODO RSA Domain Validation Secure Server CA' }, subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org', infoAccess: { 'CA Issuers - URI': [ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ], 'OCSP - URI': [ 'http://ocsp.comodoca.com' ] }, modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1', exponent: '0x10001', pubkey: <Buffer ... >, valid_from: 'Aug 14 00:00:00 2017 GMT', valid_to: 'Nov 20 23:59:59 2019 GMT', fingerprint: '01:02:59:D9:C3:D2:0D:08:F7:82:4E:44:A4:B4:53:C5:E2:3A:87:4D', fingerprint256: '69:AE:1A:6A:D4:3D:C6:C1:1B:EA:C6:23:DE:BA:2A:14:62:62:93:5C:7A:EA:06:41:9B:0B:BC:87:CE:48:4E:02', ext_key_usage: [ '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' ], serialNumber: '66593D57F20CBC573E433381B5FEC280', raw: <Buffer ... > } </code></pre> <h2>tls.connect(options[, callback])<span><a class="mark" href="#tls_tls_connect_options_callback" id="tls_tls_connect_options_callback">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.16.0</td> <td><p>The <code>timeout</code> option is supported now.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>lookup</code> option is supported now.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>ALPNProtocols</code> option can be a <code>Uint8Array</code> now.</p></td></tr> <tr><td>v5.3.0, v4.7.0</td> <td><p>The <code>secureContext</code> option is supported now.</p></td></tr> <tr><td>v5.0.0</td> <td><p>ALPN options are supported now.</p></td></tr> <tr><td>v0.11.3</td> <td><p><span>Added in: v0.11.3</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Host the client should connect to. <strong>Default:</strong> <code>'localhost'</code>.</li> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Port the client should connect to.</li> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Creates unix socket connection to path. If this option is specified, <code>host</code> and <code>port</code> are ignored.</li> <li><code>socket</code> <a href="#stream_class_stream_duplex" class="type"><stream.Duplex></a> Establish secure connection on a given socket rather than creating a new socket. Typically, this is an instance of <a href="#net_class_net_socket"><code>net.Socket</code></a>, but any <code>Duplex</code> stream is allowed. If this option is specified, <code>path</code>, <code>host</code> and <code>port</code> are ignored, except for certificate validation. Usually, a socket is already connected when passed to <code>tls.connect()</code>, but it can be connected later. Note that connection/disconnection/destruction of <code>socket</code> is the user's responsibility, calling <code>tls.connect()</code> will not cause <code>net.connect()</code> to be called.</li> <li><code>rejectUnauthorized</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If not <code>false</code>, the server certificate is verified against the list of supplied CAs. An <code>'error'</code> event is emitted if verification fails; <code>err.code</code> contains the OpenSSL error code. <strong>Default:</strong> <code>true</code>.</li> <li><code>ALPNProtocols</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#buffer_class_buffer" class="type"><Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array[]></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> An array of strings, <code>Buffer</code>s or <code>Uint8Array</code>s, or a single <code>Buffer</code> or <code>Uint8Array</code> containing the supported ALPN protocols. <code>Buffer</code>s should have the format <code>[len][name][len][name]...</code> e.g. <code>'\x08http/1.1\x08http/1.0'</code>, where the <code>len</code> byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. <code>['http/1.1', 'http/1.0']</code>. Protocols earlier in the list have higher preference than those later.</li> <li><code>servername</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Server name for the SNI (Server Name Indication) TLS extension. It is the name of the host being connected to, and must be a host name, and not an IP address. It can be used by a multi-homed server to choose the correct certificate to present to the client, see the <code>SNICallback</code> option to <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>.</li> <li><code>checkServerIdentity(servername, cert)</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A callback function to be used (instead of the builtin <code>tls.checkServerIdentity()</code> function) when checking the server's hostname (or the provided <code>servername</code> when explicitly set) against the certificate. This should return an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> if verification fails. The method should return <code>undefined</code> if the <code>servername</code> and <code>cert</code> are verified.</li> <li><code>session</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> A <code>Buffer</code> instance, containing TLS session.</li> <li><code>minDHSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than <code>minDHSize</code>, the TLS connection is destroyed and an error is thrown. <strong>Default:</strong> <code>1024</code>.</li> <li><code>secureContext</code>: TLS context object created with <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>. If a <code>secureContext</code> is <em>not</em> provided, one will be created by passing the entire <code>options</code> object to <code>tls.createSecureContext()</code>.</li> <li><code>lookup</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Custom lookup function. <strong>Default:</strong> <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li> <li><code>timeout</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> If set and if a socket is created internally, will call <a href="#net_socket_settimeout_timeout_callback"><code>socket.setTimeout(timeout)</code></a> after the socket is created, but before it starts the connection.</li> <li>...: <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> options that are used if the <code>secureContext</code> option is missing, otherwise they are ignored.</li> </ul> </li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li> </ul> <p>The <code>callback</code> function, if specified, will be added as a listener for the <a href="#tls_event_secureconnect"><code>'secureConnect'</code></a> event.</p> <p><code>tls.connect()</code> returns a <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> object.</p> <p>The following illustrates a client for the echo server example from <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>:</p> <pre><code class="language-js">// Assumes an echo server that is listening on port 8000. const tls = require('tls'); const fs = require('fs'); const options = { // Necessary only if the server requires client certificate authentication. key: fs.readFileSync('client-key.pem'), cert: fs.readFileSync('client-cert.pem'), // Necessary only if the server uses a self-signed certificate. ca: [ fs.readFileSync('server-cert.pem') ], // Necessary only if the server's cert isn't for "localhost". checkServerIdentity: () => { return null; }, }; const socket = tls.connect(8000, options, () => { console.log('client connected', socket.authorized ? 'authorized' : 'unauthorized'); process.stdin.pipe(socket); process.stdin.resume(); }); socket.setEncoding('utf8'); socket.on('data', (data) => { console.log(data); }); socket.on('end', () => { console.log('server ends connection'); }); </code></pre> <h2>tls.connect(path[, options][, callback])<span><a class="mark" href="#tls_tls_connect_path_options_callback" id="tls_tls_connect_path_options_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.3</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Default value for <code>options.path</code>.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> See <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>.</li> <li>Returns: <a href="#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li> </ul> <p>Same as <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> except that <code>path</code> can be provided as an argument instead of an option.</p> <p>A path option, if specified, will take precedence over the path argument.</p> <h2>tls.connect(port[, host][, options][, callback])<span><a class="mark" href="#tls_tls_connect_port_host_options_callback" id="tls_tls_connect_port_host_options_callback">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.3</span> </div> <ul> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Default value for <code>options.port</code>.</li> <li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Default value for <code>options.host</code>.</li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> See <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> See <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>.</li> <li>Returns: <a href="#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li> </ul> <p>Same as <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> except that <code>port</code> and <code>host</code> can be provided as arguments instead of options.</p> <p>A port or host option, if specified, will take precedence over any port or host argument.</p> <h2>tls.createSecureContext([options])<span><a class="mark" href="#tls_tls_createsecurecontext_options" id="tls_tls_createsecurecontext_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.16.0</td> <td><p>The <code>minVersion</code> and <code>maxVersion</code> can be used to restrict the allowed TLS protocol versions.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>ecdhCurve</code> cannot be set to <code>false</code> anymore due to a change in OpenSSL.</p></td></tr> <tr><td>v9.3.0</td> <td><p>The <code>options</code> parameter can now include <code>clientCertEngine</code>.</p></td></tr> <tr><td>v9.0.0</td> <td><p>The <code>ecdhCurve</code> option can now be multiple <code>':'</code> separated curve names or <code>'auto'</code>.</p></td></tr> <tr><td>v7.3.0</td> <td><p>If the <code>key</code> option is an array, individual entries do not need a <code>passphrase</code> property anymore. <code>Array</code> entries can also just be <code>string</code>s or <code>Buffer</code>s now.</p></td></tr> <tr><td>v5.2.0</td> <td><p>The <code>ca</code> option can now be a single string containing multiple CA certificates.</p></td></tr> <tr><td>v0.11.13</td> <td><p><span>Added in: v0.11.13</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>ca</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#buffer_class_buffer" class="type"><Buffer[]></a> Optionally override the trusted CA certificates. Default is to trust the well-known CAs curated by Mozilla. Mozilla's CAs are completely replaced when CAs are explicitly specified using this option. The value can be a string or <code>Buffer</code>, or an <code>Array</code> of strings and/or <code>Buffer</code>s. Any string or <code>Buffer</code> can contain multiple PEM CAs concatenated together. The peer's certificate must be chainable to a CA trusted by the server for the connection to be authenticated. When using certificates that are not chainable to a well-known CA, the certificate's CA must be explicitly specified as a trusted or the connection will fail to authenticate. If the peer uses a certificate that doesn't match or chain to one of the default CAs, use the <code>ca</code> option to provide a CA certificate that the peer's certificate can match or chain to. For self-signed certificates, the certificate is its own CA, and must be provided. For PEM encoded certificates, supported types are "X509 CERTIFICATE", and "CERTIFICATE".</li> <li><code>cert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#buffer_class_buffer" class="type"><Buffer[]></a> Cert chains in PEM format. One cert chain should be provided per private key. Each cert chain should consist of the PEM formatted certificate for a provided private <code>key</code>, followed by the PEM formatted intermediate certificates (if any), in order, and not including the root CA (the root CA must be pre-known to the peer, see <code>ca</code>). When providing multiple cert chains, they do not have to be in the same order as their private keys in <code>key</code>. If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.</li> <li><code>ciphers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Cipher suite specification, replacing the default. For more information, see <a href="#tls_modifying_the_default_tls_cipher_suite">modifying the default cipher suite</a>.</li> <li><code>clientCertEngine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of an OpenSSL engine which can provide the client certificate.</li> <li><code>crl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#buffer_class_buffer" class="type"><Buffer[]></a> PEM formatted CRLs (Certificate Revocation Lists).</li> <li><code>dhparam</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> Diffie Hellman parameters, required for <a href="#tls_perfect_forward_secrecy">Perfect Forward Secrecy</a>. Use <code>openssl dhparam</code> to create the parameters. The key length must be greater than or equal to 1024 bits, otherwise an error will be thrown. It is strongly recommended to use 2048 bits or larger for stronger security. If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available.</li> <li><code>ecdhCurve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string describing a named curve or a colon separated list of curve NIDs or names, for example <code>P-521:P-384:P-256</code>, to use for ECDH key agreement. Set to <code>auto</code> to select the curve automatically. Use <a href="#crypto_crypto_getcurves"><code>crypto.getCurves()</code></a> to obtain a list of available curve names. On recent releases, <code>openssl ecparam -list_curves</code> will also display the name and description of each available elliptic curve. <strong>Default:</strong> <a href="#tls_tls_default_ecdh_curve"><code>tls.DEFAULT_ECDH_CURVE</code></a>.</li> <li><code>honorCipherOrder</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Attempt to use the server's cipher suite preferences instead of the client's. When <code>true</code>, causes <code>SSL_OP_CIPHER_SERVER_PREFERENCE</code> to be set in <code>secureOptions</code>, see <a href="#crypto_openssl_options">OpenSSL Options</a> for more information.</li> <li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#buffer_class_buffer" class="type"><Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> Private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with <code>options.passphrase</code>. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form <code>{pem: <string|buffer>[, passphrase: <string>]}</code>. The object form can only occur in an array. <code>object.passphrase</code> is optional. Encrypted keys will be decrypted with <code>object.passphrase</code> if provided, or <code>options.passphrase</code> if it is not.</li> <li><code>maxVersion</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optionally set the maximum TLS version to allow. One of <code>TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>. Cannot be specified along with the <code>secureProtocol</code> option, use one or the other. <strong>Default:</strong> <a href="#tls_tls_default_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a>.</li> <li><code>minVersion</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optionally set the minimum TLS version to allow. One of <code>TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>. Cannot be specified along with the <code>secureProtocol</code> option, use one or the other. It is not recommended to use less than TLSv1.2, but it may be required for interoperability. <strong>Default:</strong> <a href="#tls_tls_default_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a>.</li> <li><code>passphrase</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Shared passphrase used for a single private key and/or a PFX.</li> <li><code>pfx</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="#buffer_class_buffer" class="type"><Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> PFX or PKCS12 encoded private key and certificate chain. <code>pfx</code> is an alternative to providing <code>key</code> and <code>cert</code> individually. PFX is usually encrypted, if it is, <code>passphrase</code> will be used to decrypt it. Multiple PFX can be provided either as an array of unencrypted PFX buffers, or an array of objects in the form <code>{buf: <string|buffer>[, passphrase: <string>]}</code>. The object form can only occur in an array. <code>object.passphrase</code> is optional. Encrypted PFX will be decrypted with <code>object.passphrase</code> if provided, or <code>options.passphrase</code> if it is not.</li> <li><code>secureOptions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all! Value is a numeric bitmask of the <code>SSL_OP_*</code> options from <a href="#crypto_openssl_options">OpenSSL Options</a>.</li> <li><code>secureProtocol</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The TLS protocol version to use. The possible values are listed as <a href="https://www.openssl.org/docs/man1.1.0/ssl/ssl.html#Dealing-with-Protocol-Methods">SSL_METHODS</a>, use the function names as strings. For example, use <code>'TLSv1_1_method'</code> to force TLS version 1.1, or <code>'TLS_method'</code> to allow any TLS protocol version. It is not recommended to use TLS versions less than 1.2, but it may be required for interoperability. <strong>Default:</strong> none, see <code>minVersion</code>.</li> <li><code>sessionIdContext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Opaque identifier used by servers to ensure session state is not shared between applications. Unused by clients.</li> </ul> </li> </ul> <p><a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a> sets the default value of the <code>honorCipherOrder</code> option to <code>true</code>, other APIs that create secure contexts leave it unset.</p> <p><a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a> uses a 128 bit truncated SHA1 hash value generated from <code>process.argv</code> as the default value of the <code>sessionIdContext</code> option, other APIs that create secure contexts have no default value.</p> <p>The <code>tls.createSecureContext()</code> method creates a credentials object.</p> <p>A key is <em>required</em> for ciphers that make use of certificates. Either <code>key</code> or <code>pfx</code> can be used to provide it.</p> <p>If the 'ca' option is not given, then Node.js will use the default publicly trusted list of CAs as given in <a href="https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt">https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt</a>.</p> <h2>tls.createServer([options][, secureconnectionlistener])<span><a class="mark" href="#tls_tls_createserver_options_secureconnectionlistener" id="tls_tls_createserver_options_secureconnectionlistener">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.3.0</td> <td><p>The <code>options</code> parameter can now include <code>clientCertEngine</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>ALPNProtocols</code> option can be a <code>Uint8Array</code> now.</p></td></tr> <tr><td>v5.0.0</td> <td><p>ALPN options are supported now.</p></td></tr> <tr><td>v0.3.2</td> <td><p><span>Added in: v0.3.2</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>ALPNProtocols</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="#buffer_class_buffer" class="type"><Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array[]></a> | <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> An array of strings, <code>Buffer</code>s or <code>Uint8Array</code>s, or a single <code>Buffer</code> or <code>Uint8Array</code> containing the supported ALPN protocols. <code>Buffer</code>s should have the format <code>[len][name][len][name]...</code> e.g. <code>0x05hello0x05world</code>, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. <code>['hello', 'world']</code>. (Protocols should be ordered by their priority.)</li> <li><code>clientCertEngine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Name of an OpenSSL engine which can provide the client certificate.</li> <li><code>handshakeTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. A <code>'tlsClientError'</code> is emitted on the <code>tls.Server</code> object whenever a handshake times out. <strong>Default:</strong> <code>120000</code> (120 seconds).</li> <li><code>rejectUnauthorized</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If not <code>false</code> the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if <code>requestCert</code> is <code>true</code>. <strong>Default:</strong> <code>true</code>.</li> <li><code>requestCert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code> the server will request a certificate from clients that connect and attempt to verify that certificate. <strong>Default:</strong> <code>false</code>.</li> <li><code>sessionTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The number of seconds after which a TLS session created by the server will no longer be resumable. See <a href="#tls_session_resumption">Session Resumption</a> for more information. <strong>Default:</strong> <code>300</code>.</li> <li><code>SNICallback(servername, cb)</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: <code>servername</code> and <code>cb</code>. <code>SNICallback</code> should invoke <code>cb(null, ctx)</code>, where <code>ctx</code> is a <code>SecureContext</code> instance. (<code>tls.createSecureContext(...)</code> can be used to get a proper <code>SecureContext</code>.) If <code>SNICallback</code> wasn't provided the default callback with high-level API will be used (see below).</li> <li><code>ticketKeys</code>: <a href="#buffer_class_buffer" class="type"><Buffer></a> 48-bytes of cryptographically strong pseudo-random data. See <a href="#tls_session_resumption">Session Resumption</a> for more information.</li> <li>...: Any <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> option can be provided. For servers, the identity options (<code>pfx</code> or <code>key</code>/<code>cert</code>) are usually required.</li> </ul> </li> <li><code>secureConnectionListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="#tls_class_tls_server" class="type"><tls.Server></a></li> </ul> <p>Creates a new <a href="#tls_class_tls_server"><code>tls.Server</code></a>. The <code>secureConnectionListener</code>, if provided, is automatically set as a listener for the <a href="#tls_event_secureconnection"><code>'secureConnection'</code></a> event.</p> <p>The <code>ticketKeys</code> options is automatically shared between <code>cluster</code> module workers.</p> <p>The following illustrates a simple echo server:</p> <pre><code class="language-js">const tls = require('tls'); const fs = require('fs'); const options = { key: fs.readFileSync('server-key.pem'), cert: fs.readFileSync('server-cert.pem'), // This is necessary only if using client certificate authentication. requestCert: true, // This is necessary only if the client uses a self-signed certificate. ca: [ fs.readFileSync('client-cert.pem') ] }; const server = tls.createServer(options, (socket) => { console.log('server connected', socket.authorized ? 'authorized' : 'unauthorized'); socket.write('welcome!\n'); socket.setEncoding('utf8'); socket.pipe(socket); }); server.listen(8000, () => { console.log('server bound'); }); </code></pre> <p>The server can be tested by connecting to it using the example client from <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>.</p> <h2>tls.getCiphers()<span><a class="mark" href="#tls_tls_getciphers" id="tls_tls_getciphers">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.10.2</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Returns an array with the names of the supported SSL ciphers.</p> <pre><code class="language-js">console.log(tls.getCiphers()); // ['AES128-SHA', 'AES256-SHA', ...] </code></pre> <h2>tls.DEFAULT_ECDH_CURVE<span><a class="mark" href="#tls_tls_default_ecdh_curve" id="tls_tls_default_ecdh_curve">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Default value changed to <code>'auto'</code>.</p></td></tr> <tr><td>v0.11.13</td> <td><p><span>Added in: v0.11.13</span></p></td></tr> </tbody></table> </details> </div> <p>The default curve name to use for ECDH key agreement in a tls server. The default value is <code>'auto'</code>. See <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> for further information.</p> <h2>tls.DEFAULT_MAX_VERSION<span><a class="mark" href="#tls_tls_default_max_version" id="tls_tls_default_max_version">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The default value of the <code>maxVersion</code> option of <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>. It can be assigned any of the supported TLS protocol versions, <code>'TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>. <strong>Default:</strong> <code>'TLSv1.2'</code>.</li> </ul> <h2>tls.DEFAULT_MIN_VERSION<span><a class="mark" href="#tls_tls_default_min_version" id="tls_tls_default_min_version">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The default value of the <code>minVersion</code> option of <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>. It can be assigned any of the supported TLS protocol versions, <code>'TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>. <strong>Default:</strong> <code>'TLSv1'</code>, unless changed using CLI options. Using <code>--tls-min-v1.0</code> sets the default to <code>'TLSv1'</code>. Using <code>--tls-min-v1.1</code> sets the default to <code>'TLSv1.1'</code>. Using <code>--tls-min-v1.2</code> sets the default to <code>'TLSv1.2'</code>. If multiple of the options are provided, the lowest minimum is used.</li> </ul> <h2>Deprecated APIs<span><a class="mark" href="#tls_deprecated_apis" id="tls_deprecated_apis">#</a></span></h2> <h3>Class: CryptoStream<span><a class="mark" href="#tls_class_cryptostream" id="tls_class_cryptostream">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.4</span><span>Deprecated since: v0.11.3</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</div><p></p> <p>The <code>tls.CryptoStream</code> class represents a stream of encrypted data. This class is deprecated and should no longer be used.</p> <h4>cryptoStream.bytesWritten<span><a class="mark" href="#tls_cryptostream_byteswritten" id="tls_cryptostream_byteswritten">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.4</span><span>Deprecated since: v0.11.3</span> </div> <p>The <code>cryptoStream.bytesWritten</code> property returns the total number of bytes written to the underlying socket <em>including</em> the bytes required for the implementation of the TLS protocol.</p> <h3>Class: SecurePair<span><a class="mark" href="#tls_class_securepair" id="tls_class_securepair">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.2</span><span>Deprecated since: v0.11.3</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</div><p></p> <p>Returned by <a href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options"><code>tls.createSecurePair()</code></a>.</p> <h4>Event: 'secure'<span><a class="mark" href="#tls_event_secure" id="tls_event_secure">#</a></span></h4> <div class="api_metadata"> <span>Added in: v0.3.2</span><span>Deprecated since: v0.11.3</span> </div> <p>The <code>'secure'</code> event is emitted by the <code>SecurePair</code> object once a secure connection has been established.</p> <p>As with checking for the server <a href="#tls_event_secureconnection"><code>'secureConnection'</code></a> event, <code>pair.cleartext.authorized</code> should be inspected to confirm whether the certificate used is properly authorized.</p> <h3>tls.createSecurePair([context][, isserver][, requestCert][, rejectunauthorized][, options])<span><a class="mark" href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options" id="tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v5.0.0</td> <td><p>ALPN options are supported now.</p></td></tr> <tr><td>v0.11.3</td> <td><p><span>Deprecated since: v0.11.3</span></p></td></tr> <tr><td>v0.3.2</td> <td><p><span>Added in: v0.3.2</span></p></td></tr> </tbody></table> </details> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</div><p></p> <ul> <li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A secure context object as returned by <code>tls.createSecureContext()</code></li> <li><code>isServer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to specify that this TLS connection should be opened as a server.</li> <li><code>requestCert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> to specify whether a server should request a certificate from a connecting client. Only applies when <code>isServer</code> is <code>true</code>.</li> <li><code>rejectUnauthorized</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If not <code>false</code> a server automatically reject clients with invalid certificates. Only applies when <code>isServer</code> is <code>true</code>.</li> <li> <p><code>options</code></p> <ul> <li><code>secureContext</code>: A TLS context object from <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a></li> <li><code>isServer</code>: If <code>true</code> the TLS socket will be instantiated in server-mode. <strong>Default:</strong> <code>false</code>.</li> <li><code>server</code> <a href="#net_class_net_server" class="type"><net.Server></a> A <a href="#net_class_net_server"><code>net.Server</code></a> instance</li> <li><code>requestCert</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li> <li><code>rejectUnauthorized</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li> <li><code>ALPNProtocols</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li> <li><code>SNICallback</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li> <li><code>session</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> A <code>Buffer</code> instance containing a TLS session.</li> <li><code>requestOCSP</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, specifies that the OCSP status request extension will be added to the client hello and an <code>'OCSPResponse'</code> event will be emitted on the socket before establishing a secure communication.</li> </ul> </li> </ul> <p>Creates a new secure pair object with two streams, one of which reads and writes the encrypted data and the other of which reads and writes the cleartext data. Generally, the encrypted stream is piped to/from an incoming encrypted data stream and the cleartext one is used as a replacement for the initial encrypted stream.</p> <p><code>tls.createSecurePair()</code> returns a <code>tls.SecurePair</code> object with <code>cleartext</code> and <code>encrypted</code> stream properties.</p> <p>Using <code>cleartext</code> has the same API as <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a>.</p> <p>The <code>tls.createSecurePair()</code> method is now deprecated in favor of <code>tls.TLSSocket()</code>. For example, the code:</p> <pre><code class="language-js">pair = tls.createSecurePair(/* ... */); pair.encrypted.pipe(socket); socket.pipe(pair.encrypted); </code></pre> <p>can be replaced by:</p> <pre><code class="language-js">secureSocket = tls.TLSSocket(socket, options); </code></pre> <p>where <code>secureSocket</code> has the same API as <code>pair.cleartext</code>.</p> <h1>Trace Events<span><a class="mark" href="#tracing_trace_events" id="tracing_trace_events">#</a></span></h1> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>Trace Event provides a mechanism to centralize tracing information generated by V8, Node.js core, and userspace code.</p> <p>Tracing can be enabled with the <code>--trace-event-categories</code> command-line flag or by using the <code>trace_events</code> module. The <code>--trace-event-categories</code> flag accepts a list of comma-separated category names.</p> <p>The available categories are:</p> <ul> <li><code>node</code> - An empty placeholder.</li> <li><code>node.async_hooks</code> - Enables capture of detailed <a href="async_hooks.html"><code>async_hooks</code></a> trace data. The <a href="async_hooks.html"><code>async_hooks</code></a> events have a unique <code>asyncId</code> and a special <code>triggerId</code> <code>triggerAsyncId</code> property.</li> <li><code>node.bootstrap</code> - Enables capture of Node.js bootstrap milestones.</li> <li><code>node.console</code> - Enables capture of <code>console.time()</code> and <code>console.count()</code> output.</li> <li><code>node.fs.sync</code> - Enables capture of trace data for file system sync methods.</li> <li> <p><code>node.perf</code> - Enables capture of <a href="perf_hooks.html">Performance API</a> measurements.</p> <ul> <li><code>node.perf.usertiming</code> - Enables capture of only Performance API User Timing measures and marks.</li> <li><code>node.perf.timerify</code> - Enables capture of only Performance API timerify measurements.</li> </ul> </li> <li><code>node.promises.rejections</code> - Enables capture of trace data tracking the number of unhandled Promise rejections and handled-after-rejections.</li> <li><code>node.vm.script</code> - Enables capture of trace data for the <code>vm</code> module's <code>runInNewContext()</code>, <code>runInContext()</code>, and <code>runInThisContext()</code> methods.</li> <li><code>v8</code> - The <a href="v8.html">V8</a> events are GC, compiling, and execution related.</li> </ul> <p>By default the <code>node</code>, <code>node.async_hooks</code>, and <code>v8</code> categories are enabled.</p> <pre><code class="language-txt">node --trace-event-categories v8,node,node.async_hooks server.js </code></pre> <p>Prior versions of Node.js required the use of the <code>--trace-events-enabled</code> flag to enable trace events. This requirement has been removed. However, the <code>--trace-events-enabled</code> flag <em>may</em> still be used and will enable the <code>node</code>, <code>node.async_hooks</code>, and <code>v8</code> trace event categories by default.</p> <pre><code class="language-txt">node --trace-events-enabled // is equivalent to node --trace-event-categories v8,node,node.async_hooks </code></pre> <p>Alternatively, trace events may be enabled using the <code>trace_events</code> module:</p> <pre><code class="language-js">const trace_events = require('trace_events'); const tracing = trace_events.createTracing({ categories: ['node.perf'] }); tracing.enable(); // Enable trace event capture for the 'node.perf' category // do work tracing.disable(); // Disable trace event capture for the 'node.perf' category </code></pre> <p>Running Node.js with tracing enabled will produce log files that can be opened in the <a href="https://www.chromium.org/developers/how-tos/trace-event-profiling-tool"><code>chrome://tracing</code></a> tab of Chrome.</p> <p>The logging file is by default called <code>node_trace.${rotation}.log</code>, where <code>${rotation}</code> is an incrementing log-rotation id. The filepath pattern can be specified with <code>--trace-event-file-pattern</code> that accepts a template string that supports <code>${rotation}</code> and <code>${pid}</code>:</p> <pre><code class="language-txt">node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js </code></pre> <p>Starting with Node.js 10.0.0, the tracing system uses the same time source as the one used by <code>process.hrtime()</code> however the trace-event timestamps are expressed in microseconds, unlike <code>process.hrtime()</code> which returns nanoseconds.</p> <h2>The <code>trace_events</code> module<span><a class="mark" href="#tracing_the_trace_events_module" id="tracing_the_trace_events_module">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <h3><code>Tracing</code> object<span><a class="mark" href="#tracing_tracing_object" id="tracing_tracing_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>The <code>Tracing</code> object is used to enable or disable tracing for sets of categories. Instances are created using the <code>trace_events.createTracing()</code> method.</p> <p>When created, the <code>Tracing</code> object is disabled. Calling the <code>tracing.enable()</code> method adds the categories to the set of enabled trace event categories. Calling <code>tracing.disable()</code> will remove the categories from the set of enabled trace event categories.</p> <h4><code>tracing.categories</code><span><a class="mark" href="#tracing_tracing_categories" id="tracing_tracing_categories">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>A comma-separated list of the trace event categories covered by this <code>Tracing</code> object.</p> <h4><code>tracing.disable()</code><span><a class="mark" href="#tracing_tracing_disable" id="tracing_tracing_disable">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>Disables this <code>Tracing</code> object.</p> <p>Only trace event categories <em>not</em> covered by other enabled <code>Tracing</code> objects and <em>not</em> specified by the <code>--trace-event-categories</code> flag will be disabled.</p> <pre><code class="language-js">const trace_events = require('trace_events'); const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); t1.enable(); t2.enable(); // Prints 'node,node.perf,v8' console.log(trace_events.getEnabledCategories()); t2.disable(); // will only disable emission of the 'node.perf' category // Prints 'node,v8' console.log(trace_events.getEnabledCategories()); </code></pre> <h4><code>tracing.enable()</code><span><a class="mark" href="#tracing_tracing_enable" id="tracing_tracing_enable">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p>Enables this <code>Tracing</code> object for the set of categories covered by the <code>Tracing</code> object.</p> <h4><code>tracing.enabled</code><span><a class="mark" href="#tracing_tracing_enabled" id="tracing_tracing_enabled">#</a></span></h4> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> only if the <code>Tracing</code> object has been enabled.</li> </ul> <h3><code>trace_events.createTracing(options)</code><span><a class="mark" href="#tracing_trace_events_createtracing_options" id="tracing_trace_events_createtracing_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>categories</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array of trace category names. Values included in the array are coerced to a string when possible. An error will be thrown if the value cannot be coerced.</li> </ul> </li> <li>Returns: <a href="#tracing_tracing_object" class="type"><Tracing></a>.</li> </ul> <p>Creates and returns a <code>Tracing</code> object for the given set of <code>categories</code>.</p> <pre><code class="language-js">const trace_events = require('trace_events'); const categories = ['node.perf', 'node.async_hooks']; const tracing = trace_events.createTracing({ categories }); tracing.enable(); // do stuff tracing.disable(); </code></pre> <h3><code>trace_events.getEnabledCategories()</code><span><a class="mark" href="#tracing_trace_events_getenabledcategories" id="tracing_trace_events_getenabledcategories">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns a comma-separated list of all currently-enabled trace event categories. The current set of enabled trace event categories is determined by the <em>union</em> of all currently-enabled <code>Tracing</code> objects and any categories enabled using the <code>--trace-event-categories</code> flag.</p> <p>Given the file <code>test.js</code> below, the command <code>node --trace-event-categories node.perf test.js</code> will print <code>'node.async_hooks,node.perf'</code> to the console.</p> <pre><code class="language-js">const trace_events = require('trace_events'); const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); const t2 = trace_events.createTracing({ categories: ['node.perf'] }); const t3 = trace_events.createTracing({ categories: ['v8'] }); t1.enable(); t2.enable(); console.log(trace_events.getEnabledCategories()); </code></pre> <h1>TTY<span><a class="mark" href="#tty_tty" id="tty_tty">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>tty</code> module provides the <code>tty.ReadStream</code> and <code>tty.WriteStream</code> classes. In most cases, it will not be necessary or possible to use this module directly. However, it can be accessed using:</p> <pre><code class="language-js">const tty = require('tty'); </code></pre> <p>When Node.js detects that it is being run with a text terminal ("TTY") attached, <a href="#process_process_stdin"><code>process.stdin</code></a> will, by default, be initialized as an instance of <code>tty.ReadStream</code> and both <a href="#process_process_stdout"><code>process.stdout</code></a> and <a href="#process_process_stderr"><code>process.stderr</code></a> will, by default be instances of <code>tty.WriteStream</code>. The preferred method of determining whether Node.js is being run within a TTY context is to check that the value of the <code>process.stdout.isTTY</code> property is <code>true</code>:</p> <pre><code class="language-sh">$ node -p -e "Boolean(process.stdout.isTTY)" true $ node -p -e "Boolean(process.stdout.isTTY)" | cat false </code></pre> <p>In most cases, there should be little to no reason for an application to manually create instances of the <code>tty.ReadStream</code> and <code>tty.WriteStream</code> classes.</p> <h2>Class: tty.ReadStream<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/tty.js#L41">[src]</a><span><a class="mark" href="#tty_class_tty_readstream" id="tty_class_tty_readstream">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <p>The <code>tty.ReadStream</code> class is a subclass of <a href="#net_class_net_socket"><code>net.Socket</code></a> that represents the readable side of a TTY. In normal circumstances <a href="#process_process_stdin"><code>process.stdin</code></a> will be the only <code>tty.ReadStream</code> instance in a Node.js process and there should be no reason to create additional instances.</p> <h3>readStream.isRaw<span><a class="mark" href="#tty_readstream_israw" id="tty_readstream_israw">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <p>A <code>boolean</code> that is <code>true</code> if the TTY is currently configured to operate as a raw device. Defaults to <code>false</code>.</p> <h3>readStream.isTTY<span><a class="mark" href="#tty_readstream_istty" id="tty_readstream_istty">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <p>A <code>boolean</code> that is always <code>true</code> for <code>tty.ReadStream</code> instances.</p> <h3>readStream.setRawMode(mode)<span><a class="mark" href="#tty_readstream_setrawmode_mode" id="tty_readstream_setrawmode_mode">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, configures the <code>tty.ReadStream</code> to operate as a raw device. If <code>false</code>, configures the <code>tty.ReadStream</code> to operate in its default mode. The <code>readStream.isRaw</code> property will be set to the resulting mode.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type"><this></a> - the read stream instance.</li> </ul> <p>Allows configuration of <code>tty.ReadStream</code> so that it operates as a raw device.</p> <p>When in raw mode, input is always available character-by-character, not including modifiers. Additionally, all special processing of characters by the terminal is disabled, including echoing input characters. Note that <code>CTRL</code>+<code>C</code> will no longer cause a <code>SIGINT</code> when in this mode.</p> <h2>Class: tty.WriteStream<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/tty.js#L78">[src]</a><span><a class="mark" href="#tty_class_tty_writestream" id="tty_class_tty_writestream">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <p>The <code>tty.WriteStream</code> class is a subclass of <a href="#net_class_net_socket"><code>net.Socket</code></a> that represents the writable side of a TTY. In normal circumstances, <a href="#process_process_stdout"><code>process.stdout</code></a> and <a href="#process_process_stderr"><code>process.stderr</code></a> will be the only <code>tty.WriteStream</code> instances created for a Node.js process and there should be no reason to create additional instances.</p> <h3>Event: 'resize'<span><a class="mark" href="#tty_event_resize" id="tty_event_resize">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <p>The <code>'resize'</code> event is emitted whenever either of the <code>writeStream.columns</code> or <code>writeStream.rows</code> properties have changed. No arguments are passed to the listener callback when called.</p> <pre><code class="language-js">process.stdout.on('resize', () => { console.log('screen size has changed!'); console.log(`${process.stdout.columns}x${process.stdout.rows}`); }); </code></pre> <h3>writeStream.clearLine(dir)<span><a class="mark" href="#tty_writestream_clearline_dir" id="tty_writestream_clearline_dir">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li> <p><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></p> <ul> <li><code>-1</code> - to the left from cursor</li> <li><code>1</code> - to the right from cursor</li> <li><code>0</code> - the entire line</li> </ul> </li> </ul> <p><code>writeStream.clearLine()</code> clears the current line of this <code>WriteStream</code> in a direction identified by <code>dir</code>.</p> <h3>writeStream.clearScreenDown()<span><a class="mark" href="#tty_writestream_clearscreendown" id="tty_writestream_clearscreendown">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <p><code>writeStream.clearScreenDown()</code> clears this <code>WriteStream</code> from the current cursor down.</p> <h3>writeStream.columns<span><a class="mark" href="#tty_writestream_columns" id="tty_writestream_columns">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <p>A <code>number</code> specifying the number of columns the TTY currently has. This property is updated whenever the <code>'resize'</code> event is emitted.</p> <h3>writeStream.cursorTo(x, y)<span><a class="mark" href="#tty_writestream_cursorto_x_y" id="tty_writestream_cursorto_x_y">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><code>x</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>y</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p><code>writeStream.cursorTo()</code> moves this <code>WriteStream</code>'s cursor to the specified position.</p> <h3>writeStream.getColorDepth([env])<span><a class="mark" href="#tty_writestream_getcolordepth_env" id="tty_writestream_getcolordepth_env">#</a></span></h3> <div class="api_metadata"> <span>Added in: v9.9.0</span> </div> <ul> <li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing the environment variables to check. <strong>Default:</strong> <code>process.env</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Returns:</p> <ul> <li><code>1</code> for 2,</li> <li><code>4</code> for 16,</li> <li><code>8</code> for 256,</li> <li><code>24</code> for 16,777,216 colors supported.</li> </ul> <p>Use this to determine what colors the terminal supports. Due to the nature of colors in terminals it is possible to either have false positives or false negatives. It depends on process information and the environment variables that may lie about what terminal is used. To enforce a specific behavior without relying on <code>process.env</code> it is possible to pass in an object with different settings.</p> <p>Use the <code>NODE_DISABLE_COLORS</code> environment variable to enforce this function to always return 1.</p> <h3>writeStream.getWindowSize()<span><a class="mark" href="#tty_writestream_getwindowsize" id="tty_writestream_getwindowsize">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number[]></a></li> </ul> <p><code>writeStream.getWindowSize()</code> returns the size of the <a href="tty.html">TTY</a> corresponding to this <code>WriteStream</code>. The array is of the type <code>[numColumns, numRows]</code> where <code>numColumns</code> and <code>numRows</code> represent the number of columns and rows in the corresponding <a href="tty.html">TTY</a>.</p> <h3>writeStream.hasColors([count][, env])<span><a class="mark" href="#tty_writestream_hascolors_count_env" id="tty_writestream_hascolors_count_env">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> The number of colors that are requested (minimum 2). <strong>Default:</strong> 16.</li> <li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object containing the environment variables to check. This enables simulating the usage of a specific terminal. <strong>Default:</strong> <code>process.env</code>.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the <code>writeStream</code> supports at least as many colors as provided in <code>count</code>. Minimum support is 2 (black and white).</p> <p>This has the same false positives and negatives as described in <a href="#tty_writestream_getcolordepth_env"><code>writeStream.getColorDepth()</code></a>.</p> <pre><code class="language-js">process.stdout.hasColors(); // Returns true or false depending on if `stdout` supports at least 16 colors. process.stdout.hasColors(256); // Returns true or false depending on if `stdout` supports at least 256 colors. process.stdout.hasColors({ TMUX: '1' }); // Returns true. process.stdout.hasColors(2 ** 24, { TMUX: '1' }); // Returns false (the environment setting pretends to support 2 ** 8 colors). </code></pre> <h3>writeStream.isTTY<span><a class="mark" href="#tty_writestream_istty" id="tty_writestream_istty">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <p>A <code>boolean</code> that is always <code>true</code>.</p> <h3>writeStream.moveCursor(dx, dy)<span><a class="mark" href="#tty_writestream_movecursor_dx_dy" id="tty_writestream_movecursor_dx_dy">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <ul> <li><code>dx</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>dy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p><code>writeStream.moveCursor()</code> moves this <code>WriteStream</code>'s cursor <em>relative</em> to its current position.</p> <h3>writeStream.rows<span><a class="mark" href="#tty_writestream_rows" id="tty_writestream_rows">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.7</span> </div> <p>A <code>number</code> specifying the number of rows the TTY currently has. This property is updated whenever the <code>'resize'</code> event is emitted.</p> <h2>tty.isatty(fd)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/tty.js#L37">[src]</a><span><a class="mark" href="#tty_tty_isatty_fd" id="tty_tty_isatty_fd">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <ul> <li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> A numeric file descriptor</li> </ul> <p>The <code>tty.isatty()</code> method returns <code>true</code> if the given <code>fd</code> is associated with a TTY and <code>false</code> if it is not, including whenever <code>fd</code> is not a non-negative integer.</p> <h1>UDP/Datagram Sockets<span><a class="mark" href="#dgram_udp_datagram_sockets" id="dgram_udp_datagram_sockets">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>dgram</code> module provides an implementation of UDP Datagram sockets.</p> <pre><code class="language-js">const dgram = require('dgram'); const server = dgram.createSocket('udp4'); server.on('error', (err) => { console.log(`server error:\n${err.stack}`); server.close(); }); server.on('message', (msg, rinfo) => { console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); server.on('listening', () => { const address = server.address(); console.log(`server listening ${address.address}:${address.port}`); }); server.bind(41234); // server listening 0.0.0.0:41234 </code></pre> <h2>Class: dgram.Socket<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L70">[src]</a><span><a class="mark" href="#dgram_class_dgram_socket" id="dgram_class_dgram_socket">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <p>The <code>dgram.Socket</code> object is an <a href="events.html"><code>EventEmitter</code></a> that encapsulates the datagram functionality.</p> <p>New instances of <code>dgram.Socket</code> are created using <a href="#dgram_dgram_createsocket_options_callback"><code>dgram.createSocket()</code></a>. The <code>new</code> keyword is not to be used to create <code>dgram.Socket</code> instances.</p> <h3>Event: 'close'<span><a class="mark" href="#dgram_event_close" id="dgram_event_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <p>The <code>'close'</code> event is emitted after a socket is closed with <a href="#dgram_socket_close_callback"><code>close()</code></a>. Once triggered, no new <code>'message'</code> events will be emitted on this socket.</p> <h3>Event: 'error'<span><a class="mark" href="#dgram_event_error" id="dgram_event_error">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <ul> <li><code>exception</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>The <code>'error'</code> event is emitted whenever any error occurs. The event handler function is passed a single <code>Error</code> object.</p> <h3>Event: 'listening'<span><a class="mark" href="#dgram_event_listening" id="dgram_event_listening">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <p>The <code>'listening'</code> event is emitted whenever a socket begins listening for datagram messages. This occurs as soon as UDP sockets are created.</p> <h3>Event: 'message'<span><a class="mark" href="#dgram_event_message" id="dgram_event_message">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <p>The <code>'message'</code> event is emitted when a new datagram is available on a socket. The event handler function is passed two arguments: <code>msg</code> and <code>rinfo</code>.</p> <ul> <li><code>msg</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> The message.</li> <li> <p><code>rinfo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Remote address information.</p> <ul> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The sender address.</li> <li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The address family (<code>'IPv4'</code> or <code>'IPv6'</code>).</li> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The sender port.</li> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The message size.</li> </ul> </li> </ul> <h3>socket.addMembership(multicastAddress[, multicastInterface])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L570">[src]</a><span><a class="mark" href="#dgram_socket_addmembership_multicastaddress_multicastinterface" id="dgram_socket_addmembership_multicastaddress_multicastinterface">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.6.9</span> </div> <ul> <li><code>multicastAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Tells the kernel to join a multicast group at the given <code>multicastAddress</code> and <code>multicastInterface</code> using the <code>IP_ADD_MEMBERSHIP</code> socket option. If the <code>multicastInterface</code> argument is not specified, the operating system will choose one interface and will add membership to it. To add membership to every available interface, call <code>addMembership</code> multiple times, once per interface.</p> <p>When sharing a UDP socket across multiple <code>cluster</code> workers, the <code>socket.addMembership()</code> function must be called only once or an <code>EADDRINUSE</code> error will occur:</p> <pre><code class="language-js">const cluster = require('cluster'); const dgram = require('dgram'); if (cluster.isMaster) { cluster.fork(); // Works ok. cluster.fork(); // Fails with EADDRINUSE. } else { const s = dgram.createSocket('udp4'); s.bind(1234, () => { s.addMembership('224.0.0.114'); }); } </code></pre> <h3>socket.address()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L505">[src]</a><span><a class="mark" href="#dgram_socket_address" id="dgram_socket_address">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns an object containing the address information for a socket. For UDP sockets, this object will contain <code>address</code>, <code>family</code> and <code>port</code> properties.</p> <h3>socket.bind([port][, address][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L158">[src]</a><span><a class="mark" href="#dgram_socket_bind_port_address_callback" id="dgram_socket_bind_port_address_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <ul> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> with no parameters. Called when binding is complete.</li> </ul> <p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram messages on a named <code>port</code> and optional <code>address</code>. If <code>port</code> is not specified or is <code>0</code>, the operating system will attempt to bind to a random port. If <code>address</code> is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a <code>'listening'</code> event is emitted and the optional <code>callback</code> function is called.</p> <p>Note that specifying both a <code>'listening'</code> event listener and passing a <code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very useful.</p> <p>A bound datagram socket keeps the Node.js process running to receive datagram messages.</p> <p>If binding fails, an <code>'error'</code> event is generated. In rare case (e.g. attempting to bind with a closed socket), an <a href="#errors_class_error"><code>Error</code></a> may be thrown.</p> <p>Example of a UDP server listening on port 41234:</p> <pre><code class="language-js">const dgram = require('dgram'); const server = dgram.createSocket('udp4'); server.on('error', (err) => { console.log(`server error:\n${err.stack}`); server.close(); }); server.on('message', (msg, rinfo) => { console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); }); server.on('listening', () => { const address = server.address(); console.log(`server listening ${address.address}:${address.port}`); }); server.bind(41234); // server listening 0.0.0.0:41234 </code></pre> <h3>socket.bind(options[, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L158">[src]</a><span><a class="mark" href="#dgram_socket_bind_options_callback" id="dgram_socket_bind_options_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.14</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Required. Supports the following properties:</p> <ul> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> </li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>For UDP sockets, causes the <code>dgram.Socket</code> to listen for datagram messages on a named <code>port</code> and optional <code>address</code> that are passed as properties of an <code>options</code> object passed as the first argument. If <code>port</code> is not specified or is <code>0</code>, the operating system will attempt to bind to a random port. If <code>address</code> is not specified, the operating system will attempt to listen on all addresses. Once binding is complete, a <code>'listening'</code> event is emitted and the optional <code>callback</code> function is called.</p> <p>Note that specifying both a <code>'listening'</code> event listener and passing a <code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very useful.</p> <p>The <code>options</code> object may contain an additional <code>exclusive</code> property that is use when using <code>dgram.Socket</code> objects with the <a href="cluster.html"><code>cluster</code></a> module. When <code>exclusive</code> is set to <code>false</code> (the default), cluster workers will use the same underlying socket handle allowing connection handling duties to be shared. When <code>exclusive</code> is <code>true</code>, however, the handle is not shared and attempted port sharing results in an error.</p> <p>A bound datagram socket keeps the Node.js process running to receive datagram messages.</p> <p>If binding fails, an <code>'error'</code> event is generated. In rare case (e.g. attempting to bind with a closed socket), an <a href="#errors_class_error"><code>Error</code></a> may be thrown.</p> <p>An example socket listening on an exclusive port is shown below.</p> <pre><code class="language-js">socket.bind({ address: 'localhost', port: 8000, exclusive: true }); </code></pre> <h3>socket.close([callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L475">[src]</a><span><a class="mark" href="#dgram_socket_close_callback" id="dgram_socket_close_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called when the socket has been closed.</li> </ul> <p>Close the underlying socket and stop listening for data on it. If a callback is provided, it is added as a listener for the <a href="#dgram_event_close"><code>'close'</code></a> event.</p> <h3>socket.dropMembership(multicastAddress[, multicastInterface])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L586">[src]</a><span><a class="mark" href="#dgram_socket_dropmembership_multicastaddress_multicastinterface" id="dgram_socket_dropmembership_multicastaddress_multicastinterface">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.6.9</span> </div> <ul> <li><code>multicastAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Instructs the kernel to leave a multicast group at <code>multicastAddress</code> using the <code>IP_DROP_MEMBERSHIP</code> socket option. This method is automatically called by the kernel when the socket is closed or the process terminates, so most apps will never have reason to call this.</p> <p>If <code>multicastInterface</code> is not specified, the operating system will attempt to drop membership on all valid interfaces.</p> <h3>socket.getRecvBufferSize()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L662">[src]</a><span><a class="mark" href="#dgram_socket_getrecvbuffersize" id="dgram_socket_getrecvbuffersize">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.7.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the <code>SO_RCVBUF</code> socket receive buffer size in bytes.</li> </ul> <h3>socket.getSendBufferSize()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L667">[src]</a><span><a class="mark" href="#dgram_socket_getsendbuffersize" id="dgram_socket_getsendbuffersize">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.7.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> the <code>SO_SNDBUF</code> socket send buffer size in bytes.</li> </ul> <h3>socket.ref()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L632">[src]</a><span><a class="mark" href="#dgram_socket_ref" id="dgram_socket_ref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <p>By default, binding a socket will cause it to block the Node.js process from exiting as long as the socket is open. The <code>socket.unref()</code> method can be used to exclude the socket from the reference counting that keeps the Node.js process active. The <code>socket.ref()</code> method adds the socket back to the reference counting and restores the default behavior.</p> <p>Calling <code>socket.ref()</code> multiples times will have no additional effect.</p> <p>The <code>socket.ref()</code> method returns a reference to the socket so calls can be chained.</p> <h3>socket.send(msg[, offset, length], port[, address][, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L352">[src]</a><span><a class="mark" href="#dgram_socket_send_msg_offset_length_port_address_callback" id="dgram_socket_send_msg_offset_length_port_address_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>msg</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>address</code> parameter is always optional now.</p></td></tr> <tr><td>v6.0.0</td> <td><p>On success, <code>callback</code> will now be called with an <code>error</code> argument of <code>null</code> rather than <code>0</code>.</p></td></tr> <tr><td>v5.7.0</td> <td><p>The <code>msg</code> parameter can be an array now. Also, the <code>offset</code> and <code>length</code> parameters are optional now.</p></td></tr> <tr><td>v0.1.99</td> <td><p><span>Added in: v0.1.99</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>msg</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Message to be sent.</li> <li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Offset in the buffer where the message starts.</li> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Number of bytes in the message.</li> <li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Destination port.</li> <li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Destination hostname or IP address.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called when the message has been sent.</li> </ul> <p>Broadcasts a datagram on the socket. The destination <code>port</code> and <code>address</code> must be specified.</p> <p>The <code>msg</code> argument contains the message to be sent. Depending on its type, different behavior can apply. If <code>msg</code> is a <code>Buffer</code> or <code>Uint8Array</code>, the <code>offset</code> and <code>length</code> specify the offset within the <code>Buffer</code> where the message begins and the number of bytes in the message, respectively. If <code>msg</code> is a <code>String</code>, then it is automatically converted to a <code>Buffer</code> with <code>'utf8'</code> encoding. With messages that contain multi-byte characters, <code>offset</code> and <code>length</code> will be calculated with respect to <a href="#buffer_class_method_buffer_bytelength_string_encoding">byte length</a> and not the character position. If <code>msg</code> is an array, <code>offset</code> and <code>length</code> must not be specified.</p> <p>The <code>address</code> argument is a string. If the value of <code>address</code> is a host name, DNS will be used to resolve the address of the host. If <code>address</code> is not provided or otherwise falsy, <code>'127.0.0.1'</code> (for <code>udp4</code> sockets) or <code>'::1'</code> (for <code>udp6</code> sockets) will be used by default.</p> <p>If the socket has not been previously bound with a call to <code>bind</code>, the socket is assigned a random port number and is bound to the "all interfaces" address (<code>'0.0.0.0'</code> for <code>udp4</code> sockets, <code>'::0'</code> for <code>udp6</code> sockets.)</p> <p>An optional <code>callback</code> function may be specified to as a way of reporting DNS errors or for determining when it is safe to reuse the <code>buf</code> object. Note that DNS lookups delay the time to send for at least one tick of the Node.js event loop.</p> <p>The only way to know for sure that the datagram has been sent is by using a <code>callback</code>. If an error occurs and a <code>callback</code> is given, the error will be passed as the first argument to the <code>callback</code>. If a <code>callback</code> is not given, the error is emitted as an <code>'error'</code> event on the <code>socket</code> object.</p> <p>Offset and length are optional but both <em>must</em> be set if either are used. They are supported only when the first argument is a <code>Buffer</code> or <code>Uint8Array</code>.</p> <p>Example of sending a UDP packet to a port on <code>localhost</code>;</p> <pre><code class="language-js">const dgram = require('dgram'); const message = Buffer.from('Some bytes'); const client = dgram.createSocket('udp4'); client.send(message, 41234, 'localhost', (err) => { client.close(); }); </code></pre> <p>Example of sending a UDP packet composed of multiple buffers to a port on <code>127.0.0.1</code>;</p> <pre><code class="language-js">const dgram = require('dgram'); const buf1 = Buffer.from('Some '); const buf2 = Buffer.from('bytes'); const client = dgram.createSocket('udp4'); client.send([buf1, buf2], 41234, (err) => { client.close(); }); </code></pre> <p>Sending multiple buffers might be faster or slower depending on the application and operating system. It is important to run benchmarks to determine the optimal strategy on a case-by-case basis. Generally speaking, however, sending multiple buffers is faster.</p> <p><strong>A Note about UDP datagram size</strong></p> <p>The maximum size of an <code>IPv4/v6</code> datagram depends on the <code>MTU</code> (<em>Maximum Transmission Unit</em>) and on the <code>Payload Length</code> field size.</p> <ul> <li> <p>The <code>Payload Length</code> field is <code>16 bits</code> wide, which means that a normal payload exceed 64K octets <em>including</em> the internet header and data (65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header); this is generally true for loopback interfaces, but such long datagram messages are impractical for most hosts and networks.</p> </li> <li> <p>The <code>MTU</code> is the largest size a given link layer technology can support for datagram messages. For any link, <code>IPv4</code> mandates a minimum <code>MTU</code> of <code>68</code> octets, while the recommended <code>MTU</code> for IPv4 is <code>576</code> (typically recommended as the <code>MTU</code> for dial-up type applications), whether they arrive whole or in fragments.</p> <p>For <code>IPv6</code>, the minimum <code>MTU</code> is <code>1280</code> octets, however, the mandatory minimum fragment reassembly buffer size is <code>1500</code> octets. The value of <code>68</code> octets is very small, since most current link layer technologies, like Ethernet, have a minimum <code>MTU</code> of <code>1500</code>.</p> </li> </ul> <p>It is impossible to know in advance the MTU of each link through which a packet might travel. Sending a datagram greater than the receiver <code>MTU</code> will not work because the packet will get silently dropped without informing the source that the data did not reach its intended recipient.</p> <h3>socket.setBroadcast(flag)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L518">[src]</a><span><a class="mark" href="#dgram_socket_setbroadcast_flag" id="dgram_socket_setbroadcast_flag">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.6.9</span> </div> <ul> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Sets or clears the <code>SO_BROADCAST</code> socket option. When set to <code>true</code>, UDP packets may be sent to a local interface's broadcast address.</p> <h3>socket.setMulticastInterface(multicastInterface)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L560">[src]</a><span><a class="mark" href="#dgram_socket_setmulticastinterface_multicastinterface" id="dgram_socket_setmulticastinterface_multicastinterface">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.6.0</span> </div> <ul> <li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p><em>All references to scope in this section are referring to <a href="https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses">IPv6 Zone Indices</a>, which are defined by <a href="https://tools.ietf.org/html/rfc4007">RFC 4007</a>. In string form, an IP with a scope index is written as <code>'IP%scope'</code> where scope is an interface name or interface number.</em></p> <p>Sets the default outgoing multicast interface of the socket to a chosen interface or back to system interface selection. The <code>multicastInterface</code> must be a valid string representation of an IP from the socket's family.</p> <p>For IPv4 sockets, this should be the IP configured for the desired physical interface. All packets sent to multicast on the socket will be sent on the interface determined by the most recent successful use of this call.</p> <p>For IPv6 sockets, <code>multicastInterface</code> should include a scope to indicate the interface as in the examples that follow. In IPv6, individual <code>send</code> calls can 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.</p> <h4>Examples: IPv6 Outgoing Multicast Interface<span><a class="mark" href="#dgram_examples_ipv6_outgoing_multicast_interface" id="dgram_examples_ipv6_outgoing_multicast_interface">#</a></span></h4> <p>On most systems, where scope format uses the interface name:</p> <pre><code class="language-js">const socket = dgram.createSocket('udp6'); socket.bind(1234, () => { socket.setMulticastInterface('::%eth1'); }); </code></pre> <p>On Windows, where scope format uses an interface number:</p> <pre><code class="language-js">const socket = dgram.createSocket('udp6'); socket.bind(1234, () => { socket.setMulticastInterface('::%2'); }); </code></pre> <h4>Example: IPv4 Outgoing Multicast Interface<span><a class="mark" href="#dgram_example_ipv4_outgoing_multicast_interface" id="dgram_example_ipv4_outgoing_multicast_interface">#</a></span></h4> <p>All systems use an IP of the host on the desired physical interface:</p> <pre><code class="language-js">const socket = dgram.createSocket('udp4'); socket.bind(1234, () => { socket.setMulticastInterface('10.0.0.2'); }); </code></pre> <h4>Call Results<span><a class="mark" href="#dgram_call_results" id="dgram_call_results">#</a></span></h4> <p>A call on a socket that is not ready to send or no longer open may throw a <em>Not running</em> <a href="#errors_class_error"><code>Error</code></a>.</p> <p>If <code>multicastInterface</code> can not be parsed into an IP then an <em>EINVAL</em> <a href="#errors_class_systemerror"><code>System Error</code></a> is thrown.</p> <p>On IPv4, if <code>multicastInterface</code> is a valid address but does not match any interface, or if the address does not match the family then a <a href="#errors_class_systemerror"><code>System Error</code></a> such as <code>EADDRNOTAVAIL</code> or <code>EPROTONOSUP</code> is thrown.</p> <p>On IPv6, most errors with specifying or omitting scope will result in the socket continuing to use (or returning to) the system's default interface selection.</p> <p>A socket's address family's ANY address (IPv4 <code>'0.0.0.0'</code> or IPv6 <code>'::'</code>) can be used to return control of the sockets default outgoing interface to the system for future multicast packets.</p> <h3>socket.setMulticastLoopback(flag)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L550">[src]</a><span><a class="mark" href="#dgram_socket_setmulticastloopback_flag" id="dgram_socket_setmulticastloopback_flag">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.8</span> </div> <ul> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Sets or clears the <code>IP_MULTICAST_LOOP</code> socket option. When set to <code>true</code>, multicast packets will also be received on the local interface.</p> <h3>socket.setMulticastTTL(ttl)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L538">[src]</a><span><a class="mark" href="#dgram_socket_setmulticastttl_ttl" id="dgram_socket_setmulticastttl_ttl">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.8</span> </div> <ul> <li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Sets the <code>IP_MULTICAST_TTL</code> socket option. While TTL generally stands for "Time to Live", in this context it specifies the number of IP hops that a packet is allowed to travel through, specifically for multicast traffic. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.</p> <p>The argument passed to <code>socket.setMulticastTTL()</code> is a number of hops between 0 and 255. The default on most systems is <code>1</code> but can vary.</p> <h3>socket.setRecvBufferSize(size)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L652">[src]</a><span><a class="mark" href="#dgram_socket_setrecvbuffersize_size" id="dgram_socket_setrecvbuffersize_size">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.7.0</span> </div> <ul> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Sets the <code>SO_RCVBUF</code> socket option. Sets the maximum socket receive buffer in bytes.</p> <h3>socket.setSendBufferSize(size)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L657">[src]</a><span><a class="mark" href="#dgram_socket_setsendbuffersize_size" id="dgram_socket_setsendbuffersize_size">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.7.0</span> </div> <ul> <li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Sets the <code>SO_SNDBUF</code> socket option. Sets the maximum socket send buffer in bytes.</p> <h3>socket.setTTL(ttl)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L526">[src]</a><span><a class="mark" href="#dgram_socket_setttl_ttl" id="dgram_socket_setttl_ttl">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.101</span> </div> <ul> <li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Sets the <code>IP_TTL</code> socket option. While TTL generally stands for "Time to Live", in this context it specifies the number of IP hops that a packet is allowed to travel through. Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. Changing TTL values is typically done for network probes or when multicasting.</p> <p>The argument to <code>socket.setTTL()</code> is a number of hops between 1 and 255. The default on most systems is 64 but can vary.</p> <h3>socket.unref()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L642">[src]</a><span><a class="mark" href="#dgram_socket_unref" id="dgram_socket_unref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.1</span> </div> <p>By default, binding a socket will cause it to block the Node.js process from exiting as long as the socket is open. The <code>socket.unref()</code> method can be used to exclude the socket from the reference counting that keeps the Node.js process active, allowing the process to exit even if the socket is still listening.</p> <p>Calling <code>socket.unref()</code> multiple times will have no addition effect.</p> <p>The <code>socket.unref()</code> method returns a reference to the socket so calls can be chained.</p> <h3>Change to asynchronous <code>socket.bind()</code> behavior<span><a class="mark" href="#dgram_change_to_asynchronous_socket_bind_behavior" id="dgram_change_to_asynchronous_socket_bind_behavior">#</a></span></h3> <p>As of Node.js v0.10, <a href="#dgram_socket_bind_options_callback"><code>dgram.Socket#bind()</code></a> changed to an asynchronous execution model. Legacy code would use synchronous behavior:</p> <pre><code class="language-js">const s = dgram.createSocket('udp4'); s.bind(1234); s.addMembership('224.0.0.114'); </code></pre> <p>Such legacy code would need to be changed to pass a callback function to the <a href="#dgram_socket_bind_options_callback"><code>dgram.Socket#bind()</code></a> function:</p> <pre><code class="language-js">const s = dgram.createSocket('udp4'); s.bind(1234, () => { s.addMembership('224.0.0.114'); }); </code></pre> <h2><code>dgram</code> module functions<span><a class="mark" href="#dgram_dgram_module_functions" id="dgram_dgram_module_functions">#</a></span></h2> <h3>dgram.createSocket(options[, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L107">[src]</a><span><a class="mark" href="#dgram_dgram_createsocket_options_callback" id="dgram_dgram_createsocket_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.7.0</td> <td><p>The <code>recvBufferSize</code> and <code>sendBufferSize</code> options are supported now.</p></td></tr> <tr><td>v8.6.0</td> <td><p>The <code>lookup</code> option is supported.</p></td></tr> <tr><td>v0.11.13</td> <td><p><span>Added in: v0.11.13</span></p></td></tr> </tbody></table> </details> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Available options are:</p> <ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The family of socket. Must be either <code>'udp4'</code> or <code>'udp6'</code>. Required.</li> <li><code>reuseAddr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will reuse the address, even if another process has already bound a socket on it. <strong>Default:</strong> <code>false</code>.</li> <li><code>recvBufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> - Sets the <code>SO_RCVBUF</code> socket value.</li> <li><code>sendBufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> - Sets the <code>SO_SNDBUF</code> socket value.</li> <li><code>lookup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Custom lookup function. <strong>Default:</strong> <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li> </ul> </li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Attached as a listener for <code>'message'</code> events. Optional.</li> <li>Returns: <a href="#dgram_class_dgram_socket" class="type"><dgram.Socket></a></li> </ul> <p>Creates a <code>dgram.Socket</code> object. Once the socket is created, calling <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will instruct the socket to begin listening for datagram messages. When <code>address</code> and <code>port</code> are not passed to <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> the method will bind the socket to the "all interfaces" address on a random port (it does the right thing for both <code>udp4</code> and <code>udp6</code> sockets). The bound address and port can be retrieved using <a href="#dgram_socket_address"><code>socket.address().address</code></a> and <a href="#dgram_socket_address"><code>socket.address().port</code></a>.</p> <h3>dgram.createSocket(type[, callback])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/dgram.js#L107">[src]</a><span><a class="mark" href="#dgram_dgram_createsocket_type_callback" id="dgram_dgram_createsocket_type_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.1.99</span> </div> <ul> <li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> - Either <code>'udp4'</code> or <code>'udp6'</code>.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> - Attached as a listener to <code>'message'</code> events.</li> <li>Returns: <a href="#dgram_class_dgram_socket" class="type"><dgram.Socket></a></li> </ul> <p>Creates a <code>dgram.Socket</code> object of the specified <code>type</code>. The <code>type</code> argument can be either <code>'udp4'</code> or <code>'udp6'</code>. An optional <code>callback</code> function can be passed which is added as a listener for <code>'message'</code> events.</p> <p>Once the socket is created, calling <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will instruct the socket to begin listening for datagram messages. When <code>address</code> and <code>port</code> are not passed to <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> the method will bind the socket to the "all interfaces" address on a random port (it does the right thing for both <code>udp4</code> and <code>udp6</code> sockets). The bound address and port can be retrieved using <a href="#dgram_socket_address"><code>socket.address().address</code></a> and <a href="#dgram_socket_address"><code>socket.address().port</code></a>.</p> <h1>URL<span><a class="mark" href="#url_url" id="url_url">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>url</code> module provides utilities for URL resolution and parsing. It can be accessed using:</p> <pre><code class="language-js">const url = require('url'); </code></pre> <h2>URL Strings and URL Objects<span><a class="mark" href="#url_url_strings_and_url_objects" id="url_url_strings_and_url_objects">#</a></span></h2> <p>A URL string is a structured string containing multiple meaningful components. When parsed, a URL object is returned containing properties for each of these components.</p> <p>The <code>url</code> module provides two APIs for working with URLs: a legacy API that is Node.js specific, and a newer API that implements the same <a href="https://url.spec.whatwg.org/">WHATWG URL Standard</a> used by web browsers.</p> <p>While the Legacy API has not been deprecated, it is maintained solely for backwards compatibility with existing applications. New application code should use the WHATWG API.</p> <p>A comparison between the WHATWG and Legacy APIs is provided below. Above the URL <code>'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</code>, properties of an object returned by the legacy <code>url.parse()</code> are shown. Below it are properties of a WHATWG <code>URL</code> object.</p> <p>WHATWG URL's <code>origin</code> property includes <code>protocol</code> and <code>host</code>, but not <code>username</code> or <code>password</code>.</p> <pre><code class="language-txt">┌────────────────────────────────────────────────────────────────────────────────────────────────┐ │ href │ ├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤ │ protocol │ │ auth │ host │ path │ hash │ │ │ │ ├─────────────────┬──────┼──────────┬────────────────┤ │ │ │ │ │ hostname │ port │ pathname │ search │ │ │ │ │ │ │ │ ├─┬──────────────┤ │ │ │ │ │ │ │ │ │ query │ │ " https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string #hash " │ │ │ │ │ hostname │ port │ │ │ │ │ │ │ │ ├─────────────────┴──────┤ │ │ │ │ protocol │ │ username │ password │ host │ │ │ │ ├──────────┴──┼──────────┴──────────┼────────────────────────┤ │ │ │ │ origin │ │ origin │ pathname │ search │ hash │ ├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤ │ href │ └────────────────────────────────────────────────────────────────────────────────────────────────┘ (All spaces in the "" line should be ignored. They are purely for formatting.) </code></pre> <p>Parsing the URL string using the WHATWG API:</p> <pre><code class="language-js">const myURL = new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'); </code></pre> <p>Parsing the URL string using the Legacy API:</p> <pre><code class="language-js">const url = require('url'); const myURL = url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'); </code></pre> <h2>The WHATWG URL API<span><a class="mark" href="#url_the_whatwg_url_api" id="url_the_whatwg_url_api">#</a></span></h2> <h3>Class: URL<span><a class="mark" href="#url_class_url" id="url_class_url">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The class is now available on the global object.</p></td></tr> <tr><td>v7.0.0, v6.13.0</td> <td><p><span>Added in: v7.0.0, v6.13.0</span></p></td></tr> </tbody></table> </details> </div> <p>Browser-compatible <code>URL</code> class, implemented by following the WHATWG URL Standard. <a href="https://url.spec.whatwg.org/#example-url-parsing">Examples of parsed URLs</a> may be found in the Standard itself. The <code>URL</code> class is also available on the global object.</p> <p>In accordance with browser conventions, all properties of <code>URL</code> objects are implemented as getters and setters on the class prototype, rather than as data properties on the object itself. Thus, unlike <a href="#url_legacy_urlobject">legacy <code>urlObject</code></a>s, using the <code>delete</code> keyword on any properties of <code>URL</code> objects (e.g. <code>delete myURL.protocol</code>, <code>delete myURL.pathname</code>, etc) has no effect but will still return <code>true</code>.</p> <h4>Constructor: new URL(input[, base])<span><a class="mark" href="#url_constructor_new_url_input_base" id="url_constructor_new_url_input_base">#</a></span></h4> <ul> <li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The absolute or relative input URL to parse. If <code>input</code> is relative, then <code>base</code> is required. If <code>input</code> is absolute, the <code>base</code> is ignored.</li> <li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="#url_the_whatwg_url_api" class="type"><URL></a> The base URL to resolve against if the <code>input</code> is not absolute.</li> </ul> <p>Creates a new <code>URL</code> object by parsing the <code>input</code> relative to the <code>base</code>. If <code>base</code> is passed as a string, it will be parsed equivalent to <code>new URL(base)</code>.</p> <pre><code class="language-js">const myURL = new URL('/foo', 'https://example.org/'); // https://example.org/foo </code></pre> <p>A <code>TypeError</code> will be thrown if the <code>input</code> or <code>base</code> are not valid URLs. Note that an effort will be made to coerce the given values into strings. For instance:</p> <pre><code class="language-js">const myURL = new URL({ toString: () => 'https://example.org/' }); // https://example.org/ </code></pre> <p>Unicode characters appearing within the hostname of <code>input</code> will be automatically converted to ASCII using the <a href="https://tools.ietf.org/html/rfc5891#section-4.4">Punycode</a> algorithm.</p> <pre><code class="language-js">const myURL = new URL('https://測試'); // https://xn--g6w251d/ </code></pre> <p>This feature is only available if the <code>node</code> executable was compiled with <a href="#intl_options_for_building_node_js">ICU</a> enabled. If not, the domain names are passed through unchanged.</p> <p>In cases where it is not known in advance if <code>input</code> is an absolute URL and a <code>base</code> is provided, it is advised to validate that the <code>origin</code> of the <code>URL</code> object is what is expected.</p> <pre><code class="language-js">let myURL = new URL('http://Example.com/', 'https://example.org/'); // http://example.com/ myURL = new URL('https://Example.com/', 'https://example.org/'); // https://example.com/ myURL = new URL('foo://Example.com/', 'https://example.org/'); // foo://Example.com/ myURL = new URL('http:Example.com/', 'https://example.org/'); // http://example.com/ myURL = new URL('https:Example.com/', 'https://example.org/'); // https://example.org/Example.com/ myURL = new URL('foo:Example.com/', 'https://example.org/'); // foo:Example.com/ </code></pre> <h4>url.hash<span><a class="mark" href="#url_url_hash" id="url_url_hash">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Gets and sets the fragment portion of the URL.</p> <pre><code class="language-js">const myURL = new URL('https://example.org/foo#bar'); console.log(myURL.hash); // Prints #bar myURL.hash = 'baz'; console.log(myURL.href); // Prints https://example.org/foo#baz </code></pre> <p>Invalid URL characters included in the value assigned to the <code>hash</code> property are <a href="#whatwg-percent-encoding">percent-encoded</a>. Note that the selection of which characters to percent-encode may vary somewhat from what the <a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a> and <a href="#url_url_format_urlobject"><code>url.format()</code></a> methods would produce.</p> <h4>url.host<span><a class="mark" href="#url_url_host" id="url_url_host">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Gets and sets the host portion of the URL.</p> <pre><code class="language-js">const myURL = new URL('https://example.org:81/foo'); console.log(myURL.host); // Prints example.org:81 myURL.host = 'example.com:82'; console.log(myURL.href); // Prints https://example.com:82/foo </code></pre> <p>Invalid host values assigned to the <code>host</code> property are ignored.</p> <h4>url.hostname<span><a class="mark" href="#url_url_hostname" id="url_url_hostname">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Gets and sets the hostname portion of the URL. The key difference between <code>url.host</code> and <code>url.hostname</code> is that <code>url.hostname</code> does <em>not</em> include the port.</p> <pre><code class="language-js">const myURL = new URL('https://example.org:81/foo'); console.log(myURL.hostname); // Prints example.org myURL.hostname = 'example.com:82'; console.log(myURL.href); // Prints https://example.com:81/foo </code></pre> <p>Invalid hostname values assigned to the <code>hostname</code> property are ignored.</p> <h4>url.href<span><a class="mark" href="#url_url_href" id="url_url_href">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Gets and sets the serialized URL.</p> <pre><code class="language-js">const myURL = new URL('https://example.org/foo'); console.log(myURL.href); // Prints https://example.org/foo myURL.href = 'https://example.com/bar'; console.log(myURL.href); // Prints https://example.com/bar </code></pre> <p>Getting the value of the <code>href</code> property is equivalent to calling <a href="#url_url_tostring"><code>url.toString()</code></a>.</p> <p>Setting the value of this property to a new value is equivalent to creating a new <code>URL</code> object using <a href="#url_constructor_new_url_input_base"><code>new URL(value)</code></a>. Each of the <code>URL</code> object's properties will be modified.</p> <p>If the value assigned to the <code>href</code> property is not a valid URL, a <code>TypeError</code> will be thrown.</p> <h4>url.origin<span><a class="mark" href="#url_url_origin" id="url_url_origin">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Gets the read-only serialization of the URL's origin.</p> <pre><code class="language-js">const myURL = new URL('https://example.org/foo/bar?baz'); console.log(myURL.origin); // Prints https://example.org </code></pre> <pre><code class="language-js">const idnURL = new URL('https://測試'); console.log(idnURL.origin); // Prints https://xn--g6w251d console.log(idnURL.hostname); // Prints xn--g6w251d </code></pre> <h4>url.password<span><a class="mark" href="#url_url_password" id="url_url_password">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Gets and sets the password portion of the URL.</p> <pre><code class="language-js">const myURL = new URL('https://abc:xyz@example.com'); console.log(myURL.password); // Prints xyz myURL.password = '123'; console.log(myURL.href); // Prints https://abc:123@example.com </code></pre> <p>Invalid URL characters included in the value assigned to the <code>password</code> property are <a href="#whatwg-percent-encoding">percent-encoded</a>. Note that the selection of which characters to percent-encode may vary somewhat from what the <a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a> and <a href="#url_url_format_urlobject"><code>url.format()</code></a> methods would produce.</p> <h4>url.pathname<span><a class="mark" href="#url_url_pathname" id="url_url_pathname">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Gets and sets the path portion of the URL.</p> <pre><code class="language-js">const myURL = new URL('https://example.org/abc/xyz?123'); console.log(myURL.pathname); // Prints /abc/xyz myURL.pathname = '/abcdef'; console.log(myURL.href); // Prints https://example.org/abcdef?123 </code></pre> <p>Invalid URL characters included in the value assigned to the <code>pathname</code> property are <a href="#whatwg-percent-encoding">percent-encoded</a>. Note that the selection of which characters to percent-encode may vary somewhat from what the <a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a> and <a href="#url_url_format_urlobject"><code>url.format()</code></a> methods would produce.</p> <h4>url.port<span><a class="mark" href="#url_url_port" id="url_url_port">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Gets and sets the port portion of the URL.</p> <p>The port value may be a number or a string containing a number in the range <code>0</code> to <code>65535</code> (inclusive). Setting the value to the default port of the <code>URL</code> objects given <code>protocol</code> will result in the <code>port</code> value becoming the empty string (<code>''</code>).</p> <p>The port value can be an empty string in which case the port depends on the protocol/scheme:</p> <table><thead><tr><th align="left">protocol</th><th align="left">port</th></tr></thead><tbody><tr><td align="left">"ftp"</td><td align="left">21</td></tr><tr><td align="left">"file"</td><td align="left"></td></tr><tr><td align="left">"gopher"</td><td align="left">70</td></tr><tr><td align="left">"http"</td><td align="left">80</td></tr><tr><td align="left">"https"</td><td align="left">443</td></tr><tr><td align="left">"ws"</td><td align="left">80</td></tr><tr><td align="left">"wss"</td><td align="left">443</td></tr></tbody></table> <p>Upon assigning a value to the port, the value will first be converted to a string using <code>.toString()</code>.</p> <p>If that string is invalid but it begins with a number, the leading number is assigned to <code>port</code>. If the number lies outside the range denoted above, it is ignored.</p> <pre><code class="language-js">const myURL = new URL('https://example.org:8888'); console.log(myURL.port); // Prints 8888 // Default ports are automatically transformed to the empty string // (HTTPS protocol's default port is 443) myURL.port = '443'; console.log(myURL.port); // Prints the empty string console.log(myURL.href); // Prints https://example.org/ myURL.port = 1234; console.log(myURL.port); // Prints 1234 console.log(myURL.href); // Prints https://example.org:1234/ // Completely invalid port strings are ignored myURL.port = 'abcd'; console.log(myURL.port); // Prints 1234 // Leading numbers are treated as a port number myURL.port = '5678abcd'; console.log(myURL.port); // Prints 5678 // Non-integers are truncated myURL.port = 1234.5678; console.log(myURL.port); // Prints 1234 // Out-of-range numbers which are not represented in scientific notation // will be ignored. myURL.port = 1e10; // 10000000000, will be range-checked as described below console.log(myURL.port); // Prints 1234 </code></pre> <p>Note that numbers which contain a decimal point, such as floating-point numbers or numbers in scientific notation, are not an exception to this rule. Leading numbers up to the decimal point will be set as the URL's port, assuming they are valid:</p> <pre><code class="language-js">myURL.port = 4.567e21; console.log(myURL.port); // Prints 4 (because it is the leading number in the string '4.567e21') </code></pre> <h4>url.protocol<span><a class="mark" href="#url_url_protocol" id="url_url_protocol">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Gets and sets the protocol portion of the URL.</p> <pre><code class="language-js">const myURL = new URL('https://example.org'); console.log(myURL.protocol); // Prints https: myURL.protocol = 'ftp'; console.log(myURL.href); // Prints ftp://example.org/ </code></pre> <p>Invalid URL protocol values assigned to the <code>protocol</code> property are ignored.</p> <h5>Special Schemes<span><a class="mark" href="#url_special_schemes" id="url_special_schemes">#</a></span></h5> <p>The <a href="https://url.spec.whatwg.org/">WHATWG URL Standard</a> considers a handful of URL protocol schemes to be <em>special</em> in terms of how they are parsed and serialized. When a URL is parsed using one of these special protocols, the <code>url.protocol</code> property may be changed to another special protocol but cannot be changed to a non-special protocol, and vice versa.</p> <p>For instance, changing from <code>http</code> to <code>https</code> works:</p> <pre><code class="language-js">const u = new URL('http://example.org'); u.protocol = 'https'; console.log(u.href); // https://example.org </code></pre> <p>However, changing from <code>http</code> to a hypothetical <code>fish</code> protocol does not because the new protocol is not special.</p> <pre><code class="language-js">const u = new URL('http://example.org'); u.protocol = 'fish'; console.log(u.href); // http://example.org </code></pre> <p>Likewise, changing from a non-special protocol to a special protocol is also not permitted:</p> <pre><code class="language-js">const u = new URL('fish://example.org'); u.protocol = 'http'; console.log(u.href); // fish://example.org </code></pre> <p>The protocol schemes considered to be special by the WHATWG URL Standard include: <code>ftp</code>, <code>file</code>, <code>gopher</code>, <code>http</code>, <code>https</code>, <code>ws</code>, and <code>wss</code>.</p> <h4>url.search<span><a class="mark" href="#url_url_search" id="url_url_search">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Gets and sets the serialized query portion of the URL.</p> <pre><code class="language-js">const myURL = new URL('https://example.org/abc?123'); console.log(myURL.search); // Prints ?123 myURL.search = 'abc=xyz'; console.log(myURL.href); // Prints https://example.org/abc?abc=xyz </code></pre> <p>Any invalid URL characters appearing in the value assigned the <code>search</code> property will be <a href="#whatwg-percent-encoding">percent-encoded</a>. Note that the selection of which characters to percent-encode may vary somewhat from what the <a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a> and <a href="#url_url_format_urlobject"><code>url.format()</code></a> methods would produce.</p> <h4>url.searchParams<span><a class="mark" href="#url_url_searchparams" id="url_url_searchparams">#</a></span></h4> <ul> <li><a href="#url_class_urlsearchparams" class="type"><URLSearchParams></a></li> </ul> <p>Gets the <a href="#url_class_urlsearchparams"><code>URLSearchParams</code></a> object representing the query parameters of the URL. This property is read-only; to replace the entirety of query parameters of the URL, use the <a href="#url_url_search"><code>url.search</code></a> setter. See <a href="#url_class_urlsearchparams"><code>URLSearchParams</code></a> documentation for details.</p> <h4>url.username<span><a class="mark" href="#url_url_username" id="url_url_username">#</a></span></h4> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Gets and sets the username portion of the URL.</p> <pre><code class="language-js">const myURL = new URL('https://abc:xyz@example.com'); console.log(myURL.username); // Prints abc myURL.username = '123'; console.log(myURL.href); // Prints https://123:xyz@example.com/ </code></pre> <p>Any invalid URL characters appearing in the value assigned the <code>username</code> property will be <a href="#whatwg-percent-encoding">percent-encoded</a>. Note that the selection of which characters to percent-encode may vary somewhat from what the <a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a> and <a href="#url_url_format_urlobject"><code>url.format()</code></a> methods would produce.</p> <h4>url.toString()<span><a class="mark" href="#url_url_tostring" id="url_url_tostring">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>toString()</code> method on the <code>URL</code> object returns the serialized URL. The value returned is equivalent to that of <a href="#url_url_href"><code>url.href</code></a> and <a href="#url_url_tojson"><code>url.toJSON()</code></a>.</p> <p>Because of the need for standard compliance, this method does not allow users to customize the serialization process of the URL. For more flexibility, <a href="#url_url_format_url_options"><code>require('url').format()</code></a> method might be of interest.</p> <h4>url.toJSON()<span><a class="mark" href="#url_url_tojson" id="url_url_tojson">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>toJSON()</code> method on the <code>URL</code> object returns the serialized URL. The value returned is equivalent to that of <a href="#url_url_href"><code>url.href</code></a> and <a href="#url_url_tostring"><code>url.toString()</code></a>.</p> <p>This method is automatically called when an <code>URL</code> object is serialized with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify"><code>JSON.stringify()</code></a>.</p> <pre><code class="language-js">const myURLs = [ new URL('https://www.example.com'), new URL('https://test.example.org') ]; console.log(JSON.stringify(myURLs)); // Prints ["https://www.example.com/","https://test.example.org/"] </code></pre> <h3>Class: URLSearchParams<span><a class="mark" href="#url_class_urlsearchparams" id="url_class_urlsearchparams">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The class is now available on the global object.</p></td></tr> <tr><td>v7.5.0, v6.13.0</td> <td><p><span>Added in: v7.5.0, v6.13.0</span></p></td></tr> </tbody></table> </details> </div> <p>The <code>URLSearchParams</code> API provides read and write access to the query of a <code>URL</code>. The <code>URLSearchParams</code> class can also be used standalone with one of the four following constructors. The <code>URLSearchParams</code> class is also available on the global object.</p> <p>The WHATWG <code>URLSearchParams</code> interface and the <a href="querystring.html"><code>querystring</code></a> module have similar purpose, but the purpose of the <a href="querystring.html"><code>querystring</code></a> module is more general, as it allows the customization of delimiter characters (<code>&</code> and <code>=</code>). On the other hand, this API is designed purely for URL query strings.</p> <pre><code class="language-js">const myURL = new URL('https://example.org/?abc=123'); console.log(myURL.searchParams.get('abc')); // Prints 123 myURL.searchParams.append('abc', 'xyz'); console.log(myURL.href); // Prints https://example.org/?abc=123&abc=xyz myURL.searchParams.delete('abc'); myURL.searchParams.set('a', 'b'); console.log(myURL.href); // Prints https://example.org/?a=b const newSearchParams = new URLSearchParams(myURL.searchParams); // The above is equivalent to // const newSearchParams = new URLSearchParams(myURL.search); newSearchParams.append('a', 'c'); console.log(myURL.href); // Prints https://example.org/?a=b console.log(newSearchParams.toString()); // Prints a=b&a=c // newSearchParams.toString() is implicitly called myURL.search = newSearchParams; console.log(myURL.href); // Prints https://example.org/?a=b&a=c newSearchParams.delete('a'); console.log(myURL.href); // Prints https://example.org/?a=b&a=c </code></pre> <h4>Constructor: new URLSearchParams()<span><a class="mark" href="#url_constructor_new_urlsearchparams" id="url_constructor_new_urlsearchparams">#</a></span></h4> <p>Instantiate a new empty <code>URLSearchParams</code> object.</p> <h4>Constructor: new URLSearchParams(string)<span><a class="mark" href="#url_constructor_new_urlsearchparams_string" id="url_constructor_new_urlsearchparams_string">#</a></span></h4> <ul> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A query string</li> </ul> <p>Parse the <code>string</code> as a query string, and use it to instantiate a new <code>URLSearchParams</code> object. A leading <code>'?'</code>, if present, is ignored.</p> <pre><code class="language-js">let params; params = new URLSearchParams('user=abc&query=xyz'); console.log(params.get('user')); // Prints 'abc' console.log(params.toString()); // Prints 'user=abc&query=xyz' params = new URLSearchParams('?user=abc&query=xyz'); console.log(params.toString()); // Prints 'user=abc&query=xyz' </code></pre> <h4>Constructor: new URLSearchParams(obj)<span><a class="mark" href="#url_constructor_new_urlsearchparams_obj" id="url_constructor_new_urlsearchparams_obj">#</a></span></h4> <div class="api_metadata"> <span>Added in: v7.10.0, v6.13.0</span> </div> <ul> <li><code>obj</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object representing a collection of key-value pairs</li> </ul> <p>Instantiate a new <code>URLSearchParams</code> object with a query hash map. The key and value of each property of <code>obj</code> are always coerced to strings.</p> <p>Unlike <a href="querystring.html"><code>querystring</code></a> module, duplicate keys in the form of array values are not allowed. Arrays are stringified using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString"><code>array.toString()</code></a>, which simply joins all array elements with commas.</p> <pre><code class="language-js">const params = new URLSearchParams({ user: 'abc', query: ['first', 'second'] }); console.log(params.getAll('query')); // Prints [ 'first,second' ] console.log(params.toString()); // Prints 'user=abc&query=first%2Csecond' </code></pre> <h4>Constructor: new URLSearchParams(iterable)<span><a class="mark" href="#url_constructor_new_urlsearchparams_iterable" id="url_constructor_new_urlsearchparams_iterable">#</a></span></h4> <div class="api_metadata"> <span>Added in: v7.10.0, v6.13.0</span> </div> <ul> <li><code>iterable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type"><Iterable></a> An iterable object whose elements are key-value pairs</li> </ul> <p>Instantiate a new <code>URLSearchParams</code> object with an iterable map in a way that is similar to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a>'s constructor. <code>iterable</code> can be an <code>Array</code> or any iterable object. That means <code>iterable</code> can be another <code>URLSearchParams</code>, in which case the constructor will simply create a clone of the provided <code>URLSearchParams</code>. Elements of <code>iterable</code> are key-value pairs, and can themselves be any iterable object.</p> <p>Duplicate keys are allowed.</p> <pre><code class="language-js">let params; // Using an array params = new URLSearchParams([ ['user', 'abc'], ['query', 'first'], ['query', 'second'] ]); console.log(params.toString()); // Prints 'user=abc&query=first&query=second' // Using a Map object const map = new Map(); map.set('user', 'abc'); map.set('query', 'xyz'); params = new URLSearchParams(map); console.log(params.toString()); // Prints 'user=abc&query=xyz' // Using a generator function function* getQueryPairs() { yield ['user', 'abc']; yield ['query', 'first']; yield ['query', 'second']; } params = new URLSearchParams(getQueryPairs()); console.log(params.toString()); // Prints 'user=abc&query=first&query=second' // Each key-value pair must have exactly two elements new URLSearchParams([ ['user', 'abc', 'error'] ]); // Throws TypeError [ERR_INVALID_TUPLE]: // Each query pair must be an iterable [name, value] tuple </code></pre> <h4>urlSearchParams.append(name, value)<span><a class="mark" href="#url_urlsearchparams_append_name_value" id="url_urlsearchparams_append_name_value">#</a></span></h4> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Append a new name-value pair to the query string.</p> <h4>urlSearchParams.delete(name)<span><a class="mark" href="#url_urlsearchparams_delete_name" id="url_urlsearchparams_delete_name">#</a></span></h4> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Remove all name-value pairs whose name is <code>name</code>.</p> <h4>urlSearchParams.entries()<span><a class="mark" href="#url_urlsearchparams_entries" id="url_urlsearchparams_entries">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li> </ul> <p>Returns an ES6 <code>Iterator</code> over each of the name-value pairs in the query. Each item of the iterator is a JavaScript <code>Array</code>. The first item of the <code>Array</code> is the <code>name</code>, the second item of the <code>Array</code> is the <code>value</code>.</p> <p>Alias for <a href="#url_urlsearchparams_symbol_iterator"><code>urlSearchParams[@@iterator]()</code></a>.</p> <h4>urlSearchParams.forEach(fn[, thisArg])<span><a class="mark" href="#url_urlsearchparams_foreach_fn_thisarg" id="url_urlsearchparams_foreach_fn_thisarg">#</a></span></h4> <ul> <li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Invoked for each name-value pair in the query</li> <li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> To be used as <code>this</code> value for when <code>fn</code> is called</li> </ul> <p>Iterates over each name-value pair in the query and invokes the given function.</p> <pre><code class="language-js">const myURL = new URL('https://example.org/?a=b&c=d'); myURL.searchParams.forEach((value, name, searchParams) => { console.log(name, value, myURL.searchParams === searchParams); }); // Prints: // a b true // c d true </code></pre> <h4>urlSearchParams.get(name)<span><a class="mark" href="#url_urlsearchparams_get_name" id="url_urlsearchparams_get_name">#</a></span></h4> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> or <code>null</code> if there is no name-value pair with the given <code>name</code>.</li> </ul> <p>Returns the value of the first name-value pair whose name is <code>name</code>. If there are no such pairs, <code>null</code> is returned.</p> <h4>urlSearchParams.getAll(name)<span><a class="mark" href="#url_urlsearchparams_getall_name" id="url_urlsearchparams_getall_name">#</a></span></h4> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>Returns the values of all name-value pairs whose name is <code>name</code>. If there are no such pairs, an empty array is returned.</p> <h4>urlSearchParams.has(name)<span><a class="mark" href="#url_urlsearchparams_has_name" id="url_urlsearchparams_has_name">#</a></span></h4> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if there is at least one name-value pair whose name is <code>name</code>.</p> <h4>urlSearchParams.keys()<span><a class="mark" href="#url_urlsearchparams_keys" id="url_urlsearchparams_keys">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li> </ul> <p>Returns an ES6 <code>Iterator</code> over the names of each name-value pair.</p> <pre><code class="language-js">const params = new URLSearchParams('foo=bar&foo=baz'); for (const name of params.keys()) { console.log(name); } // Prints: // foo // foo </code></pre> <h4>urlSearchParams.set(name, value)<span><a class="mark" href="#url_urlsearchparams_set_name_value" id="url_urlsearchparams_set_name_value">#</a></span></h4> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Sets the value in the <code>URLSearchParams</code> object associated with <code>name</code> to <code>value</code>. If there are any pre-existing name-value pairs whose names are <code>name</code>, set the first such pair's value to <code>value</code> and remove all others. If not, append the name-value pair to the query string.</p> <pre><code class="language-js">const params = new URLSearchParams(); params.append('foo', 'bar'); params.append('foo', 'baz'); params.append('abc', 'def'); console.log(params.toString()); // Prints foo=bar&foo=baz&abc=def params.set('foo', 'def'); params.set('xyz', 'opq'); console.log(params.toString()); // Prints foo=def&abc=def&xyz=opq </code></pre> <h4>urlSearchParams.sort()<span><a class="mark" href="#url_urlsearchparams_sort" id="url_urlsearchparams_sort">#</a></span></h4> <div class="api_metadata"> <span>Added in: v7.7.0, v6.13.0</span> </div> <p>Sort all existing name-value pairs in-place by their names. Sorting is done with a <a href="https://en.wikipedia.org/wiki/Sorting_algorithm#Stability">stable sorting algorithm</a>, so relative order between name-value pairs with the same name is preserved.</p> <p>This method can be used, in particular, to increase cache hits.</p> <pre><code class="language-js">const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); params.sort(); console.log(params.toString()); // Prints query%5B%5D=abc&query%5B%5D=123&type=search </code></pre> <h4>urlSearchParams.toString()<span><a class="mark" href="#url_urlsearchparams_tostring" id="url_urlsearchparams_tostring">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the search parameters serialized as a string, with characters percent-encoded where necessary.</p> <h4>urlSearchParams.values()<span><a class="mark" href="#url_urlsearchparams_values" id="url_urlsearchparams_values">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li> </ul> <p>Returns an ES6 <code>Iterator</code> over the values of each name-value pair.</p> <h4>urlSearchParams[Symbol.iterator]()<span><a class="mark" href="#url_urlsearchparams_symbol_iterator" id="url_urlsearchparams_symbol_iterator">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type"><Iterator></a></li> </ul> <p>Returns an ES6 <code>Iterator</code> over each of the name-value pairs in the query string. Each item of the iterator is a JavaScript <code>Array</code>. The first item of the <code>Array</code> is the <code>name</code>, the second item of the <code>Array</code> is the <code>value</code>.</p> <p>Alias for <a href="#url_urlsearchparams_entries"><code>urlSearchParams.entries()</code></a>.</p> <pre><code class="language-js">const params = new URLSearchParams('foo=bar&xyz=baz'); for (const [name, value] of params) { console.log(name, value); } // Prints: // foo bar // xyz baz </code></pre> <h3>url.domainToASCII(domain)<span><a class="mark" href="#url_url_domaintoascii_domain" id="url_url_domaintoascii_domain">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.4.0, v6.13.0</span> </div> <ul> <li><code>domain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the <a href="https://tools.ietf.org/html/rfc5891#section-4.4">Punycode</a> ASCII serialization of the <code>domain</code>. If <code>domain</code> is an invalid domain, the empty string is returned.</p> <p>It performs the inverse operation to <a href="#url_url_domaintounicode_domain"><code>url.domainToUnicode()</code></a>.</p> <pre><code class="language-js">const url = require('url'); console.log(url.domainToASCII('español.com')); // Prints xn--espaol-zwa.com console.log(url.domainToASCII('中文.com')); // Prints xn--fiq228c.com console.log(url.domainToASCII('xn--iñvalid.com')); // Prints an empty string </code></pre> <h3>url.domainToUnicode(domain)<span><a class="mark" href="#url_url_domaintounicode_domain" id="url_url_domaintounicode_domain">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.4.0, v6.13.0</span> </div> <ul> <li><code>domain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the Unicode serialization of the <code>domain</code>. If <code>domain</code> is an invalid domain, the empty string is returned.</p> <p>It performs the inverse operation to <a href="#url_url_domaintoascii_domain"><code>url.domainToASCII()</code></a>.</p> <pre><code class="language-js">const url = require('url'); console.log(url.domainToUnicode('xn--espaol-zwa.com')); // Prints español.com console.log(url.domainToUnicode('xn--fiq228c.com')); // Prints 中文.com console.log(url.domainToUnicode('xn--iñvalid.com')); // Prints an empty string </code></pre> <h3>url.fileURLToPath(url)<span><a class="mark" href="#url_url_fileurltopath_url" id="url_url_fileurltopath_url">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>url</code> <a href="#url_the_whatwg_url_api" class="type"><URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The file URL string or URL object to convert to a path.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The fully-resolved platform-specific Node.js file path.</li> </ul> <p>This function ensures the correct decodings of percent-encoded characters as well as ensuring a cross-platform valid absolute path string.</p> <pre><code class="language-js">new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) new URL('file:///hello world').pathname; // Incorrect: /hello%20world fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) </code></pre> <h3>url.format(URL[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/url.js#L571">[src]</a><span><a class="mark" href="#url_url_format_url_options" id="url_url_format_url_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v7.6.0</span> </div> <ul> <li><code>URL</code> <a href="#url_the_whatwg_url_api" class="type"><URL></a> A <a href="#url_the_whatwg_url_api">WHATWG URL</a> object</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>auth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the serialized URL string should include the username and password, <code>false</code> otherwise. <strong>Default:</strong> <code>true</code>.</li> <li><code>fragment</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the serialized URL string should include the fragment, <code>false</code> otherwise. <strong>Default:</strong> <code>true</code>.</li> <li><code>search</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if the serialized URL string should include the search query, <code>false</code> otherwise. <strong>Default:</strong> <code>true</code>.</li> <li><code>unicode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to being Punycode encoded. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns a customizable serialization of a URL <code>String</code> representation of a <a href="#url_the_whatwg_url_api">WHATWG URL</a> object.</p> <p>The URL object has both a <code>toString()</code> method and <code>href</code> property that return string serializations of the URL. These are not, however, customizable in any way. The <code>url.format(URL[, options])</code> method allows for basic customization of the output.</p> <pre><code class="language-js">const myURL = new URL('https://a:b@測試?abc#foo'); console.log(myURL.href); // Prints https://a:b@xn--g6w251d/?abc#foo console.log(myURL.toString()); // Prints https://a:b@xn--g6w251d/?abc#foo console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); // Prints 'https://測試/?abc' </code></pre> <h3>url.pathToFileURL(path)<span><a class="mark" href="#url_url_pathtofileurl_path" id="url_url_pathtofileurl_path">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.12.0</span> </div> <ul> <li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The path to convert to a File URL.</li> <li>Returns: <a href="#url_the_whatwg_url_api" class="type"><URL></a> The file URL object.</li> </ul> <p>This function ensures that <code>path</code> is resolved absolutely, and that the URL control characters are correctly encoded when converting into a File URL.</p> <pre><code class="language-js">new URL(__filename); // Incorrect: throws (POSIX) new URL(__filename); // Incorrect: C:\... (Windows) pathToFileURL(__filename); // Correct: file:///... (POSIX) pathToFileURL(__filename); // Correct: file:///C:/... (Windows) new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) new URL('/some/path%.js', 'file:'); // Incorrect: file:///some/path% pathToFileURL('/some/path%.js'); // Correct: file:///some/path%25 (POSIX) </code></pre> <h2>Legacy URL API<span><a class="mark" href="#url_legacy_url_api" id="url_legacy_url_api">#</a></span></h2> <h3>Legacy <code>urlObject</code><span><a class="mark" href="#url_legacy_urlobject" id="url_legacy_urlobject">#</a></span></h3> <p>The legacy <code>urlObject</code> (<code>require('url').Url</code>) is created and returned by the <code>url.parse()</code> function.</p> <h4>urlObject.auth<span><a class="mark" href="#url_urlobject_auth" id="url_urlobject_auth">#</a></span></h4> <p>The <code>auth</code> property is the username and password portion of the URL, also referred to as <em>userinfo</em>. This string subset follows the <code>protocol</code> and double slashes (if present) and precedes the <code>host</code> component, delimited by <code>@</code>. The string is either the username, or it is the username and password separated by <code>:</code>.</p> <p>For example: <code>'user:pass'</code>.</p> <h4>urlObject.hash<span><a class="mark" href="#url_urlobject_hash" id="url_urlobject_hash">#</a></span></h4> <p>The <code>hash</code> property is the fragment identifier portion of the URL including the leading <code>#</code> character.</p> <p>For example: <code>'#hash'</code>.</p> <h4>urlObject.host<span><a class="mark" href="#url_urlobject_host" id="url_urlobject_host">#</a></span></h4> <p>The <code>host</code> property is the full lower-cased host portion of the URL, including the <code>port</code> if specified.</p> <p>For example: <code>'sub.example.com:8080'</code>.</p> <h4>urlObject.hostname<span><a class="mark" href="#url_urlobject_hostname" id="url_urlobject_hostname">#</a></span></h4> <p>The <code>hostname</code> property is the lower-cased host name portion of the <code>host</code> component <em>without</em> the <code>port</code> included.</p> <p>For example: <code>'sub.example.com'</code>.</p> <h4>urlObject.href<span><a class="mark" href="#url_urlobject_href" id="url_urlobject_href">#</a></span></h4> <p>The <code>href</code> property is the full URL string that was parsed with both the <code>protocol</code> and <code>host</code> components converted to lower-case.</p> <p>For example: <code>'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</code>.</p> <h4>urlObject.path<span><a class="mark" href="#url_urlobject_path" id="url_urlobject_path">#</a></span></h4> <p>The <code>path</code> property is a concatenation of the <code>pathname</code> and <code>search</code> components.</p> <p>For example: <code>'/p/a/t/h?query=string'</code>.</p> <p>No decoding of the <code>path</code> is performed.</p> <h4>urlObject.pathname<span><a class="mark" href="#url_urlobject_pathname" id="url_urlobject_pathname">#</a></span></h4> <p>The <code>pathname</code> property consists of the entire path section of the URL. This is everything following the <code>host</code> (including the <code>port</code>) and before the start of the <code>query</code> or <code>hash</code> components, delimited by either the ASCII question mark (<code>?</code>) or hash (<code>#</code>) characters.</p> <p>For example: <code>'/p/a/t/h'</code>.</p> <p>No decoding of the path string is performed.</p> <h4>urlObject.port<span><a class="mark" href="#url_urlobject_port" id="url_urlobject_port">#</a></span></h4> <p>The <code>port</code> property is the numeric port portion of the <code>host</code> component.</p> <p>For example: <code>'8080'</code>.</p> <h4>urlObject.protocol<span><a class="mark" href="#url_urlobject_protocol" id="url_urlobject_protocol">#</a></span></h4> <p>The <code>protocol</code> property identifies the URL's lower-cased protocol scheme.</p> <p>For example: <code>'http:'</code>.</p> <h4>urlObject.query<span><a class="mark" href="#url_urlobject_query" id="url_urlobject_query">#</a></span></h4> <p>The <code>query</code> property is either the query string without the leading ASCII question mark (<code>?</code>), or an object returned by the <a href="querystring.html"><code>querystring</code></a> module's <code>parse()</code> method. Whether the <code>query</code> property is a string or object is determined by the <code>parseQueryString</code> argument passed to <code>url.parse()</code>.</p> <p>For example: <code>'query=string'</code> or <code>{'query': 'string'}</code>.</p> <p>If returned as a string, no decoding of the query string is performed. If returned as an object, both keys and values are decoded.</p> <h4>urlObject.search<span><a class="mark" href="#url_urlobject_search" id="url_urlobject_search">#</a></span></h4> <p>The <code>search</code> property consists of the entire "query string" portion of the URL, including the leading ASCII question mark (<code>?</code>) character.</p> <p>For example: <code>'?query=string'</code>.</p> <p>No decoding of the query string is performed.</p> <h4>urlObject.slashes<span><a class="mark" href="#url_urlobject_slashes" id="url_urlobject_slashes">#</a></span></h4> <p>The <code>slashes</code> property is a <code>boolean</code> with a value of <code>true</code> if two ASCII forward-slash characters (<code>/</code>) are required following the colon in the <code>protocol</code>.</p> <h3>url.format(urlObject)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/url.js#L571">[src]</a><span><a class="mark" href="#url_url_format_urlobject" id="url_url_format_urlobject">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.0.0</td> <td><p>URLs with a <code>file:</code> scheme will now always use the correct number of slashes regardless of <code>slashes</code> option. A false-y <code>slashes</code> option with no protocol is now also respected at all times.</p></td></tr> <tr><td>v0.1.25</td> <td><p><span>Added in: v0.1.25</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>urlObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A URL object (as returned by <code>url.parse()</code> or constructed otherwise). If a string, it is converted to an object by passing it to <code>url.parse()</code>.</li> </ul> <p>The <code>url.format()</code> method returns a formatted URL string derived from <code>urlObject</code>.</p> <pre><code class="language-js">url.format({ protocol: 'https', hostname: 'example.com', pathname: '/some/path', query: { page: 1, format: 'json' } }); // => 'https://example.com/some/path?page=1&format=json' </code></pre> <p>If <code>urlObject</code> is not an object or a string, <code>url.format()</code> will throw a <a href="#errors_class_typeerror"><code>TypeError</code></a>.</p> <p>The formatting process operates as follows:</p> <ul> <li>A new empty string <code>result</code> is created.</li> <li>If <code>urlObject.protocol</code> is a string, it is appended as-is to <code>result</code>.</li> <li>Otherwise, if <code>urlObject.protocol</code> is not <code>undefined</code> and is not a string, an <a href="#errors_class_error"><code>Error</code></a> is thrown.</li> <li>For all string values of <code>urlObject.protocol</code> that <em>do not end</em> with an ASCII colon (<code>:</code>) character, the literal string <code>:</code> will be appended to <code>result</code>.</li> <li> <p>If either of the following conditions is true, then the literal string <code>//</code> will be appended to <code>result</code>:</p> <ul> <li><code>urlObject.slashes</code> property is true;</li> <li><code>urlObject.protocol</code> begins with <code>http</code>, <code>https</code>, <code>ftp</code>, <code>gopher</code>, or <code>file</code>;</li> </ul> </li> <li>If the value of the <code>urlObject.auth</code> property is truthy, and either <code>urlObject.host</code> or <code>urlObject.hostname</code> are not <code>undefined</code>, the value of <code>urlObject.auth</code> will be coerced into a string and appended to <code>result</code> followed by the literal string <code>@</code>.</li> <li> <p>If the <code>urlObject.host</code> property is <code>undefined</code> then:</p> <ul> <li>If the <code>urlObject.hostname</code> is a string, it is appended to <code>result</code>.</li> <li>Otherwise, if <code>urlObject.hostname</code> is not <code>undefined</code> and is not a string, an <a href="#errors_class_error"><code>Error</code></a> is thrown.</li> <li> <p>If the <code>urlObject.port</code> property value is truthy, and <code>urlObject.hostname</code> is not <code>undefined</code>:</p> <ul> <li>The literal string <code>:</code> is appended to <code>result</code>, and</li> <li>The value of <code>urlObject.port</code> is coerced to a string and appended to <code>result</code>.</li> </ul> </li> </ul> </li> <li>Otherwise, if the <code>urlObject.host</code> property value is truthy, the value of <code>urlObject.host</code> is coerced to a string and appended to <code>result</code>.</li> <li> <p>If the <code>urlObject.pathname</code> property is a string that is not an empty string:</p> <ul> <li>If the <code>urlObject.pathname</code> <em>does not start</em> with an ASCII forward slash (<code>/</code>), then the literal string <code>'/'</code> is appended to <code>result</code>.</li> <li>The value of <code>urlObject.pathname</code> is appended to <code>result</code>.</li> </ul> </li> <li>Otherwise, if <code>urlObject.pathname</code> is not <code>undefined</code> and is not a string, an <a href="#errors_class_error"><code>Error</code></a> is thrown.</li> <li>If the <code>urlObject.search</code> property is <code>undefined</code> and if the <code>urlObject.query</code> property is an <code>Object</code>, the literal string <code>?</code> is appended to <code>result</code> followed by the output of calling the <a href="querystring.html"><code>querystring</code></a> module's <code>stringify()</code> method passing the value of <code>urlObject.query</code>.</li> <li> <p>Otherwise, if <code>urlObject.search</code> is a string:</p> <ul> <li>If the value of <code>urlObject.search</code> <em>does not start</em> with the ASCII question mark (<code>?</code>) character, the literal string <code>?</code> is appended to <code>result</code>.</li> <li>The value of <code>urlObject.search</code> is appended to <code>result</code>.</li> </ul> </li> <li>Otherwise, if <code>urlObject.search</code> is not <code>undefined</code> and is not a string, an <a href="#errors_class_error"><code>Error</code></a> is thrown.</li> <li> <p>If the <code>urlObject.hash</code> property is a string:</p> <ul> <li>If the value of <code>urlObject.hash</code> <em>does not start</em> with the ASCII hash (<code>#</code>) character, the literal string <code>#</code> is appended to <code>result</code>.</li> <li>The value of <code>urlObject.hash</code> is appended to <code>result</code>.</li> </ul> </li> <li>Otherwise, if the <code>urlObject.hash</code> property is not <code>undefined</code> and is not a string, an <a href="#errors_class_error"><code>Error</code></a> is thrown.</li> <li><code>result</code> is returned.</li> </ul> <h3>url.parse(urlString[, parseQueryString[, slashesDenoteHost]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/url.js#L152">[src]</a><span><a class="mark" href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost" id="url_url_parse_urlstring_parsequerystring_slashesdenotehost">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.0.0</td> <td><p>The <code>search</code> property on the returned URL object is now <code>null</code> when no query string is present.</p></td></tr> <tr><td>v0.1.25</td> <td><p><span>Added in: v0.1.25</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>urlString</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The URL string to parse.</li> <li><code>parseQueryString</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the <code>query</code> property will always be set to an object returned by the <a href="querystring.html"><code>querystring</code></a> module's <code>parse()</code> method. If <code>false</code>, the <code>query</code> property on the returned URL object will be an unparsed, undecoded string. <strong>Default:</strong> <code>false</code>.</li> <li><code>slashesDenoteHost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the first token after the literal string <code>//</code> and preceding the next <code>/</code> will be interpreted as the <code>host</code>. For instance, given <code>//foo/bar</code>, the result would be <code>{host: 'foo', pathname: '/bar'}</code> rather than <code>{pathname: '//foo/bar'}</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> <p>The <code>url.parse()</code> method takes a URL string, parses it, and returns a URL object.</p> <p>A <code>TypeError</code> is thrown if <code>urlString</code> is not a string.</p> <p>A <code>URIError</code> is thrown if the <code>auth</code> property is present but cannot be decoded.</p> <h3>url.resolve(from, to)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/url.js#L662">[src]</a><span><a class="mark" href="#url_url_resolve_from_to" id="url_url_resolve_from_to">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.6.0</td> <td><p>The <code>auth</code> fields are now kept intact when <code>from</code> and <code>to</code> refer to the same host.</p></td></tr> <tr><td>v6.5.0, v4.6.2</td> <td><p>The <code>port</code> field is copied correctly now.</p></td></tr> <tr><td>v6.0.0</td> <td><p>The <code>auth</code> fields is cleared now the <code>to</code> parameter contains a hostname.</p></td></tr> <tr><td>v0.1.25</td> <td><p><span>Added in: v0.1.25</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>from</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The Base URL being resolved against.</li> <li><code>to</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The HREF URL being resolved.</li> </ul> <p>The <code>url.resolve()</code> method resolves a target URL relative to a base URL in a manner similar to that of a Web browser resolving an anchor tag HREF.</p> <pre><code class="language-js">const url = require('url'); url.resolve('/one/two/three', 'four'); // '/one/two/four' url.resolve('http://example.com/', '/one'); // 'http://example.com/one' url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' </code></pre> <p><a id="whatwg-percent-encoding"></a></p> <h2>Percent-Encoding in URLs<span><a class="mark" href="#url_percent_encoding_in_urls" id="url_percent_encoding_in_urls">#</a></span></h2> <p>URLs are permitted to only contain a certain range of characters. Any character falling outside of that range must be encoded. How such characters are encoded, and which characters to encode depends entirely on where the character is located within the structure of the URL.</p> <h3>Legacy API<span><a class="mark" href="#url_legacy_api" id="url_legacy_api">#</a></span></h3> <p>Within the Legacy API, spaces (<code>' '</code>) and the following characters will be automatically escaped in the properties of URL objects:</p> <pre><code class="language-txt">< > " ` \r \n \t { } | \ ^ ' </code></pre> <p>For example, the ASCII space character (<code>' '</code>) is encoded as <code>%20</code>. The ASCII forward slash (<code>/</code>) character is encoded as <code>%3C</code>.</p> <h3>WHATWG API<span><a class="mark" href="#url_whatwg_api" id="url_whatwg_api">#</a></span></h3> <p>The <a href="https://url.spec.whatwg.org/">WHATWG URL Standard</a> uses a more selective and fine grained approach to selecting encoded characters than that used by the Legacy API.</p> <p>The WHATWG algorithm defines four "percent-encode sets" that describe ranges of characters that must be percent-encoded:</p> <ul> <li> <p>The <em>C0 control percent-encode set</em> includes code points in range U+0000 to U+001F (inclusive) and all code points greater than U+007E.</p> </li> <li> <p>The <em>fragment percent-encode set</em> includes the <em>C0 control percent-encode set</em> and code points U+0020, U+0022, U+003C, U+003E, and U+0060.</p> </li> <li> <p>The <em>path percent-encode set</em> includes the <em>C0 control percent-encode set</em> and code points U+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060, U+007B, and U+007D.</p> </li> <li> <p>The <em>userinfo encode set</em> includes the <em>path percent-encode set</em> and code points U+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D, U+005E, and U+007C.</p> </li> </ul> <p>The <em>userinfo percent-encode set</em> is used exclusively for username and passwords encoded within the URL. The <em>path percent-encode set</em> is used for the path of most URLs. The <em>fragment percent-encode set</em> is used for URL fragments. The <em>C0 control percent-encode set</em> is used for host and path under certain specific conditions, in addition to all other cases.</p> <p>When non-ASCII characters appear within a hostname, the hostname is encoded using the <a href="https://tools.ietf.org/html/rfc5891#section-4.4">Punycode</a> algorithm. Note, however, that a hostname <em>may</em> contain <em>both</em> Punycode encoded and percent-encoded characters:</p> <pre><code class="language-js">const myURL = new URL('https://%CF%80.example.com/foo'); console.log(myURL.href); // Prints https://xn--1xa.example.com/foo console.log(myURL.origin); // Prints https://xn--1xa.example.com </code></pre> <h1>Util<span><a class="mark" href="#util_util" id="util_util">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>util</code> module is primarily designed to support the needs of Node.js' own internal APIs. However, many of the utilities are useful for application and module developers as well. It can be accessed using:</p> <pre><code class="language-js">const util = require('util'); </code></pre> <h2>util.callbackify(original)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L340">[src]</a><span><a class="mark" href="#util_util_callbackify_original" id="util_util_callbackify_original">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.2.0</span> </div> <ul> <li><code>original</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> An <code>async</code> function</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> a callback style function</li> </ul> <p>Takes an <code>async</code> function (or a function that returns a <code>Promise</code>) and returns a function following the error-first callback style, i.e. taking an <code>(err, value) => ...</code> callback as the last argument. In the callback, the first argument will be the rejection reason (or <code>null</code> if the <code>Promise</code> resolved), and the second argument will be the resolved value.</p> <pre><code class="language-js">const util = require('util'); async function fn() { return 'hello world'; } const callbackFunction = util.callbackify(fn); callbackFunction((err, ret) => { if (err) throw err; console.log(ret); }); </code></pre> <p>Will print:</p> <pre><code class="language-txt">hello world </code></pre> <p>The callback is executed asynchronously, and will have a limited stack trace. If the callback throws, the process will emit an <a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a> event, and if not handled will exit.</p> <p>Since <code>null</code> has a special meaning as the first argument to a callback, if a wrapped function rejects a <code>Promise</code> with a falsy value as a reason, the value is wrapped in an <code>Error</code> with the original value stored in a field named <code>reason</code>.</p> <pre><code class="language-js">function fn() { return Promise.reject(null); } const callbackFunction = util.callbackify(fn); callbackFunction((err, ret) => { // When the Promise was rejected with `null` it is wrapped with an Error and // the original value is stored in `reason`. err && err.hasOwnProperty('reason') && err.reason === null; // true }); </code></pre> <h2>util.debuglog(section)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L181">[src]</a><span><a class="mark" href="#util_util_debuglog_section" id="util_util_debuglog_section">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.3</span> </div> <ul> <li><code>section</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A string identifying the portion of the application for which the <code>debuglog</code> function is being created.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The logging function</li> </ul> <p>The <code>util.debuglog()</code> method is used to create a function that conditionally writes debug messages to <code>stderr</code> based on the existence of the <code>NODE_DEBUG</code> environment variable. If the <code>section</code> name appears within the value of that environment variable, then the returned function operates similar to <a href="#console_console_error_data_args"><code>console.error()</code></a>. If not, then the returned function is a no-op.</p> <pre><code class="language-js">const util = require('util'); const debuglog = util.debuglog('foo'); debuglog('hello from foo [%d]', 123); </code></pre> <p>If this program is run with <code>NODE_DEBUG=foo</code> in the environment, then it will output something like:</p> <pre><code class="language-txt">FOO 3245: hello from foo [123] </code></pre> <p>where <code>3245</code> is the process id. If it is not run with that environment variable set, then it will not print anything.</p> <p>The <code>section</code> supports wildcard also:</p> <pre><code class="language-js">const util = require('util'); const debuglog = util.debuglog('foo-bar'); debuglog('hi there, it\'s foo-bar [%d]', 2333); </code></pre> <p>if it is run with <code>NODE_DEBUG=foo*</code> in the environment, then it will output something like:</p> <pre><code class="language-txt">FOO-BAR 3257: hi there, it's foo-bar [2333] </code></pre> <p>Multiple comma-separated <code>section</code> names may be specified in the <code>NODE_DEBUG</code> environment variable: <code>NODE_DEBUG=fs,net,tls</code>.</p> <h2>util.deprecate(fn, msg[, code])<span><a class="mark" href="#util_util_deprecate_fn_msg_code" id="util_util_deprecate_fn_msg_code">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>Deprecation warnings are only emitted once for each code.</p></td></tr> <tr><td>v0.8.0</td> <td><p><span>Added in: v0.8.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The function that is being deprecated.</li> <li><code>msg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A warning message to display when the deprecated function is invoked.</li> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A deprecation code. See the <a href="#deprecations_list_of_deprecated_apis">list of deprecated APIs</a> for a list of codes.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> The deprecated function wrapped to emit a warning.</li> </ul> <p>The <code>util.deprecate()</code> method wraps <code>fn</code> (which may be a function or class) in such a way that it is marked as deprecated.</p> <pre><code class="language-js">const util = require('util'); exports.obsoleteFunction = util.deprecate(() => { // Do something here. }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); </code></pre> <p>When called, <code>util.deprecate()</code> will return a function that will emit a <code>DeprecationWarning</code> using the <a href="#process_event_warning"><code>'warning'</code></a> event. The warning will be emitted and printed to <code>stderr</code> the first time the returned function is called. After the warning is emitted, the wrapped function is called without emitting a warning.</p> <p>If the same optional <code>code</code> is supplied in multiple calls to <code>util.deprecate()</code>, the warning will be emitted only once for that <code>code</code>.</p> <pre><code class="language-js">const util = require('util'); const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); fn1(); // emits a deprecation warning with code DEP0001 fn2(); // does not emit a deprecation warning because it has the same code </code></pre> <p>If either the <code>--no-deprecation</code> or <code>--no-warnings</code> command line flags are used, or if the <code>process.noDeprecation</code> property is set to <code>true</code> <em>prior</em> to the first deprecation warning, the <code>util.deprecate()</code> method does nothing.</p> <p>If the <code>--trace-deprecation</code> or <code>--trace-warnings</code> command line flags are set, or the <code>process.traceDeprecation</code> property is set to <code>true</code>, a warning and a stack trace are printed to <code>stderr</code> the first time the deprecated function is called.</p> <p>If the <code>--throw-deprecation</code> command line flag is set, or the <code>process.throwDeprecation</code> property is set to <code>true</code>, then an exception will be thrown when the deprecated function is called.</p> <p>The <code>--throw-deprecation</code> command line flag and <code>process.throwDeprecation</code> property take precedence over <code>--trace-deprecation</code> and <code>process.traceDeprecation</code>.</p> <h2>util.format(format[, ...args])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L71">[src]</a><span><a class="mark" href="#util_util_format_format_args" id="util_util_format_format_args">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.12.0</td> <td><p>The <code>%d</code> and <code>%i</code> specifiers now support BigInt.</p></td></tr> <tr><td>v8.4.0</td> <td><p>The <code>%o</code> and <code>%O</code> specifiers are supported now.</p></td></tr> <tr><td>v0.5.3</td> <td><p><span>Added in: v0.5.3</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> A <code>printf</code>-like format string.</li> </ul> <p>The <code>util.format()</code> method returns a formatted string using the first argument as a <code>printf</code>-like format.</p> <p>The first argument is a string containing zero or more <em>placeholder</em> tokens. Each placeholder token is replaced with the converted value from the corresponding argument. Supported placeholders are:</p> <ul> <li><code>%s</code> - <code>String</code>.</li> <li><code>%d</code> - <code>Number</code> (integer or floating point value) or <code>BigInt</code>.</li> <li><code>%i</code> - Integer or <code>BigInt</code>.</li> <li><code>%f</code> - Floating point value.</li> <li><code>%j</code> - JSON. Replaced with the string <code>'[Circular]'</code> if the argument contains circular references.</li> <li><code>%o</code> - <code>Object</code>. A string representation of an object with generic JavaScript object formatting. Similar to <code>util.inspect()</code> with options <code>{ showHidden: true, showProxy: true }</code>. This will show the full object including non-enumerable properties and proxies.</li> <li><code>%O</code> - <code>Object</code>. A string representation of an object with generic JavaScript object formatting. Similar to <code>util.inspect()</code> without options. This will show the full object not including non-enumerable properties and proxies.</li> <li><code>%%</code> - single percent sign (<code>'%'</code>). This does not consume an argument.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The formatted string</li> </ul> <p>If the placeholder does not have a corresponding argument, the placeholder is not replaced.</p> <pre><code class="language-js">util.format('%s:%s', 'foo'); // Returns: 'foo:%s' </code></pre> <p>If there are more arguments passed to the <code>util.format()</code> method than the number of placeholders, the extra arguments are coerced into strings then concatenated to the returned string, each delimited by a space. Excessive arguments whose <code>typeof</code> is <code>'object'</code> or <code>'symbol'</code> (except <code>null</code>) will be transformed by <code>util.inspect()</code>.</p> <pre><code class="language-js">util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz' </code></pre> <p>If the first argument is not a string then <code>util.format()</code> returns a string that is the concatenation of all arguments separated by spaces. Each argument is converted to a string using <code>util.inspect()</code>.</p> <pre><code class="language-js">util.format(1, 2, 3); // '1 2 3' </code></pre> <p>If only one argument is passed to <code>util.format()</code>, it is returned as it is without any formatting.</p> <pre><code class="language-js">util.format('%% %s'); // '%% %s' </code></pre> <p>Please note that <code>util.format()</code> is a synchronous method that is mainly intended as a debugging tool. Some input values can have a significant performance overhead that can block the event loop. Use this function with care and never in a hot code path.</p> <h2>util.formatWithOptions(inspectOptions, format[, ...args])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L75">[src]</a><span><a class="mark" href="#util_util_formatwithoptions_inspectoptions_format_args" id="util_util_formatwithoptions_inspectoptions_format_args">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>inspectOptions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>This function is identical to <a href="#util_util_format_format_args"><code>util.format()</code></a>, except in that it takes an <code>inspectOptions</code> argument which specifies options that are passed along to <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a>.</p> <pre><code class="language-js">util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); // Returns 'See object { foo: 42 }', where `42` is colored as a number // when printed to a terminal. </code></pre> <h2>util.getSystemErrorName(err)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L367">[src]</a><span><a class="mark" href="#util_util_getsystemerrorname_err" id="util_util_getsystemerrorname_err">#</a></span></h2> <div class="api_metadata"> <span>Added in: v9.7.0</span> </div> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Returns the string name for a numeric error code that comes from a Node.js API. The mapping between error codes and error names is platform-dependent. See <a href="#errors_common_system_errors">Common System Errors</a> for the names of common errors.</p> <pre><code class="language-js">fs.access('file/that/does/not/exist', (err) => { const name = util.getSystemErrorName(err.errno); console.error(name); // ENOENT }); </code></pre> <h2>util.inherits(constructor, superConstructor)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L274">[src]</a><span><a class="mark" href="#util_util_inherits_constructor_superconstructor" id="util_util_inherits_constructor_superconstructor">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v5.0.0</td> <td><p>The <code>constructor</code> parameter can refer to an ES6 class now.</p></td></tr> <tr><td>v0.3.0</td> <td><p><span>Added in: v0.3.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>constructor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li><code>superConstructor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Usage of <code>util.inherits()</code> is discouraged. Please use the ES6 <code>class</code> and <code>extends</code> keywords to get language level inheritance support. Also note that the two styles are <a href="https://github.com/nodejs/node/issues/4179">semantically incompatible</a>.</p> <p>Inherit the prototype methods from one <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a> into another. The prototype of <code>constructor</code> will be set to a new object created from <code>superConstructor</code>.</p> <p>As an additional convenience, <code>superConstructor</code> will be accessible through the <code>constructor.super_</code> property.</p> <pre><code class="language-js">const util = require('util'); const EventEmitter = require('events'); function MyStream() { EventEmitter.call(this); } util.inherits(MyStream, EventEmitter); MyStream.prototype.write = function(data) { this.emit('data', data); }; const stream = new MyStream(); console.log(stream instanceof EventEmitter); // true console.log(MyStream.super_ === EventEmitter); // true stream.on('data', (data) => { console.log(`Received data: "${data}"`); }); stream.write('It works!'); // Received data: "It works!" </code></pre> <p>ES6 example using <code>class</code> and <code>extends</code>:</p> <pre><code class="language-js">const EventEmitter = require('events'); class MyStream extends EventEmitter { write(data) { this.emit('data', data); } } const stream = new MyStream(); stream.on('data', (data) => { console.log(`Received data: "${data}"`); }); stream.write('With ES6'); </code></pre> <h2>util.inspect(object[, options])<span><a class="mark" href="#util_util_inspect_object_options" id="util_util_inspect_object_options">#</a></span></h2> <h2>util.inspect(object[, showHidden[, depth[, colors]]])<span><a class="mark" href="#util_util_inspect_object_showhidden_depth_colors" id="util_util_inspect_object_showhidden_depth_colors">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.12.0</td> <td><p>The <code>sorted</code> option is supported now.</p></td></tr> <tr><td>v10.6.0</td> <td><p>Inspecting linked lists and similar objects is now possible up to the maximum call stack size.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>WeakMap</code> and <code>WeakSet</code> entries can now be inspected.</p></td></tr> <tr><td>v9.9.0</td> <td><p>The <code>compact</code> option is supported now.</p></td></tr> <tr><td>v6.6.0</td> <td><p>Custom inspection functions can now return <code>this</code>.</p></td></tr> <tr><td>v6.3.0</td> <td><p>The <code>breakLength</code> option is supported now.</p></td></tr> <tr><td>v6.1.0</td> <td><p>The <code>maxArrayLength</code> option is supported now; in particular, long arrays are truncated by default.</p></td></tr> <tr><td>v6.1.0</td> <td><p>The <code>showProxy</code> option is supported now.</p></td></tr> <tr><td>v0.3.0</td> <td><p><span>Added in: v0.3.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any JavaScript primitive or <code>Object</code>.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>showHidden</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the <code>object</code>'s non-enumerable symbols and properties will be included in the formatted result as well as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> entries. <strong>Default:</strong> <code>false</code>.</li> <li><code>depth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of times to recurse while formatting the <code>object</code>. This is useful for inspecting large complicated objects. To make it recurse up to the maximum call stack size pass <code>Infinity</code> or <code>null</code>. <strong>Default:</strong> <code>2</code>.</li> <li><code>colors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the output will be styled with ANSI color codes. Colors are customizable, see <a href="#util_customizing_util_inspect_colors">Customizing <code>util.inspect</code> colors</a>. <strong>Default:</strong> <code>false</code>.</li> <li><code>customInspect</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>false</code>, then custom <code>inspect(depth, opts)</code> functions will not be called. <strong>Default:</strong> <code>true</code>.</li> <li><code>showProxy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, then objects and functions that are <code>Proxy</code> objects will be introspected to show their <code>target</code> and <code>handler</code> objects. <strong>Default:</strong> <code>false</code>.</li> <li><code>maxArrayLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the maximum number of <code>Array</code>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> elements to include when formatting. Set to <code>null</code> or <code>Infinity</code> to show all elements. Set to <code>0</code> or negative to show no elements. <strong>Default:</strong> <code>100</code>.</li> <li><code>breakLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> The length at which an object's keys are split across multiple lines. Set to <code>Infinity</code> to format an object as a single line. <strong>Default:</strong> <code>60</code> for legacy compatibility.</li> <li><code>compact</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Setting this to <code>false</code> changes the default indentation to use a line break for each object key instead of lining up multiple properties in one line. It will also break text that is above the <code>breakLength</code> size into smaller and better readable chunks and indents objects the same as arrays. Note that no text will be reduced below 16 characters, no matter the <code>breakLength</code> size. For more information, see the example below. <strong>Default:</strong> <code>true</code>.</li> <li><code>sorted</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> If set to <code>true</code> or a function, all properties of an object and Set and Map entries will be sorted in the returned string. If set to <code>true</code> the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">default sort</a> is going to be used. If set to a function, it is used as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters">compare function</a>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The representation of passed object</li> </ul> <p>The <code>util.inspect()</code> method returns a string representation of <code>object</code> that is intended for debugging. The output of <code>util.inspect</code> may change at any time and should not be depended upon programmatically. Additional <code>options</code> may be passed that alter certain aspects of the formatted string. <code>util.inspect()</code> will use the constructor's name and/or <code>@@toStringTag</code> to make an identifiable tag for an inspected value.</p> <pre><code class="language-js">class Foo { get [Symbol.toStringTag]() { return 'bar'; } } class Bar {} const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); util.inspect(new Foo()); // 'Foo [bar] {}' util.inspect(new Bar()); // 'Bar {}' util.inspect(baz); // '[foo] {}' </code></pre> <p>The following example inspects all properties of the <code>util</code> object:</p> <pre><code class="language-js">const util = require('util'); console.log(util.inspect(util, { showHidden: true, depth: null })); </code></pre> <p>Values may supply their own custom <code>inspect(depth, opts)</code> functions, when called these receive the current <code>depth</code> in the recursive inspection, as well as the options object passed to <code>util.inspect()</code>.</p> <p>The following example highlights the difference with the <code>compact</code> option:</p> <pre><code class="language-js">const util = require('util'); const o = { a: [1, 2, [[ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' + 'eiusmod tempor incididunt ut labore et dolore magna aliqua.', 'test', 'foo']], 4], b: new Map([['za', 1], ['zb', 'test']]) }; console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); // This will print // { a: // [ 1, // 2, // [ [ 'Lorem ipsum dolor sit amet, consectetur [...]', // A long line // 'test', // 'foo' ] ], // 4 ], // b: Map { 'za' => 1, 'zb' => 'test' } } // Setting `compact` to false changes the output to be more reader friendly. console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); // { // a: [ // 1, // 2, // [ // [ // 'Lorem ipsum dolor sit amet, consectetur ' + // 'adipiscing elit, sed do eiusmod tempor ' + // 'incididunt ut labore et dolore magna ' + // 'aliqua., // 'test', // 'foo' // ] // ], // 4 // ], // b: Map { // 'za' => 1, // 'zb' => 'test' // } // } // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a // single line. // Reducing the `breakLength` will split the "Lorem ipsum" text in smaller // chunks. </code></pre> <p>Using the <code>showHidden</code> option allows to inspect <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> entries. If there are more entries than <code>maxArrayLength</code>, there is no guarantee which entries are displayed. That means retrieving the same <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> entries twice might actually result in a different output. Besides this any item might be collected at any point of time by the garbage collector if there is no strong reference left to that object. Therefore there is no guarantee to get a reliable output.</p> <pre><code class="language-js">const { inspect } = require('util'); const obj = { a: 1 }; const obj2 = { b: 2 }; const weakSet = new WeakSet([obj, obj2]); console.log(inspect(weakSet, { showHidden: true })); // WeakSet { { a: 1 }, { b: 2 } } </code></pre> <p>The <code>sorted</code> option makes sure the output is identical, no matter of the properties insertion order:</p> <pre><code class="language-js">const { inspect } = require('util'); const assert = require('assert'); const o1 = { b: [2, 3, 1], a: '`a` comes before `b`', c: new Set([2, 3, 1]) }; console.log(inspect(o1, { sorted: true })); // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set { 1, 2, 3 } } console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); // { c: Set { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } const o2 = { c: new Set([2, 1, 3]), a: '`a` comes before `b`', b: [2, 3, 1] }; assert.strict.equal( inspect(o1, { sorted: true }), inspect(o2, { sorted: true }) ); </code></pre> <p>Please note that <code>util.inspect()</code> is a synchronous method that is mainly intended as a debugging tool. Some input values can have a significant performance overhead that can block the event loop. Use this function with care and never in a hot code path.</p> <h3>Customizing <code>util.inspect</code> colors<span><a class="mark" href="#util_customizing_util_inspect_colors" id="util_customizing_util_inspect_colors">#</a></span></h3> <p>Color output (if enabled) of <code>util.inspect</code> is customizable globally via the <code>util.inspect.styles</code> and <code>util.inspect.colors</code> properties.</p> <p><code>util.inspect.styles</code> is a map associating a style name to a color from <code>util.inspect.colors</code>.</p> <p>The default styles and associated colors are:</p> <ul> <li><code>number</code> - <code>yellow</code></li> <li><code>boolean</code> - <code>yellow</code></li> <li><code>string</code> - <code>green</code></li> <li><code>date</code> - <code>magenta</code></li> <li><code>regexp</code> - <code>red</code></li> <li><code>null</code> - <code>bold</code></li> <li><code>undefined</code> - <code>grey</code></li> <li><code>special</code> - <code>cyan</code> (only applied to functions at this time)</li> <li><code>name</code> - (no styling)</li> </ul> <p>The predefined color codes are: <code>white</code>, <code>grey</code>, <code>black</code>, <code>blue</code>, <code>cyan</code>, <code>green</code>, <code>magenta</code>, <code>red</code> and <code>yellow</code>. There are also <code>bold</code>, <code>italic</code>, <code>underline</code> and <code>inverse</code> codes.</p> <p>Color styling uses ANSI control codes that may not be supported on all terminals.</p> <h3>Custom inspection functions on Objects<span><a class="mark" href="#util_custom_inspection_functions_on_objects" id="util_custom_inspection_functions_on_objects">#</a></span></h3> <p>Objects may also define their own <a href="#util_util_inspect_custom"><code>[util.inspect.custom](depth, opts)</code></a> (or the equivalent but deprecated <code>inspect(depth, opts)</code>) function, which <code>util.inspect()</code> will invoke and use the result of when inspecting the object:</p> <pre><code class="language-js">const util = require('util'); class Box { constructor(value) { this.value = value; } [util.inspect.custom](depth, options) { if (depth < 0) { return options.stylize('[Box]', 'special'); } const newOptions = Object.assign({}, options, { depth: options.depth === null ? null : options.depth - 1 }); // Five space padding because that's the size of "Box< ". const padding = ' '.repeat(5); const inner = util.inspect(this.value, newOptions) .replace(/\n/g, `\n${padding}`); return `${options.stylize('Box', 'special')}< ${inner} >`; } } const box = new Box(true); util.inspect(box); // Returns: "Box< true >" </code></pre> <p>Custom <code>[util.inspect.custom](depth, opts)</code> functions typically return a string but may return a value of any type that will be formatted accordingly by <code>util.inspect()</code>.</p> <pre><code class="language-js">const util = require('util'); const obj = { foo: 'this will not show up in the inspect() output' }; obj[util.inspect.custom] = (depth) => { return { bar: 'baz' }; }; util.inspect(obj); // Returns: "{ bar: 'baz' }" </code></pre> <h3>util.inspect.custom<span><a class="mark" href="#util_util_inspect_custom" id="util_util_inspect_custom">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.12.0</td> <td><p>This is now defined as a shared symbol.</p></td></tr> <tr><td>v6.6.0</td> <td><p><span>Added in: v6.6.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> that can be used to declare custom inspect functions.</li> </ul> <p>In addition to being accessible through <code>util.inspect.custom</code>, this symbol is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for">registered globally</a> and can be accessed in any environment as <code>Symbol.for('nodejs.util.inspect.custom')</code>.</p> <pre><code class="language-js">const inspect = Symbol.for('nodejs.util.inspect.custom'); class Password { constructor(value) { this.value = value; } toString() { return 'xxxxxxxx'; } [inspect]() { return `Password <${this.toString()}>`; } } const password = new Password('r0sebud'); console.log(password); // Prints Password <xxxxxxxx> </code></pre> <p>See <a href="#util_custom_inspection_functions_on_objects">Custom inspection functions on Objects</a> for more details.</p> <h3>util.inspect.defaultOptions<span><a class="mark" href="#util_util_inspect_defaultoptions" id="util_util_inspect_defaultoptions">#</a></span></h3> <div class="api_metadata"> <span>Added in: v6.4.0</span> </div> <p>The <code>defaultOptions</code> value allows customization of the default options used by <code>util.inspect</code>. This is useful for functions like <code>console.log</code> or <code>util.format</code> which implicitly call into <code>util.inspect</code>. It shall be set to an object containing one or more valid <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> options. Setting option properties directly is also supported.</p> <pre><code class="language-js">const util = require('util'); const arr = Array(101).fill(0); console.log(arr); // logs the truncated array util.inspect.defaultOptions.maxArrayLength = null; console.log(arr); // logs the full array </code></pre> <h2>util.isDeepStrictEqual(val1, val2)<span><a class="mark" href="#util_util_isdeepstrictequal_val1_val2" id="util_util_isdeepstrictequal_val1_val2">#</a></span></h2> <div class="api_metadata"> <span>Added in: v9.0.0</span> </div> <ul> <li><code>val1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>val2</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if there is deep strict equality between <code>val1</code> and <code>val2</code>. Otherwise, returns <code>false</code>.</p> <p>See <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a> for more information about deep strict equality.</p> <h2>util.promisify(original)<span><a class="mark" href="#util_util_promisify_original" id="util_util_promisify_original">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>original</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Takes a function following the common error-first callback style, i.e. taking an <code>(err, value) => ...</code> callback as the last argument, and returns a version that returns promises.</p> <pre><code class="language-js">const util = require('util'); const fs = require('fs'); const stat = util.promisify(fs.stat); stat('.').then((stats) => { // Do something with `stats` }).catch((error) => { // Handle the error. }); </code></pre> <p>Or, equivalently using <code>async function</code>s:</p> <pre><code class="language-js">const util = require('util'); const fs = require('fs'); const stat = util.promisify(fs.stat); async function callStat() { const stats = await stat('.'); console.log(`This directory is owned by ${stats.uid}`); } </code></pre> <p>If there is an <code>original[util.promisify.custom]</code> property present, <code>promisify</code> will return its value, see <a href="#util_custom_promisified_functions">Custom promisified functions</a>.</p> <p><code>promisify()</code> assumes that <code>original</code> is a function taking a callback as its final argument in all cases. If <code>original</code> is not a function, <code>promisify()</code> will throw an error. If <code>original</code> is a function but its last argument is not an error-first callback, it will still be passed an error-first callback as its last argument.</p> <h3>Custom promisified functions<span><a class="mark" href="#util_custom_promisified_functions" id="util_custom_promisified_functions">#</a></span></h3> <p>Using the <code>util.promisify.custom</code> symbol one can override the return value of <a href="#util_util_promisify_original"><code>util.promisify()</code></a>:</p> <pre><code class="language-js">const util = require('util'); function doSomething(foo, callback) { // ... } doSomething[util.promisify.custom] = (foo) => { return getPromiseSomehow(); }; const promisified = util.promisify(doSomething); console.log(promisified === doSomething[util.promisify.custom]); // prints 'true' </code></pre> <p>This can be useful for cases where the original function does not follow the standard format of taking an error-first callback as the last argument.</p> <p>For example, with a function that takes in <code>(foo, onSuccessCallback, onErrorCallback)</code>:</p> <pre><code class="language-js">doSomething[util.promisify.custom] = (foo) => { return new Promise((resolve, reject) => { doSomething(foo, resolve, reject); }); }; </code></pre> <p>If <code>promisify.custom</code> is defined but is not a function, <code>promisify()</code> will throw an error.</p> <h3>util.promisify.custom<span><a class="mark" href="#util_util_promisify_custom" id="util_util_promisify_custom">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a></li> </ul> <p>A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type"><symbol></a> that can be used to declare custom promisified variants of functions, see <a href="#util_custom_promisified_functions">Custom promisified functions</a>.</p> <h2>Class: util.TextDecoder<span><a class="mark" href="#util_class_util_textdecoder" id="util_class_util_textdecoder">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.3.0</span> </div> <p>An implementation of the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a> <code>TextDecoder</code> API.</p> <pre><code class="language-js">const decoder = new TextDecoder('shift_jis'); let string = ''; let buffer; while (buffer = getNextChunkSomehow()) { string += decoder.decode(buffer, { stream: true }); } string += decoder.decode(); // end-of-stream </code></pre> <h3>WHATWG Supported Encodings<span><a class="mark" href="#util_whatwg_supported_encodings" id="util_whatwg_supported_encodings">#</a></span></h3> <p>Per the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a>, the encodings supported by the <code>TextDecoder</code> API are outlined in the tables below. For each encoding, one or more aliases may be used.</p> <p>Different Node.js build configurations support different sets of encodings. While a very basic set of encodings is supported even on Node.js builds without ICU enabled, support for some encodings is provided only when Node.js is built with ICU and using the full ICU data (see <a href="intl.html">Internationalization</a>).</p> <h4>Encodings Supported Without ICU<span><a class="mark" href="#util_encodings_supported_without_icu" id="util_encodings_supported_without_icu">#</a></span></h4> <table><thead><tr><th>Encoding</th><th>Aliases</th></tr></thead><tbody><tr><td><code>'utf-8'</code></td><td><code>'unicode-1-1-utf-8'</code>, <code>'utf8'</code></td></tr><tr><td><code>'utf-16le'</code></td><td><code>'utf-16'</code></td></tr></tbody></table> <h4>Encodings Supported by Default (With ICU)<span><a class="mark" href="#util_encodings_supported_by_default_with_icu" id="util_encodings_supported_by_default_with_icu">#</a></span></h4> <table><thead><tr><th>Encoding</th><th>Aliases</th></tr></thead><tbody><tr><td><code>'utf-8'</code></td><td><code>'unicode-1-1-utf-8'</code>, <code>'utf8'</code></td></tr><tr><td><code>'utf-16le'</code></td><td><code>'utf-16'</code></td></tr><tr><td><code>'utf-16be'</code></td><td></td></tr></tbody></table> <h4>Encodings Requiring Full ICU Data<span><a class="mark" href="#util_encodings_requiring_full_icu_data" id="util_encodings_requiring_full_icu_data">#</a></span></h4> <table><thead><tr><th>Encoding</th><th>Aliases</th></tr></thead><tbody><tr><td><code>'ibm866'</code></td><td><code>'866'</code>, <code>'cp866'</code>, <code>'csibm866'</code></td></tr><tr><td><code>'iso-8859-2'</code></td><td><code>'csisolatin2'</code>, <code>'iso-ir-101'</code>, <code>'iso8859-2'</code>, <code>'iso88592'</code>, <code>'iso_8859-2'</code>, <code>'iso_8859-2:1987'</code>, <code>'l2'</code>, <code>'latin2'</code></td></tr><tr><td><code>'iso-8859-3'</code></td><td><code>'csisolatin3'</code>, <code>'iso-ir-109'</code>, <code>'iso8859-3'</code>, <code>'iso88593'</code>, <code>'iso_8859-3'</code>, <code>'iso_8859-3:1988'</code>, <code>'l3'</code>, <code>'latin3'</code></td></tr><tr><td><code>'iso-8859-4'</code></td><td><code>'csisolatin4'</code>, <code>'iso-ir-110'</code>, <code>'iso8859-4'</code>, <code>'iso88594'</code>, <code>'iso_8859-4'</code>, <code>'iso_8859-4:1988'</code>, <code>'l4'</code>, <code>'latin4'</code></td></tr><tr><td><code>'iso-8859-5'</code></td><td><code>'csisolatincyrillic'</code>, <code>'cyrillic'</code>, <code>'iso-ir-144'</code>, <code>'iso8859-5'</code>, <code>'iso88595'</code>, <code>'iso_8859-5'</code>, <code>'iso_8859-5:1988'</code></td></tr><tr><td><code>'iso-8859-6'</code></td><td><code>'arabic'</code>, <code>'asmo-708'</code>, <code>'csiso88596e'</code>, <code>'csiso88596i'</code>, <code>'csisolatinarabic'</code>, <code>'ecma-114'</code>, <code>'iso-8859-6-e'</code>, <code>'iso-8859-6-i'</code>, <code>'iso-ir-127'</code>, <code>'iso8859-6'</code>, <code>'iso88596'</code>, <code>'iso_8859-6'</code>, <code>'iso_8859-6:1987'</code></td></tr><tr><td><code>'iso-8859-7'</code></td><td><code>'csisolatingreek'</code>, <code>'ecma-118'</code>, <code>'elot_928'</code>, <code>'greek'</code>, <code>'greek8'</code>, <code>'iso-ir-126'</code>, <code>'iso8859-7'</code>, <code>'iso88597'</code>, <code>'iso_8859-7'</code>, <code>'iso_8859-7:1987'</code>, <code>'sun_eu_greek'</code></td></tr><tr><td><code>'iso-8859-8'</code></td><td><code>'csiso88598e'</code>, <code>'csisolatinhebrew'</code>, <code>'hebrew'</code>, <code>'iso-8859-8-e'</code>, <code>'iso-ir-138'</code>, <code>'iso8859-8'</code>, <code>'iso88598'</code>, <code>'iso_8859-8'</code>, <code>'iso_8859-8:1988'</code>, <code>'visual'</code></td></tr><tr><td><code>'iso-8859-8-i'</code></td><td><code>'csiso88598i'</code>, <code>'logical'</code></td></tr><tr><td><code>'iso-8859-10'</code></td><td><code>'csisolatin6'</code>, <code>'iso-ir-157'</code>, <code>'iso8859-10'</code>, <code>'iso885910'</code>, <code>'l6'</code>, <code>'latin6'</code></td></tr><tr><td><code>'iso-8859-13'</code></td><td><code>'iso8859-13'</code>, <code>'iso885913'</code></td></tr><tr><td><code>'iso-8859-14'</code></td><td><code>'iso8859-14'</code>, <code>'iso885914'</code></td></tr><tr><td><code>'iso-8859-15'</code></td><td><code>'csisolatin9'</code>, <code>'iso8859-15'</code>, <code>'iso885915'</code>, <code>'iso_8859-15'</code>, <code>'l9'</code></td></tr><tr><td><code>'koi8-r'</code></td><td><code>'cskoi8r'</code>, <code>'koi'</code>, <code>'koi8'</code>, <code>'koi8_r'</code></td></tr><tr><td><code>'koi8-u'</code></td><td><code>'koi8-ru'</code></td></tr><tr><td><code>'macintosh'</code></td><td><code>'csmacintosh'</code>, <code>'mac'</code>, <code>'x-mac-roman'</code></td></tr><tr><td><code>'windows-874'</code></td><td><code>'dos-874'</code>, <code>'iso-8859-11'</code>, <code>'iso8859-11'</code>, <code>'iso885911'</code>, <code>'tis-620'</code></td></tr><tr><td><code>'windows-1250'</code></td><td><code>'cp1250'</code>, <code>'x-cp1250'</code></td></tr><tr><td><code>'windows-1251'</code></td><td><code>'cp1251'</code>, <code>'x-cp1251'</code></td></tr><tr><td><code>'windows-1252'</code></td><td><code>'ansi_x3.4-1968'</code>, <code>'ascii'</code>, <code>'cp1252'</code>, <code>'cp819'</code>, <code>'csisolatin1'</code>, <code>'ibm819'</code>, <code>'iso-8859-1'</code>, <code>'iso-ir-100'</code>, <code>'iso8859-1'</code>, <code>'iso88591'</code>, <code>'iso_8859-1'</code>, <code>'iso_8859-1:1987'</code>, <code>'l1'</code>, <code>'latin1'</code>, <code>'us-ascii'</code>, <code>'x-cp1252'</code></td></tr><tr><td><code>'windows-1253'</code></td><td><code>'cp1253'</code>, <code>'x-cp1253'</code></td></tr><tr><td><code>'windows-1254'</code></td><td><code>'cp1254'</code>, <code>'csisolatin5'</code>, <code>'iso-8859-9'</code>, <code>'iso-ir-148'</code>, <code>'iso8859-9'</code>, <code>'iso88599'</code>, <code>'iso_8859-9'</code>, <code>'iso_8859-9:1989'</code>, <code>'l5'</code>, <code>'latin5'</code>, <code>'x-cp1254'</code></td></tr><tr><td><code>'windows-1255'</code></td><td><code>'cp1255'</code>, <code>'x-cp1255'</code></td></tr><tr><td><code>'windows-1256'</code></td><td><code>'cp1256'</code>, <code>'x-cp1256'</code></td></tr><tr><td><code>'windows-1257'</code></td><td><code>'cp1257'</code>, <code>'x-cp1257'</code></td></tr><tr><td><code>'windows-1258'</code></td><td><code>'cp1258'</code>, <code>'x-cp1258'</code></td></tr><tr><td><code>'x-mac-cyrillic'</code></td><td><code>'x-mac-ukrainian'</code></td></tr><tr><td><code>'gbk'</code></td><td><code>'chinese'</code>, <code>'csgb2312'</code>, <code>'csiso58gb231280'</code>, <code>'gb2312'</code>, <code>'gb_2312'</code>, <code>'gb_2312-80'</code>, <code>'iso-ir-58'</code>, <code>'x-gbk'</code></td></tr><tr><td><code>'gb18030'</code></td><td></td></tr><tr><td><code>'big5'</code></td><td><code>'big5-hkscs'</code>, <code>'cn-big5'</code>, <code>'csbig5'</code>, <code>'x-x-big5'</code></td></tr><tr><td><code>'euc-jp'</code></td><td><code>'cseucpkdfmtjapanese'</code>, <code>'x-euc-jp'</code></td></tr><tr><td><code>'iso-2022-jp'</code></td><td><code>'csiso2022jp'</code></td></tr><tr><td><code>'shift_jis'</code></td><td><code>'csshiftjis'</code>, <code>'ms932'</code>, <code>'ms_kanji'</code>, <code>'shift-jis'</code>, <code>'sjis'</code>, <code>'windows-31j'</code>, <code>'x-sjis'</code></td></tr><tr><td><code>'euc-kr'</code></td><td><code>'cseuckr'</code>, <code>'csksc56011987'</code>, <code>'iso-ir-149'</code>, <code>'korean'</code>, <code>'ks_c_5601-1987'</code>, <code>'ks_c_5601-1989'</code>, <code>'ksc5601'</code>, <code>'ksc_5601'</code>, <code>'windows-949'</code></td></tr></tbody></table> <p>The <code>'iso-8859-16'</code> encoding listed in the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a> is not supported.</p> <h3>new TextDecoder([encoding[, options]])<span><a class="mark" href="#util_new_textdecoder_encoding_options" id="util_new_textdecoder_encoding_options">#</a></span></h3> <ul> <li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Identifies the <code>encoding</code> that this <code>TextDecoder</code> instance supports. <strong>Default:</strong> <code>'utf-8'</code>.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>fatal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if decoding failures are fatal. This option is only supported when ICU is enabled (see <a href="intl.html">Internationalization</a>). <strong>Default:</strong> <code>false</code>.</li> <li><code>ignoreBOM</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, the <code>TextDecoder</code> will include the byte order mark in the decoded result. When <code>false</code>, the byte order mark will be removed from the output. This option is only used when <code>encoding</code> is <code>'utf-8'</code>, <code>'utf-16be'</code> or <code>'utf-16le'</code>. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> </ul> <p>Creates an new <code>TextDecoder</code> instance. The <code>encoding</code> may specify one of the supported encodings or an alias.</p> <h3>textDecoder.decode([input[, options]])<span><a class="mark" href="#util_textdecoder_decode_input_options" id="util_textdecoder_decode_input_options">#</a></span></h3> <ul> <li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> An <code>ArrayBuffer</code>, <code>DataView</code> or <code>Typed Array</code> instance containing the encoded data.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>stream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <code>true</code> if additional chunks of data are expected. <strong>Default:</strong> <code>false</code>.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>Decodes the <code>input</code> and returns a string. If <code>options.stream</code> is <code>true</code>, any incomplete byte sequences occurring at the end of the <code>input</code> are buffered internally and emitted after the next call to <code>textDecoder.decode()</code>.</p> <p>If <code>textDecoder.fatal</code> is <code>true</code>, decoding errors that occur will result in a <code>TypeError</code> being thrown.</p> <h3>textDecoder.encoding<span><a class="mark" href="#util_textdecoder_encoding" id="util_textdecoder_encoding">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The encoding supported by the <code>TextDecoder</code> instance.</p> <h3>textDecoder.fatal<span><a class="mark" href="#util_textdecoder_fatal" id="util_textdecoder_fatal">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The value will be <code>true</code> if decoding errors result in a <code>TypeError</code> being thrown.</p> <h3>textDecoder.ignoreBOM<span><a class="mark" href="#util_textdecoder_ignorebom" id="util_textdecoder_ignorebom">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>The value will be <code>true</code> if the decoding result will include the byte order mark.</p> <h2>Class: util.TextEncoder<span><a class="mark" href="#util_class_util_textencoder" id="util_class_util_textencoder">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.3.0</span> </div> <p>An implementation of the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a> <code>TextEncoder</code> API. All instances of <code>TextEncoder</code> only support UTF-8 encoding.</p> <pre><code class="language-js">const encoder = new TextEncoder(); const uint8array = encoder.encode('this is some data'); </code></pre> <h3>textEncoder.encode([input])<span><a class="mark" href="#util_textencoder_encode_input" id="util_textencoder_encode_input">#</a></span></h3> <ul> <li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The text to encode. <strong>Default:</strong> an empty string.</li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type"><Uint8Array></a></li> </ul> <p>UTF-8 encodes the <code>input</code> string and returns a <code>Uint8Array</code> containing the encoded bytes.</p> <h3>textEncoder.encoding<span><a class="mark" href="#util_textencoder_encoding" id="util_textencoder_encoding">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The encoding supported by the <code>TextEncoder</code> instance. Always set to <code>'utf-8'</code>.</p> <h2>util.types<span><a class="mark" href="#util_util_types" id="util_util_types">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <p><code>util.types</code> provides a number of type checks for different kinds of built-in objects. Unlike <code>instanceof</code> or <code>Object.prototype.toString.call(value)</code>, these checks do not inspect properties of the object that are accessible from JavaScript (like their prototype), and usually have the overhead of calling into C++.</p> <p>The result generally does not make any guarantees about what kinds of properties or behavior a value exposes in JavaScript. They are primarily useful for addon developers who prefer to do type checking in JavaScript.</p> <h3>util.types.isAnyArrayBuffer(value)<span><a class="mark" href="#util_util_types_isanyarraybuffer_value" id="util_util_types_isanyarraybuffer_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instance.</p> <p>See also <a href="#util_util_types_isarraybuffer_value"><code>util.types.isArrayBuffer()</code></a> and <a href="#util_util_types_issharedarraybuffer_value"><code>util.types.isSharedArrayBuffer()</code></a>.</p> <pre><code class="language-js">util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true </code></pre> <h3>util.types.isArgumentsObject(value)<span><a class="mark" href="#util_util_types_isargumentsobject_value" id="util_util_types_isargumentsobject_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is an <code>arguments</code> object.</p> <!-- eslint-disable prefer-rest-params --> <pre><code class="language-js">function foo() { util.types.isArgumentsObject(arguments); // Returns true } </code></pre> <h3>util.types.isArrayBuffer(value)<span><a class="mark" href="#util_util_types_isarraybuffer_value" id="util_util_types_isarraybuffer_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> instance. This does <em>not</em> include <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instances. Usually, it is desirable to test for both; See <a href="#util_util_types_isanyarraybuffer_value"><code>util.types.isAnyArrayBuffer()</code></a> for that.</p> <pre><code class="language-js">util.types.isArrayBuffer(new ArrayBuffer()); // Returns true util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false </code></pre> <h3>util.types.isAsyncFunction(value)<span><a class="mark" href="#util_util_types_isasyncfunction_value" id="util_util_types_isasyncfunction_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async function</a>. Note that this only reports back what the JavaScript engine is seeing; in particular, the return value may not match the original source code if a transpilation tool was used.</p> <pre><code class="language-js">util.types.isAsyncFunction(function foo() {}); // Returns false util.types.isAsyncFunction(async function foo() {}); // Returns true </code></pre> <h3>util.types.isBigInt64Array(value)<span><a class="mark" href="#util_util_types_isbigint64array_value" id="util_util_types_isbigint64array_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a <code>BigInt64Array</code> instance.</p> <pre><code class="language-js">util.types.isBigInt64Array(new BigInt64Array()); // Returns true util.types.isBigInt64Array(new BigUint64Array()); // Returns false </code></pre> <h3>util.types.isBigUint64Array(value)<span><a class="mark" href="#util_util_types_isbiguint64array_value" id="util_util_types_isbiguint64array_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a <code>BigUint64Array</code> instance.</p> <pre><code class="language-js">util.types.isBigUint64Array(new BigInt64Array()); // Returns false util.types.isBigUint64Array(new BigUint64Array()); // Returns true </code></pre> <h3>util.types.isBooleanObject(value)<span><a class="mark" href="#util_util_types_isbooleanobject_value" id="util_util_types_isbooleanobject_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a boolean object, e.g. created by <code>new Boolean()</code>.</p> <pre><code class="language-js">util.types.isBooleanObject(false); // Returns false util.types.isBooleanObject(true); // Returns false util.types.isBooleanObject(new Boolean(false)); // Returns true util.types.isBooleanObject(new Boolean(true)); // Returns true util.types.isBooleanObject(Boolean(false)); // Returns false util.types.isBooleanObject(Boolean(true)); // Returns false </code></pre> <h3>util.types.isBoxedPrimitive(value)<span><a class="mark" href="#util_util_types_isboxedprimitive_value" id="util_util_types_isboxedprimitive_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.11.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is any boxed primitive object, e.g. created by <code>new Boolean()</code>, <code>new String()</code> or <code>Object(Symbol())</code>.</p> <p>For example:</p> <pre><code class="language-js">util.types.isBoxedPrimitive(false); // Returns false util.types.isBoxedPrimitive(new Boolean(false)); // Returns true util.types.isBoxedPrimitive(Symbol('foo')); // Returns false util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true </code></pre> <h3>util.types.isDataView(value)<span><a class="mark" href="#util_util_types_isdataview_value" id="util_util_types_isdataview_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><code>DataView</code></a> instance.</p> <pre><code class="language-js">const ab = new ArrayBuffer(20); util.types.isDataView(new DataView(ab)); // Returns true util.types.isDataView(new Float64Array()); // Returns false </code></pre> <p>See also <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView"><code>ArrayBuffer.isView()</code></a>.</p> <h3>util.types.isDate(value)<span><a class="mark" href="#util_util_types_isdate_value" id="util_util_types_isdate_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date"><code>Date</code></a> instance.</p> <pre><code class="language-js">util.types.isDate(new Date()); // Returns true </code></pre> <h3>util.types.isExternal(value)<span><a class="mark" href="#util_util_types_isexternal_value" id="util_util_types_isexternal_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a native <code>External</code> value.</p> <h3>util.types.isFloat32Array(value)<span><a class="mark" href="#util_util_types_isfloat32array_value" id="util_util_types_isfloat32array_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array"><code>Float32Array</code></a> instance.</p> <pre><code class="language-js">util.types.isFloat32Array(new ArrayBuffer()); // Returns false util.types.isFloat32Array(new Float32Array()); // Returns true util.types.isFloat32Array(new Float64Array()); // Returns false </code></pre> <h3>util.types.isFloat64Array(value)<span><a class="mark" href="#util_util_types_isfloat64array_value" id="util_util_types_isfloat64array_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array"><code>Float64Array</code></a> instance.</p> <pre><code class="language-js">util.types.isFloat64Array(new ArrayBuffer()); // Returns false util.types.isFloat64Array(new Uint8Array()); // Returns false util.types.isFloat64Array(new Float64Array()); // Returns true </code></pre> <h3>util.types.isGeneratorFunction(value)<span><a class="mark" href="#util_util_types_isgeneratorfunction_value" id="util_util_types_isgeneratorfunction_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a generator function. Note that this only reports back what the JavaScript engine is seeing; in particular, the return value may not match the original source code if a transpilation tool was used.</p> <pre><code class="language-js">util.types.isGeneratorFunction(function foo() {}); // Returns false util.types.isGeneratorFunction(function* foo() {}); // Returns true </code></pre> <h3>util.types.isGeneratorObject(value)<span><a class="mark" href="#util_util_types_isgeneratorobject_value" id="util_util_types_isgeneratorobject_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a generator object as returned from a built-in generator function. Note that this only reports back what the JavaScript engine is seeing; in particular, the return value may not match the original source code if a transpilation tool was used.</p> <pre><code class="language-js">function* foo() {} const generator = foo(); util.types.isGeneratorObject(generator); // Returns true </code></pre> <h3>util.types.isInt8Array(value)<span><a class="mark" href="#util_util_types_isint8array_value" id="util_util_types_isint8array_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array"><code>Int8Array</code></a> instance.</p> <pre><code class="language-js">util.types.isInt8Array(new ArrayBuffer()); // Returns false util.types.isInt8Array(new Int8Array()); // Returns true util.types.isInt8Array(new Float64Array()); // Returns false </code></pre> <h3>util.types.isInt16Array(value)<span><a class="mark" href="#util_util_types_isint16array_value" id="util_util_types_isint16array_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array"><code>Int16Array</code></a> instance.</p> <pre><code class="language-js">util.types.isInt16Array(new ArrayBuffer()); // Returns false util.types.isInt16Array(new Int16Array()); // Returns true util.types.isInt16Array(new Float64Array()); // Returns false </code></pre> <h3>util.types.isInt32Array(value)<span><a class="mark" href="#util_util_types_isint32array_value" id="util_util_types_isint32array_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array"><code>Int32Array</code></a> instance.</p> <pre><code class="language-js">util.types.isInt32Array(new ArrayBuffer()); // Returns false util.types.isInt32Array(new Int32Array()); // Returns true util.types.isInt32Array(new Float64Array()); // Returns false </code></pre> <h3>util.types.isMap(value)<span><a class="mark" href="#util_util_types_ismap_value" id="util_util_types_ismap_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> instance.</p> <pre><code class="language-js">util.types.isMap(new Map()); // Returns true </code></pre> <h3>util.types.isMapIterator(value)<span><a class="mark" href="#util_util_types_ismapiterator_value" id="util_util_types_ismapiterator_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is an iterator returned for a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> instance.</p> <pre><code class="language-js">const map = new Map(); util.types.isMapIterator(map.keys()); // Returns true util.types.isMapIterator(map.values()); // Returns true util.types.isMapIterator(map.entries()); // Returns true util.types.isMapIterator(map[Symbol.iterator]()); // Returns true </code></pre> <h3>util.types.isModuleNamespaceObject(value)<span><a class="mark" href="#util_util_types_ismodulenamespaceobject_value" id="util_util_types_ismodulenamespaceobject_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is an instance of a <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects">Module Namespace Object</a>.</p> <!-- eslint-skip --> <pre><code class="language-js">import * as ns from './a.js'; util.types.isModuleNamespaceObject(ns); // Returns true </code></pre> <h3>util.types.isNativeError(value)<span><a class="mark" href="#util_util_types_isnativeerror_value" id="util_util_types_isnativeerror_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is an instance of a built-in <a href="#errors_class_error"><code>Error</code></a> type.</p> <pre><code class="language-js">util.types.isNativeError(new Error()); // Returns true util.types.isNativeError(new TypeError()); // Returns true util.types.isNativeError(new RangeError()); // Returns true </code></pre> <h3>util.types.isNumberObject(value)<span><a class="mark" href="#util_util_types_isnumberobject_value" id="util_util_types_isnumberobject_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a number object, e.g. created by <code>new Number()</code>.</p> <pre><code class="language-js">util.types.isNumberObject(0); // Returns false util.types.isNumberObject(new Number(0)); // Returns true </code></pre> <h3>util.types.isPromise(value)<span><a class="mark" href="#util_util_types_ispromise_value" id="util_util_types_ispromise_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><code>Promise</code></a>.</p> <pre><code class="language-js">util.types.isPromise(Promise.resolve(42)); // Returns true </code></pre> <h3>util.types.isProxy(value)<span><a class="mark" href="#util_util_types_isproxy_value" id="util_util_types_isproxy_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy"><code>Proxy</code></a> instance.</p> <pre><code class="language-js">const target = {}; const proxy = new Proxy(target, {}); util.types.isProxy(target); // Returns false util.types.isProxy(proxy); // Returns true </code></pre> <h3>util.types.isRegExp(value)<span><a class="mark" href="#util_util_types_isregexp_value" id="util_util_types_isregexp_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a regular expression object.</p> <pre><code class="language-js">util.types.isRegExp(/abc/); // Returns true util.types.isRegExp(new RegExp('abc')); // Returns true </code></pre> <h3>util.types.isSet(value)<span><a class="mark" href="#util_util_types_isset_value" id="util_util_types_isset_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a> instance.</p> <pre><code class="language-js">util.types.isSet(new Set()); // Returns true </code></pre> <h3>util.types.isSetIterator(value)<span><a class="mark" href="#util_util_types_issetiterator_value" id="util_util_types_issetiterator_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is an iterator returned for a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a> instance.</p> <pre><code class="language-js">const set = new Set(); util.types.isSetIterator(set.keys()); // Returns true util.types.isSetIterator(set.values()); // Returns true util.types.isSetIterator(set.entries()); // Returns true util.types.isSetIterator(set[Symbol.iterator]()); // Returns true </code></pre> <h3>util.types.isSharedArrayBuffer(value)<span><a class="mark" href="#util_util_types_issharedarraybuffer_value" id="util_util_types_issharedarraybuffer_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instance. This does <em>not</em> include <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> instances. Usually, it is desirable to test for both; See <a href="#util_util_types_isanyarraybuffer_value"><code>util.types.isAnyArrayBuffer()</code></a> for that.</p> <pre><code class="language-js">util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true </code></pre> <h3>util.types.isStringObject(value)<span><a class="mark" href="#util_util_types_isstringobject_value" id="util_util_types_isstringobject_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a string object, e.g. created by <code>new String()</code>.</p> <pre><code class="language-js">util.types.isStringObject('foo'); // Returns false util.types.isStringObject(new String('foo')); // Returns true </code></pre> <h3>util.types.isSymbolObject(value)<span><a class="mark" href="#util_util_types_issymbolobject_value" id="util_util_types_issymbolobject_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a symbol object, created by calling <code>Object()</code> on a <code>Symbol</code> primitive.</p> <pre><code class="language-js">const symbol = Symbol('foo'); util.types.isSymbolObject(symbol); // Returns false util.types.isSymbolObject(Object(symbol)); // Returns true </code></pre> <h3>util.types.isTypedArray(value)<span><a class="mark" href="#util_util_types_istypedarray_value" id="util_util_types_istypedarray_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instance.</p> <pre><code class="language-js">util.types.isTypedArray(new ArrayBuffer()); // Returns false util.types.isTypedArray(new Uint8Array()); // Returns true util.types.isTypedArray(new Float64Array()); // Returns true </code></pre> <p>See also <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView"><code>ArrayBuffer.isView()</code></a>.</p> <h3>util.types.isUint8Array(value)<span><a class="mark" href="#util_util_types_isuint8array_value" id="util_util_types_isuint8array_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> instance.</p> <pre><code class="language-js">util.types.isUint8Array(new ArrayBuffer()); // Returns false util.types.isUint8Array(new Uint8Array()); // Returns true util.types.isUint8Array(new Float64Array()); // Returns false </code></pre> <h3>util.types.isUint8ClampedArray(value)<span><a class="mark" href="#util_util_types_isuint8clampedarray_value" id="util_util_types_isuint8clampedarray_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray"><code>Uint8ClampedArray</code></a> instance.</p> <pre><code class="language-js">util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true util.types.isUint8ClampedArray(new Float64Array()); // Returns false </code></pre> <h3>util.types.isUint16Array(value)<span><a class="mark" href="#util_util_types_isuint16array_value" id="util_util_types_isuint16array_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array"><code>Uint16Array</code></a> instance.</p> <pre><code class="language-js">util.types.isUint16Array(new ArrayBuffer()); // Returns false util.types.isUint16Array(new Uint16Array()); // Returns true util.types.isUint16Array(new Float64Array()); // Returns false </code></pre> <h3>util.types.isUint32Array(value)<span><a class="mark" href="#util_util_types_isuint32array_value" id="util_util_types_isuint32array_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array"><code>Uint32Array</code></a> instance.</p> <pre><code class="language-js">util.types.isUint32Array(new ArrayBuffer()); // Returns false util.types.isUint32Array(new Uint32Array()); // Returns true util.types.isUint32Array(new Float64Array()); // Returns false </code></pre> <h3>util.types.isWeakMap(value)<span><a class="mark" href="#util_util_types_isweakmap_value" id="util_util_types_isweakmap_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> instance.</p> <pre><code class="language-js">util.types.isWeakMap(new WeakMap()); // Returns true </code></pre> <h3>util.types.isWeakSet(value)<span><a class="mark" href="#util_util_types_isweakset_value" id="util_util_types_isweakset_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> instance.</p> <pre><code class="language-js">util.types.isWeakSet(new WeakSet()); // Returns true </code></pre> <h3>util.types.isWebAssemblyCompiledModule(value)<span><a class="mark" href="#util_util_types_iswebassemblycompiledmodule_value" id="util_util_types_iswebassemblycompiledmodule_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module"><code>WebAssembly.Module</code></a> instance.</p> <pre><code class="language-js">const module = new WebAssembly.Module(wasmBuffer); util.types.isWebAssemblyCompiledModule(module); // Returns true </code></pre> <h2>Deprecated APIs<span><a class="mark" href="#util_deprecated_apis" id="util_deprecated_apis">#</a></span></h2> <p>The following APIs are deprecated and should no longer be used. Existing applications and modules should be updated to find alternative approaches.</p> <h3>util._extend(target, source)<span><a class="mark" href="#util_util_extend_target_source" id="util_util_extend_target_source">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.5</span><span>Deprecated since: v6.0.0</span> </div> <ul> <li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign"><code>Object.assign()</code></a> instead.</div><p></p> <p>The <code>util._extend()</code> method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.</p> <p>It is deprecated and should not be used in new code. JavaScript comes with very similar built-in functionality through <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign"><code>Object.assign()</code></a>.</p> <h3>util.debug(string)<span><a class="mark" href="#util_util_debug_string" id="util_util_debug_string">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span><span>Deprecated since: v0.11.3</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#console_console_error_data_args"><code>console.error()</code></a> instead.</div><p></p> <ul> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The message to print to <code>stderr</code></li> </ul> <p>Deprecated predecessor of <code>console.error</code>.</p> <h3>util.error([...strings])<span><a class="mark" href="#util_util_error_strings" id="util_util_error_strings">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span><span>Deprecated since: v0.11.3</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#console_console_error_data_args"><code>console.error()</code></a> instead.</div><p></p> <ul> <li><code>...strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The message to print to <code>stderr</code></li> </ul> <p>Deprecated predecessor of <code>console.error</code>.</p> <h3>util.isArray(object)<span><a class="mark" href="#util_util_isarray_object" id="util_util_isarray_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray"><code>Array.isArray()</code></a> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Alias for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray"><code>Array.isArray()</code></a>.</p> <p>Returns <code>true</code> if the given <code>object</code> is an <code>Array</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isArray([]); // Returns: true util.isArray(new Array()); // Returns: true util.isArray({}); // Returns: false </code></pre> <h3>util.isBoolean(object)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L197">[src]</a><span><a class="mark" href="#util_util_isboolean_object" id="util_util_isboolean_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'boolean'</code> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is a <code>Boolean</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isBoolean(1); // Returns: false util.isBoolean(0); // Returns: false util.isBoolean(false); // Returns: true </code></pre> <h3>util.isBuffer(object)<span><a class="mark" href="#util_util_isbuffer_object" id="util_util_isbuffer_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_isbuffer_obj"><code>Buffer.isBuffer()</code></a> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is a <code>Buffer</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isBuffer({ length: 0 }); // Returns: false util.isBuffer([]); // Returns: false util.isBuffer(Buffer.from('hello world')); // Returns: true </code></pre> <h3>util.isDate(object)<span><a class="mark" href="#util_util_isdate_object" id="util_util_isdate_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#util_util_types_isdate_value"><code>util.types.isDate()</code></a> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is a <code>Date</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isDate(new Date()); // Returns: true util.isDate(Date()); // false (without 'new' returns a String) util.isDate({}); // Returns: false </code></pre> <h3>util.isError(object)<span><a class="mark" href="#util_util_iserror_object" id="util_util_iserror_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#util_util_types_isnativeerror_value"><code>util.types.isNativeError()</code></a> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is an <a href="#errors_class_error"><code>Error</code></a>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isError(new Error()); // Returns: true util.isError(new TypeError()); // Returns: true util.isError({ name: 'Error', message: 'an error occurred' }); // Returns: false </code></pre> <p>Note that this method relies on <code>Object.prototype.toString()</code> behavior. It is possible to obtain an incorrect result when the <code>object</code> argument manipulates <code>@@toStringTag</code>.</p> <pre><code class="language-js">const util = require('util'); const obj = { name: 'Error', message: 'an error occurred' }; util.isError(obj); // Returns: false obj[Symbol.toStringTag] = 'Error'; util.isError(obj); // Returns: true </code></pre> <h3>util.isFunction(object)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L229">[src]</a><span><a class="mark" href="#util_util_isfunction_object" id="util_util_isfunction_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'function'</code> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is a <code>Function</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); function Foo() {} const Bar = () => {}; util.isFunction({}); // Returns: false util.isFunction(Foo); // Returns: true util.isFunction(Bar); // Returns: true </code></pre> <h3>util.isNull(object)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L201">[src]</a><span><a class="mark" href="#util_util_isnull_object" id="util_util_isnull_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>value === null</code> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is strictly <code>null</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isNull(0); // Returns: false util.isNull(undefined); // Returns: false util.isNull(null); // Returns: true </code></pre> <h3>util.isNullOrUndefined(object)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L205">[src]</a><span><a class="mark" href="#util_util_isnullorundefined_object" id="util_util_isnullorundefined_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>value === undefined || value === null</code> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is <code>null</code> or <code>undefined</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isNullOrUndefined(0); // Returns: false util.isNullOrUndefined(undefined); // Returns: true util.isNullOrUndefined(null); // Returns: true </code></pre> <h3>util.isNumber(object)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L209">[src]</a><span><a class="mark" href="#util_util_isnumber_object" id="util_util_isnumber_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'number'</code> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is a <code>Number</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isNumber(false); // Returns: false util.isNumber(Infinity); // Returns: true util.isNumber(0); // Returns: true util.isNumber(NaN); // Returns: true </code></pre> <h3>util.isObject(object)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L225">[src]</a><span><a class="mark" href="#util_util_isobject_object" id="util_util_isobject_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>value !== null && typeof value === 'object'</code> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is strictly an <code>Object</code> <strong>and</strong> not a <code>Function</code> (even though functions are objects in JavaScript). Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isObject(5); // Returns: false util.isObject(null); // Returns: false util.isObject({}); // Returns: true util.isObject(() => {}); // Returns: false </code></pre> <h3>util.isPrimitive(object)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L233">[src]</a><span><a class="mark" href="#util_util_isprimitive_object" id="util_util_isprimitive_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>(typeof value !== 'object' && typeof value !== 'function') || value === null</code> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is a primitive type. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isPrimitive(5); // Returns: true util.isPrimitive('foo'); // Returns: true util.isPrimitive(false); // Returns: true util.isPrimitive(null); // Returns: true util.isPrimitive(undefined); // Returns: true util.isPrimitive({}); // Returns: false util.isPrimitive(() => {}); // Returns: false util.isPrimitive(/^$/); // Returns: false util.isPrimitive(new Date()); // Returns: false </code></pre> <h3>util.isRegExp(object)<span><a class="mark" href="#util_util_isregexp_object" id="util_util_isregexp_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is a <code>RegExp</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isRegExp(/some regexp/); // Returns: true util.isRegExp(new RegExp('another regexp')); // Returns: true util.isRegExp({}); // Returns: false </code></pre> <h3>util.isString(object)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L213">[src]</a><span><a class="mark" href="#util_util_isstring_object" id="util_util_isstring_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'string'</code> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is a <code>string</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isString(''); // Returns: true util.isString('foo'); // Returns: true util.isString(String('foo')); // Returns: true util.isString(5); // Returns: false </code></pre> <h3>util.isSymbol(object)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L217">[src]</a><span><a class="mark" href="#util_util_issymbol_object" id="util_util_issymbol_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'symbol'</code> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is a <code>Symbol</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); util.isSymbol(5); // Returns: false util.isSymbol('foo'); // Returns: false util.isSymbol(Symbol('foo')); // Returns: true </code></pre> <h3>util.isUndefined(object)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L221">[src]</a><span><a class="mark" href="#util_util_isundefined_object" id="util_util_isundefined_object">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>value === undefined</code> instead.</div><p></p> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>object</code> is <code>undefined</code>. Otherwise, returns <code>false</code>.</p> <pre><code class="language-js">const util = require('util'); const foo = undefined; util.isUndefined(5); // Returns: false util.isUndefined(foo); // Returns: true util.isUndefined(null); // Returns: false </code></pre> <h3>util.log(string)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/util.js#L255">[src]</a><span><a class="mark" href="#util_util_log_string" id="util_util_log_string">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span><span>Deprecated since: v6.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use a third party module instead.</div><p></p> <ul> <li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>util.log()</code> method prints the given <code>string</code> to <code>stdout</code> with an included timestamp.</p> <pre><code class="language-js">const util = require('util'); util.log('Timestamped message.'); </code></pre> <h3>util.print([...strings])<span><a class="mark" href="#util_util_print_strings" id="util_util_print_strings">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span><span>Deprecated since: v0.11.3</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#console_console_log_data_args"><code>console.log()</code></a> instead.</div><p></p> <p>Deprecated predecessor of <code>console.log</code>.</p> <h3>util.puts([...strings])<span><a class="mark" href="#util_util_puts_strings" id="util_util_puts_strings">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.0</span><span>Deprecated since: v0.11.3</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#console_console_log_data_args"><code>console.log()</code></a> instead.</div><p></p> <p>Deprecated predecessor of <code>console.log</code>.</p> <h1>V8<span><a class="mark" href="#v8_v8" id="v8_v8">#</a></span></h1> <p>The <code>v8</code> module exposes APIs that are specific to the version of <a href="https://developers.google.com/v8/">V8</a> built into the Node.js binary. It can be accessed using:</p> <pre><code class="language-js">const v8 = require('v8'); </code></pre> <p>The APIs and implementation are subject to change at any time.</p> <h2>v8.cachedDataVersionTag()<span><a class="mark" href="#v8_v8_cacheddataversiontag" id="v8_v8_cacheddataversiontag">#</a></span></h2> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Returns an integer representing a "version tag" derived from the V8 version, command line flags and detected CPU features. This is useful for determining whether a <a href="#vm_new_vm_script_code_options"><code>vm.Script</code></a> <code>cachedData</code> buffer is compatible with this instance of V8.</p> <h2>v8.getHeapSpaceStatistics()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/v8.js#L92">[src]</a><span><a class="mark" href="#v8_v8_getheapspacestatistics" id="v8_v8_getheapspacestatistics">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.5.0</td> <td><p>Support values exceeding the 32-bit unsigned integer range.</p></td></tr> <tr><td>v6.0.0</td> <td><p><span>Added in: v6.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> <p>Returns statistics about the V8 heap spaces, i.e. the segments which make up the V8 heap. Neither the ordering of heap spaces, nor the availability of a heap space can be guaranteed as the statistics are provided via the V8 <a href="https://v8docs.nodesource.com/node-10.6/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4"><code>GetHeapSpaceStatistics</code></a> function and may change from one V8 version to the next.</p> <p>The value returned is an array of objects containing the following properties:</p> <ul> <li><code>space_name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>space_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>space_used_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>space_available_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>physical_space_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <pre><code class="language-json">[ { "space_name": "new_space", "space_size": 2063872, "space_used_size": 951112, "space_available_size": 80824, "physical_space_size": 2063872 }, { "space_name": "old_space", "space_size": 3090560, "space_used_size": 2493792, "space_available_size": 0, "physical_space_size": 3090560 }, { "space_name": "code_space", "space_size": 1260160, "space_used_size": 644256, "space_available_size": 960, "physical_space_size": 1260160 }, { "space_name": "map_space", "space_size": 1094160, "space_used_size": 201608, "space_available_size": 0, "physical_space_size": 1094160 }, { "space_name": "large_object_space", "space_size": 0, "space_used_size": 0, "space_available_size": 1490980608, "physical_space_size": 0 } ] </code></pre> <h2>v8.getHeapStatistics()<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/v8.js#L74">[src]</a><span><a class="mark" href="#v8_v8_getheapstatistics" id="v8_v8_getheapstatistics">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v7.5.0</td> <td><p>Support values exceeding the 32-bit unsigned integer range.</p></td></tr> <tr><td>v7.2.0</td> <td><p>Added <code>malloced_memory</code>, <code>peak_malloced_memory</code>, and <code>does_zap_garbage</code>.</p></td></tr> <tr><td>v1.0.0</td> <td><p><span>Added in: v1.0.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Returns an object with the following properties:</p> <ul> <li><code>total_heap_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>total_heap_size_executable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>total_physical_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>total_available_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>used_heap_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>heap_size_limit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>malloced_memory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>peak_malloced_memory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> <li><code>does_zap_garbage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p><code>does_zap_garbage</code> is a 0/1 boolean, which signifies whether the <code>--zap_code_space</code> option is enabled or not. This makes V8 overwrite heap garbage with a bit pattern. The RSS footprint (resident memory set) gets bigger because it continuously touches all heap pages and that makes them less likely to get swapped out by the operating system.</p> <!-- eslint-skip --> <pre><code class="language-js">{ total_heap_size: 7326976, total_heap_size_executable: 4194304, total_physical_size: 7326976, total_available_size: 1152656, used_heap_size: 3476208, heap_size_limit: 1535115264, malloced_memory: 16384, peak_malloced_memory: 1127496, does_zap_garbage: 0 } </code></pre> <h2>v8.setFlagsFromString(flags)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/v8.js#L68">[src]</a><span><a class="mark" href="#v8_v8_setflagsfromstring_flags" id="v8_v8_setflagsfromstring_flags">#</a></span></h2> <div class="api_metadata"> <span>Added in: v1.0.0</span> </div> <ul> <li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The <code>v8.setFlagsFromString()</code> method can be used to programmatically set V8 command line flags. This method should be used with care. Changing settings after the VM has started may result in unpredictable behavior, including crashes and data loss; or it may simply do nothing.</p> <p>The V8 options available for a version of Node.js may be determined by running <code>node --v8-options</code>. An unofficial, community-maintained list of options and their effects is available <a href="https://github.com/thlorenz/v8-flags/blob/master/flags-0.11.md">here</a>.</p> <p>Usage:</p> <pre><code class="language-js">// Print GC events to stdout for one minute. const v8 = require('v8'); v8.setFlagsFromString('--trace_gc'); setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); </code></pre> <h2>Serialization API<span><a class="mark" href="#v8_serialization_api" id="v8_serialization_api">#</a></span></h2> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>The serialization API provides means of serializing JavaScript values in a way that is compatible with the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>. The format is backward-compatible (i.e. safe to store to disk).</p> <p>This API is under development, and changes (including incompatible changes to the API or wire format) may occur until this warning is removed.</p> <h3>v8.serialize(value)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/v8.js#L199">[src]</a><span><a class="mark" href="#v8_v8_serialize_value" id="v8_v8_serialize_value">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Uses a <a href="#v8_class_v8_defaultserializer"><code>DefaultSerializer</code></a> to serialize <code>value</code> into a buffer.</p> <h3>v8.deserialize(buffer)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/v8.js#L206">[src]</a><span><a class="mark" href="#v8_v8_deserialize_buffer" id="v8_v8_deserialize_buffer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> A buffer returned by <a href="#v8_v8_serialize_value"><code>serialize()</code></a>.</li> </ul> <p>Uses a <a href="#v8_class_v8_defaultdeserializer"><code>DefaultDeserializer</code></a> with default options to read a JS value from a buffer.</p> <h3>class: v8.Serializer<span><a class="mark" href="#v8_class_v8_serializer" id="v8_class_v8_serializer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <h4>new Serializer()<span><a class="mark" href="#v8_new_serializer" id="v8_new_serializer">#</a></span></h4> <p>Creates a new <code>Serializer</code> object.</p> <h4>serializer.writeHeader()<span><a class="mark" href="#v8_serializer_writeheader" id="v8_serializer_writeheader">#</a></span></h4> <p>Writes out a header, which includes the serialization format version.</p> <h4>serializer.writeValue(value)<span><a class="mark" href="#v8_serializer_writevalue_value" id="v8_serializer_writevalue_value">#</a></span></h4> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>Serializes a JavaScript value and adds the serialized representation to the internal buffer.</p> <p>This throws an error if <code>value</code> cannot be serialized.</p> <h4>serializer.releaseBuffer()<span><a class="mark" href="#v8_serializer_releasebuffer" id="v8_serializer_releasebuffer">#</a></span></h4> <ul> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Returns the stored internal buffer. This serializer should not be used once the buffer is released. Calling this method results in undefined behavior if a previous write has failed.</p> <h4>serializer.transferArrayBuffer(id, arrayBuffer)<span><a class="mark" href="#v8_serializer_transferarraybuffer_id_arraybuffer" id="v8_serializer_transferarraybuffer_id_arraybuffer">#</a></span></h4> <ul> <li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> A 32-bit unsigned integer.</li> <li><code>arrayBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> An <code>ArrayBuffer</code> instance.</li> </ul> <p>Marks an <code>ArrayBuffer</code> as havings its contents transferred out of band. Pass the corresponding <code>ArrayBuffer</code> in the deserializing context to <a href="#v8_deserializer_transferarraybuffer_id_arraybuffer"><code>deserializer.transferArrayBuffer()</code></a>.</p> <h4>serializer.writeUint32(value)<span><a class="mark" href="#v8_serializer_writeuint32_value" id="v8_serializer_writeuint32_value">#</a></span></h4> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Write a raw 32-bit unsigned integer. For use inside of a custom <a href="#v8_serializer_writehostobject_object"><code>serializer._writeHostObject()</code></a>.</p> <h4>serializer.writeUint64(hi, lo)<span><a class="mark" href="#v8_serializer_writeuint64_hi_lo" id="v8_serializer_writeuint64_hi_lo">#</a></span></h4> <ul> <li><code>hi</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>lo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. For use inside of a custom <a href="#v8_serializer_writehostobject_object"><code>serializer._writeHostObject()</code></a>.</p> <h4>serializer.writeDouble(value)<span><a class="mark" href="#v8_serializer_writedouble_value" id="v8_serializer_writedouble_value">#</a></span></h4> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Write a JS <code>number</code> value. For use inside of a custom <a href="#v8_serializer_writehostobject_object"><code>serializer._writeHostObject()</code></a>.</p> <h4>serializer.writeRawBytes(buffer)<span><a class="mark" href="#v8_serializer_writerawbytes_buffer" id="v8_serializer_writerawbytes_buffer">#</a></span></h4> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a></li> </ul> <p>Write raw bytes into the serializer’s internal buffer. The deserializer will require a way to compute the length of the buffer. For use inside of a custom <a href="#v8_serializer_writehostobject_object"><code>serializer._writeHostObject()</code></a>.</p> <h4>serializer._writeHostObject(object)<span><a class="mark" href="#v8_serializer_writehostobject_object" id="v8_serializer_writehostobject_object">#</a></span></h4> <ul> <li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>This method is called to write some kind of host object, i.e. an object created by native C++ bindings. If it is not possible to serialize <code>object</code>, a suitable exception should be thrown.</p> <p>This method is not present on the <code>Serializer</code> class itself but can be provided by subclasses.</p> <h4>serializer._getDataCloneError(message)<span><a class="mark" href="#v8_serializer_getdatacloneerror_message" id="v8_serializer_getdatacloneerror_message">#</a></span></h4> <ul> <li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>This method is called to generate error objects that will be thrown when an object can not be cloned.</p> <p>This method defaults to the <a href="#errors_class_error"><code>Error</code></a> constructor and can be overridden on subclasses.</p> <h4>serializer._getSharedArrayBufferId(sharedArrayBuffer)<span><a class="mark" href="#v8_serializer_getsharedarraybufferid_sharedarraybuffer" id="v8_serializer_getsharedarraybufferid_sharedarraybuffer">#</a></span></h4> <ul> <li><code>sharedArrayBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a></li> </ul> <p>This method is called when the serializer is going to serialize a <code>SharedArrayBuffer</code> object. It must return an unsigned 32-bit integer ID for the object, using the same ID if this <code>SharedArrayBuffer</code> has already been serialized. When deserializing, this ID will be passed to <a href="#v8_deserializer_transferarraybuffer_id_arraybuffer"><code>deserializer.transferArrayBuffer()</code></a>.</p> <p>If the object cannot be serialized, an exception should be thrown.</p> <p>This method is not present on the <code>Serializer</code> class itself but can be provided by subclasses.</p> <h4>serializer._setTreatArrayBufferViewsAsHostObjects(flag)<span><a class="mark" href="#v8_serializer_settreatarraybufferviewsashostobjects_flag" id="v8_serializer_settreatarraybufferviewsashostobjects_flag">#</a></span></h4> <ul> <li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> <strong>Default:</strong> <code>false</code></li> </ul> <p>Indicate whether to treat <code>TypedArray</code> and <code>DataView</code> objects as host objects, i.e. pass them to <a href="#v8_serializer_writehostobject_object"><code>serializer._writeHostObject()</code></a>.</p> <h3>class: v8.Deserializer<span><a class="mark" href="#v8_class_v8_deserializer" id="v8_class_v8_deserializer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <h4>new Deserializer(buffer)<span><a class="mark" href="#v8_new_deserializer_buffer" id="v8_new_deserializer_buffer">#</a></span></h4> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> A buffer returned by <a href="#v8_serializer_releasebuffer"><code>serializer.releaseBuffer()</code></a>.</li> </ul> <p>Creates a new <code>Deserializer</code> object.</p> <h4>deserializer.readHeader()<span><a class="mark" href="#v8_deserializer_readheader" id="v8_deserializer_readheader">#</a></span></h4> <p>Reads and validates a header (including the format version). May, for example, reject an invalid or unsupported wire format. In that case, an <code>Error</code> is thrown.</p> <h4>deserializer.readValue()<span><a class="mark" href="#v8_deserializer_readvalue" id="v8_deserializer_readvalue">#</a></span></h4> <p>Deserializes a JavaScript value from the buffer and returns it.</p> <h4>deserializer.transferArrayBuffer(id, arrayBuffer)<span><a class="mark" href="#v8_deserializer_transferarraybuffer_id_arraybuffer" id="v8_deserializer_transferarraybuffer_id_arraybuffer">#</a></span></h4> <ul> <li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> A 32-bit unsigned integer.</li> <li><code>arrayBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type"><SharedArrayBuffer></a> An <code>ArrayBuffer</code> instance.</li> </ul> <p>Marks an <code>ArrayBuffer</code> as havings its contents transferred out of band. Pass the corresponding <code>ArrayBuffer</code> in the serializing context to <a href="#v8_serializer_transferarraybuffer_id_arraybuffer"><code>serializer.transferArrayBuffer()</code></a> (or return the <code>id</code> from <a href="#v8_serializer_getsharedarraybufferid_sharedarraybuffer"><code>serializer._getSharedArrayBufferId()</code></a> in the case of <code>SharedArrayBuffer</code>s).</p> <h4>deserializer.getWireFormatVersion()<span><a class="mark" href="#v8_deserializer_getwireformatversion" id="v8_deserializer_getwireformatversion">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Reads the underlying wire format version. Likely mostly to be useful to legacy code reading old wire format versions. May not be called before <code>.readHeader()</code>.</p> <h4>deserializer.readUint32()<span><a class="mark" href="#v8_deserializer_readuint32" id="v8_deserializer_readuint32">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>Read a raw 32-bit unsigned integer and return it. For use inside of a custom <a href="#v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p> <h4>deserializer.readUint64()<span><a class="mark" href="#v8_deserializer_readuint64" id="v8_deserializer_readuint64">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer[]></a></li> </ul> <p>Read a raw 64-bit unsigned integer and return it as an array <code>[hi, lo]</code> with two 32-bit unsigned integer entries. For use inside of a custom <a href="#v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p> <h4>deserializer.readDouble()<span><a class="mark" href="#v8_deserializer_readdouble" id="v8_deserializer_readdouble">#</a></span></h4> <ul> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Read a JS <code>number</code> value. For use inside of a custom <a href="#v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p> <h4>deserializer.readRawBytes(length)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/v8.js#L116">[src]</a><span><a class="mark" href="#v8_deserializer_readrawbytes_length" id="v8_deserializer_readrawbytes_length">#</a></span></h4> <ul> <li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Read raw bytes from the deserializer’s internal buffer. The <code>length</code> parameter must correspond to the length of the buffer that was passed to <a href="#v8_serializer_writerawbytes_buffer"><code>serializer.writeRawBytes()</code></a>. For use inside of a custom <a href="#v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p> <h4>deserializer._readHostObject()<span><a class="mark" href="#v8_deserializer_readhostobject" id="v8_deserializer_readhostobject">#</a></span></h4> <p>This method is called to read some kind of host object, i.e. an object that is created by native C++ bindings. If it is not possible to deserialize the data, a suitable exception should be thrown.</p> <p>This method is not present on the <code>Deserializer</code> class itself but can be provided by subclasses.</p> <h3>class: v8.DefaultSerializer<span><a class="mark" href="#v8_class_v8_defaultserializer" id="v8_class_v8_defaultserializer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <p>A subclass of <a href="#v8_class_v8_serializer"><code>Serializer</code></a> that serializes <code>TypedArray</code> (in particular <a href="buffer.html"><code>Buffer</code></a>) and <code>DataView</code> objects as host objects, and only stores the part of their underlying <code>ArrayBuffer</code>s that they are referring to.</p> <h3>class: v8.DefaultDeserializer<span><a class="mark" href="#v8_class_v8_defaultdeserializer" id="v8_class_v8_defaultdeserializer">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.0.0</span> </div> <p>A subclass of <a href="#v8_class_v8_deserializer"><code>Deserializer</code></a> corresponding to the format written by <a href="#v8_class_v8_defaultserializer"><code>DefaultSerializer</code></a>.</p> <h1>VM (Executing JavaScript)<span><a class="mark" href="#vm_vm_executing_javascript" id="vm_vm_executing_javascript">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>vm</code> module provides APIs for compiling and running code within V8 Virtual Machine contexts. <strong>The <code>vm</code> module is not a security mechanism. Do not use it to run untrusted code</strong>. The term "sandbox" is used throughout these docs simply to refer to a separate context, and does not confer any security guarantees.</p> <p>JavaScript code can be compiled and run immediately or compiled, saved, and run later.</p> <p>A common use case is to run the code in a sandboxed environment. The sandboxed code uses a different V8 Context, meaning that it has a different global object than the rest of the code.</p> <p>One can provide the context by <a href="#vm_what_does_it_mean_to_contextify_an_object">"contextifying"</a> a sandbox object. The sandboxed code treats any property in the sandbox like a global variable. Any changes to global variables caused by the sandboxed code are reflected in the sandbox object.</p> <pre><code class="language-js">const vm = require('vm'); const x = 1; const sandbox = { x: 2 }; vm.createContext(sandbox); // Contextify the sandbox. const code = 'x += 40; var y = 17;'; // x and y are global variables in the sandboxed environment. // Initially, x has the value 2 because that is the value of sandbox.x. vm.runInContext(code, sandbox); console.log(sandbox.x); // 42 console.log(sandbox.y); // 17 console.log(x); // 1; y is not defined. </code></pre> <h2>Class: vm.SourceTextModule<span><a class="mark" href="#vm_class_vm_sourcetextmodule" id="vm_class_vm_sourcetextmodule">#</a></span></h2> <div class="api_metadata"> <span>Added in: v9.6.0</span> </div> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p><em>This feature is only available with the <code>--experimental-vm-modules</code> command flag enabled.</em></p> <p>The <code>vm.SourceTextModule</code> class provides a low-level interface for using ECMAScript modules in VM contexts. It is the counterpart of the <code>vm.Script</code> class that closely mirrors <a href="https://tc39.github.io/ecma262/#sec-source-text-module-records">Source Text Module Record</a>s as defined in the ECMAScript specification.</p> <p>Unlike <code>vm.Script</code> however, every <code>vm.SourceTextModule</code> object is bound to a context from its creation. Operations on <code>vm.SourceTextModule</code> objects are intrinsically asynchronous, in contrast with the synchronous nature of <code>vm.Script</code> objects. With the help of async functions, however, manipulating <code>vm.SourceTextModule</code> objects is fairly straightforward.</p> <p>Using a <code>vm.SourceTextModule</code> object requires four distinct steps: creation/parsing, linking, instantiation, and evaluation. These four steps are illustrated in the following example.</p> <p>This implementation lies at a lower level than the <a href="#esm_ecmascript_modules">ECMAScript Module loader</a>. There is also currently no way to interact with the Loader, though support is planned.</p> <pre><code class="language-js">const vm = require('vm'); const contextifiedSandbox = vm.createContext({ secret: 42 }); (async () => { // Step 1 // // Create a Module by constructing a new `vm.SourceTextModule` object. This // parses the provided source text, throwing a `SyntaxError` if anything goes // wrong. By default, a Module is created in the top context. But here, we // specify `contextifiedSandbox` as the context this Module belongs to. // // Here, we attempt to obtain the default export from the module "foo", and // put it into local binding "secret". const bar = new vm.SourceTextModule(` import s from 'foo'; s; `, { context: contextifiedSandbox }); // Step 2 // // "Link" the imported dependencies of this Module to it. // // The provided linking callback (the "linker") accepts two arguments: the // parent module (`bar` in this case) and the string that is the specifier of // the imported module. The callback is expected to return a Module that // corresponds to the provided specifier, with certain requirements documented // in `module.link()`. // // If linking has not started for the returned Module, the same linker // callback will be called on the returned Module. // // Even top-level Modules without dependencies must be explicitly linked. The // callback provided would never be called, however. // // The link() method returns a Promise that will be resolved when all the // Promises returned by the linker resolve. // // Note: This is a contrived example in that the linker function creates a new // "foo" module every time it is called. In a full-fledged module system, a // cache would probably be used to avoid duplicated modules. async function linker(specifier, referencingModule) { if (specifier === 'foo') { return new vm.SourceTextModule(` // The "secret" variable refers to the global variable we added to // "contextifiedSandbox" when creating the context. export default secret; `, { context: referencingModule.context }); // Using `contextifiedSandbox` instead of `referencingModule.context` // here would work as well. } throw new Error(`Unable to resolve dependency: ${specifier}`); } await bar.link(linker); // Step 3 // // Instantiate the top-level Module. // // Only the top-level Module needs to be explicitly instantiated; its // dependencies will be recursively instantiated by instantiate(). bar.instantiate(); // Step 4 // // Evaluate the Module. The evaluate() method returns a Promise with a single // property "result" that contains the result of the very last statement // executed in the Module. In the case of `bar`, it is `s;`, which refers to // the default export of the `foo` module, the `secret` we set in the // beginning to 42. const { result } = await bar.evaluate(); console.log(result); // Prints 42. })(); </code></pre> <h3>Constructor: new vm.SourceTextModule(code[, options])<span><a class="mark" href="#vm_constructor_new_vm_sourcetextmodule_code_options" id="vm_constructor_new_vm_sourcetextmodule_code_options">#</a></span></h3> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> JavaScript Module code to parse</li> <li> <p><code>options</code></p> <ul> <li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> URL used in module resolution and stack traces. <strong>Default:</strong> <code>'vm:module(i)'</code> where <code>i</code> is a context-specific ascending index.</li> <li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object as returned by the <code>vm.createContext()</code> method, to compile and evaluate this <code>Module</code> in.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the line number offset that is displayed in stack traces produced by this <code>Module</code>.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the column number offset that is displayed in stack traces produced by this <code>Module</code>.</li> <li><code>initializeImportMeta</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called during evaluation of this <code>Module</code> to initialize the <code>import.meta</code>. This function has the signature <code>(meta, module)</code>, where <code>meta</code> is the <code>import.meta</code> object in the <code>Module</code>, and <code>module</code> is this <code>vm.SourceTextModule</code> object.</li> <li><code>importModuleDynamically</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called during evaluation of this module when <code>import()</code> is called. This function has the signature <code>(specifier, module)</code> where <code>specifier</code> is the specifier passed to <code>import()</code> and <code>module</code> is this <code>vm.SourceTextModule</code>. If this option is not specified, calls to <code>import()</code> will reject with <a href="#ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>. This method can return a <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects">Module Namespace Object</a>, but returning a <code>vm.SourceTextModule</code> is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain <code>then</code> function exports.</li> </ul> </li> </ul> <p>Creates a new ES <code>Module</code> object.</p> <p>Properties assigned to the <code>import.meta</code> object that are objects may allow the <code>Module</code> to access information outside the specified <code>context</code>, if the object is created in the top level context. Use <code>vm.runInContext()</code> to create objects in a specific context.</p> <pre><code class="language-js">const vm = require('vm'); const contextifiedSandbox = vm.createContext({ secret: 42 }); (async () => { const module = new vm.SourceTextModule( 'Object.getPrototypeOf(import.meta.prop).secret = secret;', { initializeImportMeta(meta) { // Note: this object is created in the top context. As such, // Object.getPrototypeOf(import.meta.prop) points to the // Object.prototype in the top context rather than that in // the sandbox. meta.prop = {}; } }); // Since module has no dependencies, the linker function will never be called. await module.link(() => {}); module.instantiate(); await module.evaluate(); // Now, Object.prototype.secret will be equal to 42. // // To fix this problem, replace // meta.prop = {}; // above with // meta.prop = vm.runInContext('{}', contextifiedSandbox); })(); </code></pre> <h3>module.dependencySpecifiers<span><a class="mark" href="#vm_module_dependencyspecifiers" id="vm_module_dependencyspecifiers">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li> </ul> <p>The specifiers of all dependencies of this module. The returned array is frozen to disallow any changes to it.</p> <p>Corresponds to the <code>[[RequestedModules]]</code> field of <a href="https://tc39.github.io/ecma262/#sec-source-text-module-records">Source Text Module Record</a>s in the ECMAScript specification.</p> <h3>module.error<span><a class="mark" href="#vm_module_error" id="vm_module_error">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> </ul> <p>If the <code>module.status</code> is <code>'errored'</code>, this property contains the exception thrown by the module during evaluation. If the status is anything else, accessing this property will result in a thrown exception.</p> <p>The value <code>undefined</code> cannot be used for cases where there is not a thrown exception due to possible ambiguity with <code>throw undefined;</code>.</p> <p>Corresponds to the <code>[[EvaluationError]]</code> field of <a href="https://tc39.github.io/ecma262/#sec-source-text-module-records">Source Text Module Record</a>s in the ECMAScript specification.</p> <h3>module.evaluate([options])<span><a class="mark" href="#vm_module_evaluate_options" id="vm_module_evaluate_options">#</a></span></h3> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to evaluate before terminating execution. If execution is interrupted, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> <li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, the execution will be terminated when <code>SIGINT</code> (Ctrl+C) is received. Existing handlers for the event that have been attached via <code>process.on('SIGINT')</code> will be disabled during script execution, but will continue to work after that. If execution is interrupted, an <a href="#errors_class_error"><code>Error</code></a> will be thrown.</li> </ul> </li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Evaluate the module.</p> <p>This must be called after the module has been instantiated; otherwise it will throw an error. It could be called also when the module has already been evaluated, in which case it will do one of the following two things:</p> <ul> <li>return <code>undefined</code> if the initial evaluation ended in success (<code>module.status</code> is <code>'evaluated'</code>)</li> <li>rethrow the same exception the initial evaluation threw if the initial evaluation ended in an error (<code>module.status</code> is <code>'errored'</code>)</li> </ul> <p>This method cannot be called while the module is being evaluated (<code>module.status</code> is <code>'evaluating'</code>) to prevent infinite recursion.</p> <p>Corresponds to the <a href="https://tc39.github.io/ecma262/#sec-moduleevaluation">Evaluate() concrete method</a> field of <a href="https://tc39.github.io/ecma262/#sec-source-text-module-records">Source Text Module Record</a>s in the ECMAScript specification.</p> <h3>module.instantiate()<span><a class="mark" href="#vm_module_instantiate" id="vm_module_instantiate">#</a></span></h3> <p>Instantiate the module. This must be called after linking has completed (<code>linkingStatus</code> is <code>'linked'</code>); otherwise it will throw an error. It may also throw an exception if one of the dependencies does not provide an export the parent module requires.</p> <p>However, if this function succeeded, further calls to this function after the initial instantiation will be no-ops, to be consistent with the ECMAScript specification.</p> <p>Unlike other methods operating on <code>Module</code>, this function completes synchronously and returns nothing.</p> <p>Corresponds to the <a href="https://tc39.github.io/ecma262/#sec-moduledeclarationinstantiation">Instantiate() concrete method</a> field of <a href="https://tc39.github.io/ecma262/#sec-source-text-module-records">Source Text Module Record</a>s in the ECMAScript specification.</p> <h3>module.link(linker)<span><a class="mark" href="#vm_module_link_linker" id="vm_module_link_linker">#</a></span></h3> <ul> <li><code>linker</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type"><Promise></a></li> </ul> <p>Link module dependencies. This method must be called before instantiation, and can only be called once per module.</p> <p>Two parameters will be passed to the <code>linker</code> function:</p> <ul> <li> <p><code>specifier</code> The specifier of the requested module:</p> <!-- eslint-skip --> <pre><code class="language-js">import foo from 'foo'; // ^^^^^ the module specifier </code></pre> </li> <li><code>referencingModule</code> The <code>Module</code> object <code>link()</code> is called on.</li> </ul> <p>The function is expected to return a <code>Module</code> object or a <code>Promise</code> that eventually resolves to a <code>Module</code> object. The returned <code>Module</code> must satisfy the following two invariants:</p> <ul> <li>It must belong to the same context as the parent <code>Module</code>.</li> <li>Its <code>linkingStatus</code> must not be <code>'errored'</code>.</li> </ul> <p>If the returned <code>Module</code>'s <code>linkingStatus</code> is <code>'unlinked'</code>, this method will be recursively called on the returned <code>Module</code> with the same provided <code>linker</code> function.</p> <p><code>link()</code> returns a <code>Promise</code> that will either get resolved when all linking instances resolve to a valid <code>Module</code>, or rejected if the linker function either throws an exception or returns an invalid <code>Module</code>.</p> <p>The linker function roughly corresponds to the implementation-defined <a href="https://tc39.github.io/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> abstract operation in the ECMAScript specification, with a few key differences:</p> <ul> <li>The linker function is allowed to be asynchronous while <a href="https://tc39.github.io/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> is synchronous.</li> <li>The linker function is executed during linking, a Node.js-specific stage before instantiation, while <a href="https://tc39.github.io/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> is called during instantiation.</li> </ul> <p>The actual <a href="https://tc39.github.io/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation used during module instantiation is one that returns the modules linked during linking. Since at that point all modules would have been fully linked already, the <a href="https://tc39.github.io/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation is fully synchronous per specification.</p> <h3>module.linkingStatus<span><a class="mark" href="#vm_module_linkingstatus" id="vm_module_linkingstatus">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The current linking status of <code>module</code>. It will be one of the following values:</p> <ul> <li><code>'unlinked'</code>: <code>module.link()</code> has not yet been called.</li> <li><code>'linking'</code>: <code>module.link()</code> has been called, but not all Promises returned by the linker function have been resolved yet.</li> <li><code>'linked'</code>: <code>module.link()</code> has been called, and all its dependencies have been successfully linked.</li> <li><code>'errored'</code>: <code>module.link()</code> has been called, but at least one of its dependencies failed to link, either because the callback returned a <code>Promise</code> that is rejected, or because the <code>Module</code> the callback returned is invalid.</li> </ul> <h3>module.namespace<span><a class="mark" href="#vm_module_namespace" id="vm_module_namespace">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>The namespace object of the module. This is only available after instantiation (<code>module.instantiate()</code>) has completed.</p> <p>Corresponds to the <a href="https://tc39.github.io/ecma262/#sec-getmodulenamespace">GetModuleNamespace</a> abstract operation in the ECMAScript specification.</p> <h3>module.status<span><a class="mark" href="#vm_module_status" id="vm_module_status">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The current status of the module. Will be one of:</p> <ul> <li> <p><code>'uninstantiated'</code>: The module is not instantiated. It may because of any of the following reasons:</p> <ul> <li>The module was just created.</li> <li><code>module.instantiate()</code> has been called on this module, but it failed for some reason.</li> </ul> <p>This status does not convey any information regarding if <code>module.link()</code> has been called. See <code>module.linkingStatus</code> for that.</p> </li> <li> <p><code>'instantiating'</code>: The module is currently being instantiated through a <code>module.instantiate()</code> call on itself or a parent module.</p> </li> <li> <p><code>'instantiated'</code>: The module has been instantiated successfully, but <code>module.evaluate()</code> has not yet been called.</p> </li> <li> <p><code>'evaluating'</code>: The module is being evaluated through a <code>module.evaluate()</code> on itself or a parent module.</p> </li> <li> <p><code>'evaluated'</code>: The module has been successfully evaluated.</p> </li> <li> <p><code>'errored'</code>: The module has been evaluated, but an exception was thrown.</p> </li> </ul> <p>Other than <code>'errored'</code>, this status string corresponds to the specification's <a href="https://tc39.github.io/ecma262/#sec-source-text-module-records">Source Text Module Record</a>'s <code>[[Status]]</code> field. <code>'errored'</code> corresponds to <code>'evaluated'</code> in the specification, but with <code>[[EvaluationError]]</code> set to a value that is not <code>undefined</code>.</p> <h3>module.url<span><a class="mark" href="#vm_module_url" id="vm_module_url">#</a></span></h3> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> </ul> <p>The URL of the current module, as set in the constructor.</p> <h2>Class: vm.Script<span><a class="mark" href="#vm_class_vm_script" id="vm_class_vm_script">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div> <p>Instances of the <code>vm.Script</code> class contain precompiled scripts that can be executed in specific sandboxes (or "contexts").</p> <h3>new vm.Script(code, options)<span><a class="mark" href="#vm_new_vm_script_code_options" id="vm_new_vm_script_code_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.6.0</td> <td><p>The <code>produceCachedData</code> is deprecated in favour of <code>script.createCachedData()</code></p></td></tr> <tr><td>v5.7.0</td> <td><p>The <code>cachedData</code> and <code>produceCachedData</code> options are supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile.</li> <li> <p><code>options</code></p> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>cachedData</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> Provides an optional <code>Buffer</code> or <code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied source. When supplied, the <code>cachedDataRejected</code> value will be set to either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li> <li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code> and no <code>cachedData</code> is present, V8 will attempt to produce code cache data for <code>code</code>. Upon success, a <code>Buffer</code> with V8's code cache data will be produced and stored in the <code>cachedData</code> property of the returned <code>vm.Script</code> instance. The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code> depending on whether code cache data is produced successfully. This option is deprecated in favor of <code>script.createCachedData()</code>.</li> <li><code>importModuleDynamically</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Called during evaluation of this module when <code>import()</code> is called. This function has the signature <code>(specifier, module)</code> where <code>specifier</code> is the specifier passed to <code>import()</code> and <code>module</code> is this <code>vm.SourceTextModule</code>. If this option is not specified, calls to <code>import()</code> will reject with <a href="#ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>. This method can return a <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects">Module Namespace Object</a>, but returning a <code>vm.SourceTextModule</code> is recommended in order to take advantage of error tracking, and to avoid issues with namespaces that contain <code>then</code> function exports.</li> </ul> </li> </ul> <p>Creating a new <code>vm.Script</code> object compiles <code>code</code> but does not run it. The compiled <code>vm.Script</code> can be run later multiple times. The <code>code</code> is not bound to any global object; rather, it is bound before each run, just for that run.</p> <h3>script.createCachedData()<span><a class="mark" href="#vm_script_createcacheddata" id="vm_script_createcacheddata">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.6.0</span> </div> <ul> <li>Returns: <a href="#buffer_class_buffer" class="type"><Buffer></a></li> </ul> <p>Creates a code cache that can be used with the Script constructor's <code>cachedData</code> option. Returns a Buffer. This method may be called at any time and any number of times.</p> <pre><code class="language-js">const script = new vm.Script(` function add(a, b) { return a + b; } const x = add(1, 2); `); const cacheWithoutX = script.createCachedData(); script.runInThisContext(); const cacheWithX = script.createCachedData(); </code></pre> <h3>script.runInContext(contextifiedSandbox[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/vm.js#L126">[src]</a><span><a class="mark" href="#vm_script_runincontext_contextifiedsandbox_options" id="vm_script_runincontext_contextifiedsandbox_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.3.0</td> <td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> A <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object as returned by the <code>vm.createContext()</code> method.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> <li><code>breakOnSigint</code>: if <code>true</code>, the execution will be terminated when <code>SIGINT</code> (Ctrl+C) is received. Existing handlers for the event that have been attached via <code>process.on('SIGINT')</code> will be disabled during script execution, but will continue to work after that. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown.</li> </ul> </li> </ul> <p>Runs the compiled code contained by the <code>vm.Script</code> object within the given <code>contextifiedSandbox</code> and returns the result. Running code does not have access to local scope.</p> <p>The following example compiles code that increments a global variable, sets the value of another global variable, then execute the code multiple times. The globals are contained in the <code>sandbox</code> object.</p> <pre><code class="language-js">const util = require('util'); const vm = require('vm'); const sandbox = { animal: 'cat', count: 2 }; const script = new vm.Script('count += 1; name = "kitty";'); const context = vm.createContext(sandbox); for (let i = 0; i < 10; ++i) { script.runInContext(context); } console.log(util.inspect(sandbox)); // { animal: 'cat', count: 12, name: 'kitty' } </code></pre> <p>Using the <code>timeout</code> or <code>breakOnSigint</code> options will result in new event loops and corresponding threads being started, which have a non-zero performance overhead.</p> <h3>script.runInNewContext([sandbox[, options]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/vm.js#L137">[src]</a><span><a class="mark" href="#vm_script_runinnewcontext_sandbox_options" id="vm_script_runinnewcontext_sandbox_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object that will be <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a>. If <code>undefined</code>, a new object will be created.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> <li><code>contextName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Human-readable name of the newly created context. <strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of the created context.</li> <li><code>contextOrigin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">Origin</a> corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the <a href="#url_url_origin"><code>url.origin</code></a> property of a <a href="#url_class_url"><code>URL</code></a> object. Most notably, this string should omit the trailing slash, as that denotes a path. <strong>Default:</strong> <code>''</code>.</li> <li> <p><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to false any calls to <code>eval</code> or function constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an <code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li> <li><code>wasm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to false any attempt to compile a WebAssembly module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li> </ul> </li> </ul> </li> </ul> <p>First contextifies the given <code>sandbox</code>, runs the compiled code contained by the <code>vm.Script</code> object within the created sandbox, and returns the result. Running code does not have access to local scope.</p> <p>The following example compiles code that sets a global variable, then executes the code multiple times in different contexts. The globals are set on and contained within each individual <code>sandbox</code>.</p> <pre><code class="language-js">const util = require('util'); const vm = require('vm'); const script = new vm.Script('globalVar = "set"'); const sandboxes = [{}, {}, {}]; sandboxes.forEach((sandbox) => { script.runInNewContext(sandbox); }); console.log(util.inspect(sandboxes)); // [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] </code></pre> <h3>script.runInThisContext([options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/vm.js#L117">[src]</a><span><a class="mark" href="#vm_script_runinthiscontext_options" id="vm_script_runinthiscontext_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div> <ul> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> </ul> </li> </ul> <p>Runs the compiled code contained by the <code>vm.Script</code> within the context of the current <code>global</code> object. Running code does not have access to local scope, but <em>does</em> have access to the current <code>global</code> object.</p> <p>The following example compiles code that increments a <code>global</code> variable then executes that code multiple times:</p> <pre><code class="language-js">const vm = require('vm'); global.globalVar = 0; const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); for (let i = 0; i < 1000; ++i) { script.runInThisContext(); } console.log(globalVar); // 1000 </code></pre> <h2>vm.compileFunction(code[, params[, options]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/vm.js#L332">[src]</a><span><a class="mark" href="#vm_vm_compilefunction_code_params_options" id="vm_vm_compilefunction_code_params_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.10.0</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The body of the function to compile.</li> <li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> An array of strings containing all parameters for the function.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script. <strong>Default:</strong> <code>''</code>.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li> <li><code>cachedData</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> Provides an optional <code>Buffer</code> or <code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied source.</li> <li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Specifies whether to produce new cache data. <strong>Default:</strong> <code>false</code>.</li> <li><code>parsingContext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> sandbox in which the said function should be compiled in.</li> <li><code>contextExtensions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a> An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling. <strong>Default:</strong> <code>[]</code>.</li> </ul> </li> </ul> <p>Compiles the given code into the provided context/sandbox (if no context is supplied, the current context is used), and returns it wrapped inside a function with the given <code>params</code>.</p> <h2>vm.createContext([sandbox[, options]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/vm.js#L243">[src]</a><span><a class="mark" href="#vm_vm_createcontext_sandbox_options" id="vm_vm_createcontext_sandbox_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.0.0</td> <td><p>The <code>sandbox</code> option can no longer be a function.</p></td></tr> <tr><td>v10.0.0</td> <td><p>The <code>codeGeneration</code> option is supported now.</p></td></tr> <tr><td>v0.3.1</td> <td><p><span>Added in: v0.3.1</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Human-readable name of the newly created context. <strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of the created context.</li> <li><code>origin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">Origin</a> corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the <a href="#url_url_origin"><code>url.origin</code></a> property of a <a href="#url_class_url"><code>URL</code></a> object. Most notably, this string should omit the trailing slash, as that denotes a path. <strong>Default:</strong> <code>''</code>.</li> <li> <p><code>codeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to false any calls to <code>eval</code> or function constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an <code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li> <li><code>wasm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If set to false any attempt to compile a WebAssembly module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li> </ul> </li> </ul> </li> </ul> <p>If given a <code>sandbox</code> object, the <code>vm.createContext()</code> method will <a href="#vm_what_does_it_mean_to_contextify_an_object">prepare that sandbox</a> so that it can be used in calls to <a href="#vm_vm_runincontext_code_contextifiedsandbox_options"><code>vm.runInContext()</code></a> or <a href="#vm_script_runincontext_contextifiedsandbox_options"><code>script.runInContext()</code></a>. Inside such scripts, the <code>sandbox</code> object will be the global object, retaining all of its existing properties but also having the built-in objects and functions any standard <a href="https://es5.github.io/#x15.1">global object</a> has. Outside of scripts run by the vm module, global variables will remain unchanged.</p> <pre><code class="language-js">const util = require('util'); const vm = require('vm'); global.globalVar = 3; const sandbox = { globalVar: 1 }; vm.createContext(sandbox); vm.runInContext('globalVar *= 2;', sandbox); console.log(util.inspect(sandbox)); // { globalVar: 2 } console.log(util.inspect(globalVar)); // 3 </code></pre> <p>If <code>sandbox</code> is omitted (or passed explicitly as <code>undefined</code>), a new, empty <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> sandbox object will be returned.</p> <p>The <code>vm.createContext()</code> method is primarily useful for creating a single sandbox that can be used to run multiple scripts. For instance, if emulating a web browser, the method can be used to create a single sandbox representing a window's global object, then run all <code><script></code> tags together within the context of that sandbox.</p> <p>The provided <code>name</code> and <code>origin</code> of the context are made visible through the Inspector API.</p> <h2>vm.isContext(sandbox)<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/vm.js#L235">[src]</a><span><a class="mark" href="#vm_vm_iscontext_sandbox" id="vm_vm_iscontext_sandbox">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.11.7</span> </div> <ul> <li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Returns <code>true</code> if the given <code>sandbox</code> object has been <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> using <a href="#vm_vm_createcontext_sandbox_options"><code>vm.createContext()</code></a>.</p> <h2>vm.runInContext(code, contextifiedSandbox[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/vm.js#L298">[src]</a><span><a class="mark" href="#vm_vm_runincontext_code_contextifiedsandbox_options" id="vm_vm_runincontext_code_contextifiedsandbox_options">#</a></span></h2> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile and run.</li> <li><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> The <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object that will be used as the <code>global</code> when the <code>code</code> is compiled and run.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> </ul> </li> </ul> <p>The <code>vm.runInContext()</code> method compiles <code>code</code>, runs it within the context of the <code>contextifiedSandbox</code>, then returns the result. Running code does not have access to the local scope. The <code>contextifiedSandbox</code> object <em>must</em> have been previously <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> using the <a href="#vm_vm_createcontext_sandbox_options"><code>vm.createContext()</code></a> method.</p> <p>If <code>options</code> is a string, then it specifies the filename.</p> <p>The following example compiles and executes different scripts using a single <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object:</p> <pre><code class="language-js">const util = require('util'); const vm = require('vm'); const sandbox = { globalVar: 1 }; vm.createContext(sandbox); for (let i = 0; i < 10; ++i) { vm.runInContext('globalVar *= 2;', sandbox); } console.log(util.inspect(sandbox)); // { globalVar: 1024 } </code></pre> <h2>vm.runInNewContext(code[, sandbox[, options]])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/vm.js#L314">[src]</a><span><a class="mark" href="#vm_vm_runinnewcontext_code_sandbox_options" id="vm_vm_runinnewcontext_code_sandbox_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile and run.</li> <li><code>sandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> An object that will be <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a>. If <code>undefined</code>, a new object will be created.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> <li><code>contextName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Human-readable name of the newly created context. <strong>Default:</strong> <code>'VM Context i'</code>, where <code>i</code> is an ascending numerical index of the created context.</li> <li><code>contextOrigin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">Origin</a> corresponding to the newly created context for display purposes. The origin should be formatted like a URL, but with only the scheme, host, and port (if necessary), like the value of the <a href="#url_url_origin"><code>url.origin</code></a> property of a <a href="#url_class_url"><code>URL</code></a> object. Most notably, this string should omit the trailing slash, as that denotes a path. <strong>Default:</strong> <code>''</code>.</li> </ul> </li> </ul> <p>The <code>vm.runInNewContext()</code> first contextifies the given <code>sandbox</code> object (or creates a new <code>sandbox</code> if passed as <code>undefined</code>), compiles the <code>code</code>, runs it within the context of the created context, then returns the result. Running code does not have access to the local scope.</p> <p>If <code>options</code> is a string, then it specifies the filename.</p> <p>The following example compiles and executes code that increments a global variable and sets a new one. These globals are contained in the <code>sandbox</code>.</p> <pre><code class="language-js">const util = require('util'); const vm = require('vm'); const sandbox = { animal: 'cat', count: 2 }; vm.runInNewContext('count += 1; name = "kitty"', sandbox); console.log(util.inspect(sandbox)); // { animal: 'cat', count: 3, name: 'kitty' } </code></pre> <h2>vm.runInThisContext(code[, options])<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/vm.js#L325">[src]</a><span><a class="mark" href="#vm_vm_runinthiscontext_code_options" id="vm_vm_runinthiscontext_code_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.3.1</span> </div> <ul> <li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The JavaScript code to compile and run.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></p> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Specifies the filename used in stack traces produced by this script.</li> <li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the line number offset that is displayed in stack traces produced by this script.</li> <li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the column number offset that is displayed in stack traces produced by this script.</li> <li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> error occurs while compiling the <code>code</code>, the line of code causing the error is attached to the stack trace.</li> <li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Specifies the number of milliseconds to execute <code>code</code> before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. This value must be a strictly positive integer.</li> </ul> </li> </ul> <p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it within the context of the current <code>global</code> and returns the result. Running code does not have access to local scope, but does have access to the current <code>global</code> object.</p> <p>If <code>options</code> is a string, then it specifies the filename.</p> <p>The following example illustrates using both <code>vm.runInThisContext()</code> and the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> function to run the same code:</p> <!-- eslint-disable prefer-const --> <pre><code class="language-js">const vm = require('vm'); let localVar = 'initial value'; const vmResult = vm.runInThisContext('localVar = "vm";'); console.log('vmResult:', vmResult); console.log('localVar:', localVar); const evalResult = eval('localVar = "eval";'); console.log('evalResult:', evalResult); console.log('localVar:', localVar); // vmResult: 'vm', localVar: 'initial value' // evalResult: 'eval', localVar: 'eval' </code></pre> <p>Because <code>vm.runInThisContext()</code> does not have access to the local scope, <code>localVar</code> is unchanged. In contrast, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> <em>does</em> have access to the local scope, so the value <code>localVar</code> is changed. In this way <code>vm.runInThisContext()</code> is much like an <a href="https://es5.github.io/#x10.4.2">indirect <code>eval()</code> call</a>, e.g. <code>(0,eval)('code')</code>.</p> <h2>Example: Running an HTTP Server within a VM<span><a class="mark" href="#vm_example_running_an_http_server_within_a_vm" id="vm_example_running_an_http_server_within_a_vm">#</a></span></h2> <p>When using either <a href="#vm_script_runinthiscontext_options"><code>script.runInThisContext()</code></a> or <a href="#vm_vm_runinthiscontext_code_options"><code>vm.runInThisContext()</code></a>, the code is executed within the current V8 global context. The code passed to this VM context will have its own isolated scope.</p> <p>In order to run a simple web server using the <code>http</code> module the code passed to the context must either call <code>require('http')</code> on its own, or have a reference to the <code>http</code> module passed to it. For instance:</p> <pre><code class="language-js">'use strict'; const vm = require('vm'); const code = ` ((require) => { const http = require('http'); http.createServer((request, response) => { response.writeHead(200, { 'Content-Type': 'text/plain' }); response.end('Hello World\\n'); }).listen(8124); console.log('Server running at http://127.0.0.1:8124/'); })`; vm.runInThisContext(code)(require); </code></pre> <p>The <code>require()</code> in the above case shares the state with the context it is passed from. This may introduce risks when untrusted code is executed, e.g. altering objects in the context in unwanted ways.</p> <h2>What does it mean to "contextify" an object?<span><a class="mark" href="#vm_what_does_it_mean_to_contextify_an_object" id="vm_what_does_it_mean_to_contextify_an_object">#</a></span></h2> <p>All JavaScript executed within Node.js runs within the scope of a "context". According to the <a href="https://github.com/v8/v8/wiki/Embedder's%20Guide#contexts">V8 Embedder's Guide</a>:</p> <blockquote> <p>In V8, a context is an execution environment that allows separate, unrelated, JavaScript applications to run in a single instance of V8. You must explicitly specify the context in which you want any JavaScript code to be run.</p> </blockquote> <p>When the method <code>vm.createContext()</code> is called, the <code>sandbox</code> object that is passed in (or a newly created object if <code>sandbox</code> is <code>undefined</code>) is associated internally with a new instance of a V8 Context. This V8 Context provides the <code>code</code> run using the <code>vm</code> module's methods with an isolated global environment within which it can operate. The process of creating the V8 Context and associating it with the <code>sandbox</code> object is what this document refers to as "contextifying" the <code>sandbox</code>.</p> <h2>Timeout limitations when using process.nextTick(), and Promises<span><a class="mark" href="#vm_timeout_limitations_when_using_process_nexttick_and_promises" id="vm_timeout_limitations_when_using_process_nexttick_and_promises">#</a></span></h2> <p>Because of the internal mechanics of how the <code>process.nextTick()</code> queue and the microtask queue that underlies Promises are implemented within V8 and Node.js, it is possible for code running within a context to "escape" the <code>timeout</code> set using <code>vm.runInContext()</code>, <code>vm.runInNewContext()</code>, and <code>vm.runInThisContext()</code>.</p> <p>For example, the following code executed by <code>vm.runInNewContext()</code> with a timeout of 5 milliseconds schedules an infinite loop to run after a promise resolves. The scheduled loop is never interrupted by the timeout:</p> <pre><code class="language-js">const vm = require('vm'); function loop() { while (1) console.log(Date.now()); } vm.runInNewContext( 'Promise.resolve().then(loop);', { loop, console }, { timeout: 5 } ); </code></pre> <p>This issue also occurs when the <code>loop()</code> call is scheduled using the <code>process.nextTick()</code> function.</p> <p>This issue occurs because all contexts share the same microtask and nextTick queues.</p> <h1>Worker Threads<span><a class="mark" href="#worker_threads_worker_threads" id="worker_threads_worker_threads">#</a></span></h1> <p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p> <p>The <code>worker</code> module provides a way to create multiple environments running on independent threads, and to create message channels between them. It can be accessed using the <code>--experimental-worker</code> flag and:</p> <pre><code class="language-js">const worker = require('worker_threads'); </code></pre> <p>Workers are useful for performing CPU-intensive JavaScript operations; do not use them for I/O, since Node.js’s built-in mechanisms for performing operations asynchronously already treat it more efficiently than Worker threads can.</p> <p>Workers, unlike child processes or when using the <code>cluster</code> module, can also share memory efficiently by transferring <code>ArrayBuffer</code> instances or sharing <code>SharedArrayBuffer</code> instances between them.</p> <pre><code class="language-js">const { Worker, isMainThread, parentPort, workerData } = require('worker_threads'); if (isMainThread) { module.exports = async function parseJSAsync(script) { return new Promise((resolve, reject) => { const worker = new Worker(__filename, { workerData: script }); worker.on('message', resolve); worker.on('error', reject); worker.on('exit', (code) => { if (code !== 0) reject(new Error(`Worker stopped with exit code ${code}`)); }); }); }; } else { const { parse } = require('some-js-parsing-library'); const script = workerData; parentPort.postMessage(parse(script)); } </code></pre> <p>Note that this example spawns a Worker thread for each <code>parse</code> call. In practice, it is strongly recommended to use a pool of Workers for these kinds of tasks, since the overhead of creating Workers would likely exceed the benefit of handing the work off to it.</p> <h2>worker.isMainThread<span><a class="mark" href="#worker_threads_worker_ismainthread" id="worker_threads_worker_ismainthread">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li> </ul> <p>Is <code>true</code> if this code is not running inside of a <a href="#worker_threads_class_worker"><code>Worker</code></a> thread.</p> <h2>worker.parentPort<span><a class="mark" href="#worker_threads_worker_parentport" id="worker_threads_worker_parentport">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="#worker_threads_class_messageport" class="type"><MessagePort></a></li> </ul> <p>If this thread was spawned as a <a href="#worker_threads_class_worker"><code>Worker</code></a>, this will be a <a href="#worker_threads_class_messageport"><code>MessagePort</code></a> allowing communication with the parent thread. Messages sent using <code>parentPort.postMessage()</code> will be available in the parent thread using <code>worker.on('message')</code>, and messages sent from the parent thread using <code>worker.postMessage()</code> will be available in this thread using <code>parentPort.on('message')</code>.</p> <h2>worker.threadId<span><a class="mark" href="#worker_threads_worker_threadid" id="worker_threads_worker_threadid">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>An integer identifier for the current thread. On the corresponding worker object (if there is any), it is available as <a href="#worker_threads_worker_threadid_1"><code>worker.threadId</code></a>.</p> <h2>worker.workerData<span><a class="mark" href="#worker_threads_worker_workerdata" id="worker_threads_worker_workerdata">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>An arbitrary JavaScript value that contains a clone of the data passed to this thread’s <code>Worker</code> constructor.</p> <h2>Class: MessageChannel<span><a class="mark" href="#worker_threads_class_messagechannel" id="worker_threads_class_messagechannel">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Instances of the <code>worker.MessageChannel</code> class represent an asynchronous, two-way communications channel. The <code>MessageChannel</code> has no methods of its own. <code>new MessageChannel()</code> yields an object with <code>port1</code> and <code>port2</code> properties, which refer to linked <a href="#worker_threads_class_messageport"><code>MessagePort</code></a> instances.</p> <pre><code class="language-js">const { MessageChannel } = require('worker_threads'); const { port1, port2 } = new MessageChannel(); port1.on('message', (message) => console.log('received', message)); port2.postMessage({ foo: 'bar' }); // prints: received { foo: 'bar' } from the `port1.on('message')` listener </code></pre> <h2>Class: MessagePort<span><a class="mark" href="#worker_threads_class_messageport" id="worker_threads_class_messageport">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li>Extends: <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>Instances of the <code>worker.MessagePort</code> class represent one end of an asynchronous, two-way communications channel. It can be used to transfer structured data, memory regions and other <code>MessagePort</code>s between different <a href="#worker_threads_class_worker"><code>Worker</code></a>s.</p> <p>With the exception of <code>MessagePort</code>s being <a href="events.html"><code>EventEmitter</code></a>s rather than <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget"><code>EventTarget</code></a>s, this implementation matches <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort">browser <code>MessagePort</code></a>s.</p> <h3>Event: 'close'<span><a class="mark" href="#worker_threads_event_close" id="worker_threads_event_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>The <code>'close'</code> event is emitted once either side of the channel has been disconnected.</p> <h3>Event: 'message'<span><a class="mark" href="#worker_threads_event_message" id="worker_threads_event_message">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The transmitted value</li> </ul> <p>The <code>'message'</code> event is emitted for any incoming message, containing the cloned input of <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a>.</p> <p>Listeners on this event will receive a clone of the <code>value</code> parameter as passed to <code>postMessage()</code> and no further arguments.</p> <h3>port.close()<span><a class="mark" href="#worker_threads_port_close" id="worker_threads_port_close">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Disables further sending of messages on either side of the connection. This method can be called when no further communication will happen over this <code>MessagePort</code>.</p> <h3>port.postMessage(value[, transferList])<span><a class="mark" href="#worker_threads_port_postmessage_value_transferlist" id="worker_threads_port_postmessage_value_transferlist">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> <p>Sends a JavaScript value to the receiving side of this channel. <code>value</code> will be transferred in a way which is compatible with the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>. In particular, it may contain circular references and objects like typed arrays that the <code>JSON</code> API is not able to stringify.</p> <p><code>transferList</code> may be a list of <code>ArrayBuffer</code> and <code>MessagePort</code> objects. After transferring, they will not be usable on the sending side of the channel anymore (even if they are not contained in <code>value</code>). Unlike with <a href="child_process.html">child processes</a>, transferring handles such as network sockets is currently not supported.</p> <p>If <code>value</code> contains <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instances, those will be accessible from either thread. They cannot be listed in <code>transferList</code>.</p> <p><code>value</code> may still contain <code>ArrayBuffer</code> instances that are not in <code>transferList</code>; in that case, the underlying memory is copied rather than moved.</p> <p>Because the object cloning uses the structured clone algorithm, non-enumerable properties, property accessors, and object prototypes are not preserved. In particular, <a href="buffer.html"><code>Buffer</code></a> objects will be read as plain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>s on the receiving side.</p> <p>The message object will be cloned immediately, and can be modified after posting without having side effects.</p> <p>For more information on the serialization and deserialization mechanisms behind this API, see the <a href="#v8_serialization_api">serialization API of the <code>v8</code> module</a>.</p> <h3>port.ref()<span><a class="mark" href="#worker_threads_port_ref" id="worker_threads_port_ref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed port will <em>not</em> let the program exit if it's the only active handle left (the default behavior). If the port is <code>ref()</code>ed, calling <code>ref()</code> again will have no effect.</p> <p>If listeners are attached or removed using <code>.on('message')</code>, the port will be <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether listeners for the event exist.</p> <h3>port.start()<span><a class="mark" href="#worker_threads_port_start" id="worker_threads_port_start">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Starts receiving messages on this <code>MessagePort</code>. When using this port as an event emitter, this will be called automatically once <code>'message'</code> listeners are attached.</p> <h3>port.unref()<span><a class="mark" href="#worker_threads_port_unref" id="worker_threads_port_unref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Calling <code>unref()</code> on a port will allow the thread to exit if this is the only active handle in the event system. If the port is already <code>unref()</code>ed calling <code>unref()</code> again will have no effect.</p> <p>If listeners are attached or removed using <code>.on('message')</code>, the port will be <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether listeners for the event exist.</p> <h2>Class: Worker<span><a class="mark" href="#worker_threads_class_worker" id="worker_threads_class_worker">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li>Extends: <a href="#events_class_eventemitter" class="type"><EventEmitter></a></li> </ul> <p>The <code>Worker</code> class represents an independent JavaScript execution thread. Most Node.js APIs are available inside of it.</p> <p>Notable differences inside a Worker environment are:</p> <ul> <li>The <a href="#process_process_stdin"><code>process.stdin</code></a>, <a href="#process_process_stdout"><code>process.stdout</code></a> and <a href="#process_process_stderr"><code>process.stderr</code></a> may be redirected by the parent thread.</li> <li>The <a href="#worker_threads_worker_ismainthread"><code>require('worker_threads').isMainThread</code></a> property is set to <code>false</code>.</li> <li>The <a href="#worker_threads_worker_parentport"><code>require('worker_threads').parentPort</code></a> message port is available.</li> <li><a href="#process_process_exit_code"><code>process.exit()</code></a> does not stop the whole program, just the single thread, and <a href="#process_process_abort"><code>process.abort()</code></a> is not available.</li> <li><a href="#process_process_chdir_directory"><code>process.chdir()</code></a> and <code>process</code> methods that set group or user ids are not available.</li> <li><a href="#process_process_env"><code>process.env</code></a> is a read-only reference to the environment variables.</li> <li><a href="#process_process_title"><code>process.title</code></a> cannot be modified.</li> <li>Signals will not be delivered through <a href="#process_signal_events"><code>process.on('...')</code></a>.</li> <li>Execution may stop at any point as a result of <a href="#worker_threads_worker_terminate_callback"><code>worker.terminate()</code></a> being invoked.</li> <li>IPC channels from parent processes are not accessible.</li> </ul> <p>Currently, the following differences also exist until they are addressed:</p> <ul> <li>The <a href="inspector.html"><code>inspector</code></a> module is not available yet.</li> <li>Native addons are not supported yet.</li> </ul> <p>Creating <code>Worker</code> instances inside of other <code>Worker</code>s is possible.</p> <p>Like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Workers</a> and the <a href="cluster.html"><code>cluster</code> module</a>, two-way communication can be achieved through inter-thread message passing. Internally, a <code>Worker</code> has a built-in pair of <a href="#worker_threads_class_messageport"><code>MessagePort</code></a>s that are already associated with each other when the <code>Worker</code> is created. While the <code>MessagePort</code> object on the parent side is not directly exposed, its functionalities are exposed through <a href="#worker_threads_worker_postmessage_value_transferlist"><code>worker.postMessage()</code></a> and the <a href="#worker_threads_event_message_1"><code>worker.on('message')</code></a> event on the <code>Worker</code> object for the parent thread.</p> <p>To create custom messaging channels (which is encouraged over using the default global channel because it facilitates separation of concerns), users can create a <code>MessageChannel</code> object on either thread and pass one of the <code>MessagePort</code>s on that <code>MessageChannel</code> to the other thread through a pre-existing channel, such as the global one.</p> <p>See <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> for more information on how messages are passed, and what kind of JavaScript values can be successfully transported through the thread barrier.</p> <pre><code class="language-js">const assert = require('assert'); const { Worker, MessageChannel, MessagePort, isMainThread, parentPort } = require('worker_threads'); if (isMainThread) { const worker = new Worker(__filename); const subChannel = new MessageChannel(); worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); subChannel.port2.on('message', (value) => { console.log('received:', value); }); } else { parentPort.once('message', (value) => { assert(value.hereIsYourPort instanceof MessagePort); value.hereIsYourPort.postMessage('the worker is sending this'); value.hereIsYourPort.close(); }); } </code></pre> <h3>new Worker(filename[, options])<span><a class="mark" href="#worker_threads_new_worker_filename_options" id="worker_threads_new_worker_filename_options">#</a></span></h3> <ul> <li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> The path to the Worker’s main script. Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with <code>./</code> or <code>../</code>. If <code>options.eval</code> is <code>true</code>, this is a string containing JavaScript code rather than a path.</li> <li> <p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></p> <ul> <li><code>eval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If <code>true</code>, interpret the first argument to the constructor as a script that is executed once the worker is online.</li> <li><code>workerData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> Any JavaScript value that will be cloned and made available as <a href="#worker_threads_worker_workerdata"><code>require('worker_threads').workerData</code></a>. The cloning will occur as described in the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>, and an error will be thrown if the object cannot be cloned (e.g. because it contains <code>function</code>s).</li> <li>stdin <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stdin</code> will provide a writable stream whose contents will appear as <code>process.stdin</code> inside the Worker. By default, no data is provided.</li> <li>stdout <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stdout</code> will not automatically be piped through to <code>process.stdout</code> in the parent.</li> <li>stderr <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> If this is set to <code>true</code>, then <code>worker.stderr</code> will not automatically be piped through to <code>process.stderr</code> in the parent.</li> </ul> </li> </ul> <h3>Event: 'error'<span><a class="mark" href="#worker_threads_event_error" id="worker_threads_event_error">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> </ul> <p>The <code>'error'</code> event is emitted if the worker thread throws an uncaught exception. In that case, the worker will be terminated.</p> <h3>Event: 'exit'<span><a class="mark" href="#worker_threads_event_exit" id="worker_threads_event_exit">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><code>exitCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>The <code>'exit'</code> event is emitted once the worker has stopped. If the worker exited by calling <a href="#process_process_exit_code"><code>process.exit()</code></a>, the <code>exitCode</code> parameter will be the passed exit code. If the worker was terminated, the <code>exitCode</code> parameter will be <code>1</code>.</p> <h3>Event: 'message'<span><a class="mark" href="#worker_threads_event_message_1" id="worker_threads_event_message_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a> The transmitted value</li> </ul> <p>The <code>'message'</code> event is emitted when the worker thread has invoked <a href="#worker_threads_worker_postmessage_value_transferlist"><code>require('worker_threads').parentPort.postMessage()</code></a>. See the <a href="#worker_threads_event_message"><code>port.on('message')</code></a> event for more details.</p> <h3>Event: 'online'<span><a class="mark" href="#worker_threads_event_online" id="worker_threads_event_online">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>The <code>'online'</code> event is emitted when the worker thread has started executing JavaScript code.</p> <h3>worker.postMessage(value[, transferList])<span><a class="mark" href="#worker_threads_worker_postmessage_value_transferlist" id="worker_threads_worker_postmessage_value_transferlist">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type"><any></a></li> <li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object[]></a></li> </ul> <p>Send a message to the worker that will be received via <a href="#worker_threads_event_message"><code>require('worker_threads').parentPort.on('message')</code></a>. See <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> for more details.</p> <h3>worker.ref()<span><a class="mark" href="#worker_threads_worker_ref" id="worker_threads_worker_ref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref()</code>ed worker will <em>not</em> let the program exit if it's the only active handle left (the default behavior). If the worker is <code>ref()</code>ed, calling <code>ref()</code> again will have no effect.</p> <h3>worker.stderr<span><a class="mark" href="#worker_threads_worker_stderr" id="worker_threads_worker_stderr">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="#stream_class_stream_readable" class="type"><stream.Readable></a></li> </ul> <p>This is a readable stream which contains data written to <a href="#process_process_stderr"><code>process.stderr</code></a> inside the worker thread. If <code>stderr: true</code> was not passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, then data will be piped to the parent thread's <a href="#process_process_stderr"><code>process.stderr</code></a> stream.</p> <h3>worker.stdin<span><a class="mark" href="#worker_threads_worker_stdin" id="worker_threads_worker_stdin">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type"><null></a> | <a href="#stream_class_stream_writable" class="type"><stream.Writable></a></li> </ul> <p>If <code>stdin: true</code> was passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, this is a writable stream. The data written to this stream will be made available in the worker thread as <a href="#process_process_stdin"><code>process.stdin</code></a>.</p> <h3>worker.stdout<span><a class="mark" href="#worker_threads_worker_stdout" id="worker_threads_worker_stdout">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="#stream_class_stream_readable" class="type"><stream.Readable></a></li> </ul> <p>This is a readable stream which contains data written to <a href="#process_process_stdout"><code>process.stdout</code></a> inside the worker thread. If <code>stdout: true</code> was not passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, then data will be piped to the parent thread's <a href="#process_process_stdout"><code>process.stdout</code></a> stream.</p> <h3>worker.terminate([callback])<span><a class="mark" href="#worker_threads_worker_terminate_callback" id="worker_threads_worker_terminate_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li> <p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></p> <ul> <li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li> <li><code>exitCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> </li> </ul> <p>Stop all JavaScript execution in the worker thread as soon as possible. <code>callback</code> is an optional function that is invoked once this operation is known to have completed.</p> <p><strong>Warning</strong>: Currently, not all code in the internals of Node.js is prepared to expect termination at arbitrary points in time and may crash if it encounters that condition. Consequently, only call <code>.terminate()</code> if it is known that the Worker thread is not accessing Node.js core modules other than what is exposed in the <code>worker</code> module.</p> <h3>worker.threadId<span><a class="mark" href="#worker_threads_worker_threadid_1" id="worker_threads_worker_threadid_1">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> </ul> <p>An integer identifier for the referenced thread. Inside the worker thread, it is available as <a href="#worker_threads_worker_threadid"><code>require('worker_threads').threadId</code></a>.</p> <h3>worker.unref()<span><a class="mark" href="#worker_threads_worker_unref" id="worker_threads_worker_unref">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.5.0</span> </div> <p>Calling <code>unref()</code> on a worker will allow the thread to exit if this is the only active handle in the event system. If the worker is already <code>unref()</code>ed calling <code>unref()</code> again will have no effect.</p> <h1>Zlib<span><a class="mark" href="#zlib_zlib" id="zlib_zlib">#</a></span></h1> <p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p> <p>The <code>zlib</code> module provides compression functionality implemented using Gzip and Deflate/Inflate, as well as Brotli. It can be accessed using:</p> <pre><code class="language-js">const zlib = require('zlib'); </code></pre> <p>Compressing or decompressing a stream (such as a file) can be accomplished by piping the source stream data through a <code>zlib</code> stream into a destination stream:</p> <pre><code class="language-js">const gzip = zlib.createGzip(); const fs = require('fs'); const inp = fs.createReadStream('input.txt'); const out = fs.createWriteStream('input.txt.gz'); inp.pipe(gzip).pipe(out); </code></pre> <p>It is also possible to compress or decompress data in a single step:</p> <pre><code class="language-js">const input = '.................................'; zlib.deflate(input, (err, buffer) => { if (!err) { console.log(buffer.toString('base64')); } else { // handle error } }); const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64'); zlib.unzip(buffer, (err, buffer) => { if (!err) { console.log(buffer.toString()); } else { // handle error } }); </code></pre> <h2>Threadpool Usage<span><a class="mark" href="#zlib_threadpool_usage" id="zlib_threadpool_usage">#</a></span></h2> <p>Note that all zlib APIs except those that are explicitly synchronous use libuv's threadpool. This can lead to surprising effects in some applications, such as subpar performance (which can be mitigated by adjusting the <a href="#cli_uv_threadpool_size_size">pool size</a>) and/or unrecoverable and catastrophic memory fragmentation.</p> <h2>Compressing HTTP requests and responses<span><a class="mark" href="#zlib_compressing_http_requests_and_responses" id="zlib_compressing_http_requests_and_responses">#</a></span></h2> <p>The <code>zlib</code> module can be used to implement support for the <code>gzip</code>, <code>deflate</code> and <code>br</code> content-encoding mechanisms defined by <a href="https://tools.ietf.org/html/rfc7230#section-4.2">HTTP</a>.</p> <p>The HTTP <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3"><code>Accept-Encoding</code></a> header is used within an http request to identify the compression encodings accepted by the client. The <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11"><code>Content-Encoding</code></a> header is used to identify the compression encodings actually applied to a message.</p> <p>The examples given below are drastically simplified to show the basic concept. Using <code>zlib</code> encoding can be expensive, and the results ought to be cached. See <a href="#zlib_memory_usage_tuning">Memory Usage Tuning</a> for more information on the speed/memory/compression tradeoffs involved in <code>zlib</code> usage.</p> <pre><code class="language-js">// client request example const zlib = require('zlib'); const http = require('http'); const fs = require('fs'); const request = http.get({ host: 'example.com', path: '/', port: 80, headers: { 'Accept-Encoding': 'br,gzip,deflate' } }); request.on('response', (response) => { const output = fs.createWriteStream('example.com_index.html'); switch (response.headers['content-encoding']) { case 'br': response.pipe(zlib.createBrotliDecompress()).pipe(output); break; // Or, just use zlib.createUnzip() to handle both of the following cases: case 'gzip': response.pipe(zlib.createGunzip()).pipe(output); break; case 'deflate': response.pipe(zlib.createInflate()).pipe(output); break; default: response.pipe(output); break; } }); </code></pre> <pre><code class="language-js">// server example // Running a gzip operation on every request is quite expensive. // It would be much more efficient to cache the compressed buffer. const zlib = require('zlib'); const http = require('http'); const fs = require('fs'); http.createServer((request, response) => { const raw = fs.createReadStream('index.html'); let acceptEncoding = request.headers['accept-encoding']; if (!acceptEncoding) { acceptEncoding = ''; } // Note: This is not a conformant accept-encoding parser. // See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3 if (/\bdeflate\b/.test(acceptEncoding)) { response.writeHead(200, { 'Content-Encoding': 'deflate' }); raw.pipe(zlib.createDeflate()).pipe(response); } else if (/\bgzip\b/.test(acceptEncoding)) { response.writeHead(200, { 'Content-Encoding': 'gzip' }); raw.pipe(zlib.createGzip()).pipe(response); } else if (/\bbr\b/.test(acceptEncoding)) { response.writeHead(200, { 'Content-Encoding': 'br' }); raw.pipe(zlib.createBrotliCompress()).pipe(response); } else { response.writeHead(200, {}); raw.pipe(response); } }).listen(1337); </code></pre> <p>By default, the <code>zlib</code> methods will throw an error when decompressing truncated data. However, if it is known that the data is incomplete, or the desire is to inspect only the beginning of a compressed file, it is possible to suppress the default error handling by changing the flushing method that is used to decompress the last chunk of input data:</p> <pre><code class="language-js">// This is a truncated version of the buffer from the above examples const buffer = Buffer.from('eJzT0yMA', 'base64'); zlib.unzip( buffer, // For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH. { finishFlush: zlib.constants.Z_SYNC_FLUSH }, (err, buffer) => { if (!err) { console.log(buffer.toString()); } else { // handle error } }); </code></pre> <p>This will not change the behavior in other error-throwing situations, e.g. when the input data has an invalid format. Using this method, it will not be possible to determine whether the input ended prematurely or lacks the integrity checks, making it necessary to manually check that the decompressed result is valid.</p> <h2>Memory Usage Tuning<span><a class="mark" href="#zlib_memory_usage_tuning" id="zlib_memory_usage_tuning">#</a></span></h2> <h3>For zlib-based streams<span><a class="mark" href="#zlib_for_zlib_based_streams" id="zlib_for_zlib_based_streams">#</a></span></h3> <p>From <code>zlib/zconf.h</code>, modified to Node.js's usage:</p> <p>The memory requirements for deflate are (in bytes):</p> <!-- eslint-disable semi --> <pre><code class="language-js">(1 << (windowBits + 2)) + (1 << (memLevel + 9)) </code></pre> <p>That is: 128K for <code>windowBits</code> = 15 + 128K for <code>memLevel</code> = 8 (default values) plus a few kilobytes for small objects.</p> <p>For example, to reduce the default memory requirements from 256K to 128K, the options should be set to:</p> <pre><code class="language-js">const options = { windowBits: 14, memLevel: 7 }; </code></pre> <p>This will, however, generally degrade compression.</p> <p>The memory requirements for inflate are (in bytes) <code>1 << windowBits</code>. That is, 32K for <code>windowBits</code> = 15 (default value) plus a few kilobytes for small objects.</p> <p>This is in addition to a single internal output slab buffer of size <code>chunkSize</code>, which defaults to 16K.</p> <p>The speed of <code>zlib</code> compression is affected most dramatically by the <code>level</code> setting. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster.</p> <p>In general, greater memory usage options will mean that Node.js has to make fewer calls to <code>zlib</code> because it will be able to process more data on each <code>write</code> operation. So, this is another factor that affects the speed, at the cost of memory usage.</p> <h3>For Brotli-based streams<span><a class="mark" href="#zlib_for_brotli_based_streams" id="zlib_for_brotli_based_streams">#</a></span></h3> <p>There are equivalents to the zlib options for Brotli-based streams, although these options have different ranges than the zlib ones:</p> <ul> <li>zlib’s <code>level</code> option matches Brotli’s <code>BROTLI_PARAM_QUALITY</code> option.</li> <li>zlib’s <code>windowBits</code> option matches Brotli’s <code>BROTLI_PARAM_LGWIN</code> option.</li> </ul> <p>See <a href="#zlib_brotli_constants">below</a> for more details on Brotli-specific options.</p> <h2>Flushing<span><a class="mark" href="#zlib_flushing" id="zlib_flushing">#</a></span></h2> <p>Calling <a href="#zlib_zlib_flush_kind_callback"><code>.flush()</code></a> on a compression stream will make <code>zlib</code> return as much output as currently possible. This may come at the cost of degraded compression quality, but can be useful when data needs to be available as soon as possible.</p> <p>In the following example, <code>flush()</code> is used to write a compressed partial HTTP response to the client:</p> <pre><code class="language-js">const zlib = require('zlib'); const http = require('http'); http.createServer((request, response) => { // For the sake of simplicity, the Accept-Encoding checks are omitted. response.writeHead(200, { 'content-encoding': 'gzip' }); const output = zlib.createGzip(); output.pipe(response); setInterval(() => { output.write(`The current time is ${Date()}\n`, () => { // The data has been passed to zlib, but the compression algorithm may // have decided to buffer the data for more efficient compression. // Calling .flush() will make the data available as soon as the client // is ready to receive it. output.flush(); }); }, 1000); }).listen(1337); </code></pre> <h2>Constants<span><a class="mark" href="#zlib_constants" id="zlib_constants">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <h3>zlib constants<span><a class="mark" href="#zlib_zlib_constants" id="zlib_zlib_constants">#</a></span></h3> <p>All of the constants defined in <code>zlib.h</code> are also defined on <code>require('zlib').constants</code>. In the normal course of operations, it will not be necessary to use these constants. They are documented so that their presence is not surprising. This section is taken almost directly from the <a href="https://zlib.net/manual.html#Constants">zlib documentation</a>. See <a href="https://zlib.net/manual.html#Constants">https://zlib.net/manual.html#Constants</a> for more details.</p> <p>Previously, the constants were available directly from <code>require('zlib')</code>, for instance <code>zlib.Z_NO_FLUSH</code>. Accessing the constants directly from the module is currently still possible but is deprecated.</p> <p>Allowed flush values.</p> <ul> <li><code>zlib.constants.Z_NO_FLUSH</code></li> <li><code>zlib.constants.Z_PARTIAL_FLUSH</code></li> <li><code>zlib.constants.Z_SYNC_FLUSH</code></li> <li><code>zlib.constants.Z_FULL_FLUSH</code></li> <li><code>zlib.constants.Z_FINISH</code></li> <li><code>zlib.constants.Z_BLOCK</code></li> <li><code>zlib.constants.Z_TREES</code></li> </ul> <p>Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events.</p> <ul> <li><code>zlib.constants.Z_OK</code></li> <li><code>zlib.constants.Z_STREAM_END</code></li> <li><code>zlib.constants.Z_NEED_DICT</code></li> <li><code>zlib.constants.Z_ERRNO</code></li> <li><code>zlib.constants.Z_STREAM_ERROR</code></li> <li><code>zlib.constants.Z_DATA_ERROR</code></li> <li><code>zlib.constants.Z_MEM_ERROR</code></li> <li><code>zlib.constants.Z_BUF_ERROR</code></li> <li><code>zlib.constants.Z_VERSION_ERROR</code></li> </ul> <p>Compression levels.</p> <ul> <li><code>zlib.constants.Z_NO_COMPRESSION</code></li> <li><code>zlib.constants.Z_BEST_SPEED</code></li> <li><code>zlib.constants.Z_BEST_COMPRESSION</code></li> <li><code>zlib.constants.Z_DEFAULT_COMPRESSION</code></li> </ul> <p>Compression strategy.</p> <ul> <li><code>zlib.constants.Z_FILTERED</code></li> <li><code>zlib.constants.Z_HUFFMAN_ONLY</code></li> <li><code>zlib.constants.Z_RLE</code></li> <li><code>zlib.constants.Z_FIXED</code></li> <li><code>zlib.constants.Z_DEFAULT_STRATEGY</code></li> </ul> <h3>Brotli constants<span><a class="mark" href="#zlib_brotli_constants" id="zlib_brotli_constants">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <p>There are several options and other constants available for Brotli-based streams:</p> <h4>Flush operations<span><a class="mark" href="#zlib_flush_operations" id="zlib_flush_operations">#</a></span></h4> <p>The following values are valid flush operations for Brotli-based streams:</p> <ul> <li><code>zlib.constants.BROTLI_OPERATION_PROCESS</code> (default for all operations)</li> <li><code>zlib.constants.BROTLI_OPERATION_FLUSH</code> (default when calling <code>.flush()</code>)</li> <li><code>zlib.constants.BROTLI_OPERATION_FINISH</code> (default for the last chunk)</li> <li> <p><code>zlib.constants.BROTLI_OPERATION_EMIT_METADATA</code></p> <ul> <li>This particular operation may be hard to use in a Node.js context, as the streaming layer makes it hard to know which data will end up in this frame. Also, there is currently no way to consume this data through the Node.js API.</li> </ul> </li> </ul> <h4>Compressor options<span><a class="mark" href="#zlib_compressor_options" id="zlib_compressor_options">#</a></span></h4> <p>There are several options that can be set on Brotli encoders, affecting compression efficiency and speed. Both the keys and the values can be accessed as properties of the <code>zlib.constants</code> object.</p> <p>The most important options are:</p> <ul> <li> <p><code>BROTLI_PARAM_MODE</code></p> <ul> <li><code>BROTLI_MODE_GENERIC</code> (default)</li> <li><code>BROTLI_MODE_TEXT</code>, adjusted for UTF-8 text</li> <li><code>BROTLI_MODE_FONT</code>, adjusted for WOFF 2.0 fonts</li> </ul> </li> <li> <p><code>BROTLI_PARAM_QUALITY</code></p> <ul> <li>Ranges from <code>BROTLI_MIN_QUALITY</code> to <code>BROTLI_MAX_QUALITY</code>, with a default of <code>BROTLI_DEFAULT_QUALITY</code>.</li> </ul> </li> <li> <p><code>BROTLI_PARAM_SIZE_HINT</code></p> <ul> <li>Integer value representing the expected input size; defaults to <code>0</code> for an unknown input size.</li> </ul> </li> </ul> <p>The following flags can be set for advanced control over the compression algorithm and memory usage tuning:</p> <ul> <li> <p><code>BROTLI_PARAM_LGWIN</code></p> <ul> <li>Ranges from <code>BROTLI_MIN_WINDOW_BITS</code> to <code>BROTLI_MAX_WINDOW_BITS</code>, with a default of <code>BROTLI_DEFAULT_WINDOW</code>, or up to <code>BROTLI_LARGE_MAX_WINDOW_BITS</code> if the <code>BROTLI_PARAM_LARGE_WINDOW</code> flag is set.</li> </ul> </li> <li> <p><code>BROTLI_PARAM_LGBLOCK</code></p> <ul> <li>Ranges from <code>BROTLI_MIN_INPUT_BLOCK_BITS</code> to <code>BROTLI_MAX_INPUT_BLOCK_BITS</code>.</li> </ul> </li> <li> <p><code>BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING</code></p> <ul> <li>Boolean flag that decreases compression ratio in favour of decompression speed.</li> </ul> </li> <li> <p><code>BROTLI_PARAM_LARGE_WINDOW</code></p> <ul> <li>Boolean flag enabling “Large Window Brotli” mode (not compatible with the Brotli format as standardized in <a href="https://www.rfc-editor.org/rfc/rfc7932.txt">RFC 7932</a>).</li> </ul> </li> <li> <p><code>BROTLI_PARAM_NPOSTFIX</code></p> <ul> <li>Ranges from <code>0</code> to <code>BROTLI_MAX_NPOSTFIX</code>.</li> </ul> </li> <li> <p><code>BROTLI_PARAM_NDIRECT</code></p> <ul> <li>Ranges from <code>0</code> to <code>15 << NPOSTFIX</code> in steps of <code>1 << NPOSTFIX</code>.</li> </ul> </li> </ul> <h4>Decompressor options<span><a class="mark" href="#zlib_decompressor_options" id="zlib_decompressor_options">#</a></span></h4> <p>These advanced options are available for controlling decompression:</p> <ul> <li> <p><code>BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION</code></p> <ul> <li>Boolean flag that affects internal memory allocation patterns.</li> </ul> </li> <li> <p><code>BROTLI_DECODER_PARAM_LARGE_WINDOW</code></p> <ul> <li>Boolean flag enabling “Large Window Brotli” mode (not compatible with the Brotli format as standardized in <a href="https://www.rfc-editor.org/rfc/rfc7932.txt">RFC 7932</a>).</li> </ul> </li> </ul> <h2>Class: Options<span><a class="mark" href="#zlib_class_options" id="zlib_class_options">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>dictionary</code> option can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>dictionary</code> option can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v5.11.0</td> <td><p>The <code>finishFlush</code> option is supported now.</p></td></tr> <tr><td>v0.11.1</td> <td><p><span>Added in: v0.11.1</span></p></td></tr> </tbody></table> </details> </div> <p>Each zlib-based class takes an <code>options</code> object. All options are optional.</p> <p>Note that some options are only relevant when compressing, and are ignored by the decompression classes.</p> <ul> <li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>zlib.constants.Z_NO_FLUSH</code></li> <li><code>finishFlush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>zlib.constants.Z_FINISH</code></li> <li><code>chunkSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>16 * 1024</code></li> <li><code>windowBits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>level</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> (compression only)</li> <li><code>memLevel</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> (compression only)</li> <li><code>strategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> (compression only)</li> <li><code>dictionary</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> (deflate/inflate only, empty dictionary by default)</li> <li><code>info</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> (If <code>true</code>, returns an object with <code>buffer</code> and <code>engine</code>.)</li> </ul> <p>See the description of <code>deflateInit2</code> and <code>inflateInit2</code> at <a href="https://zlib.net/manual.html#Advanced">https://zlib.net/manual.html#Advanced</a> for more information on these.</p> <h2>Class: BrotliOptions<span><a class="mark" href="#zlib_class_brotlioptions" id="zlib_class_brotlioptions">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <p>Each Brotli-based class takes an <code>options</code> object. All options are optional.</p> <ul> <li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>zlib.constants.BROTLI_OPERATION_PROCESS</code></li> <li><code>finishFlush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>zlib.constants.BROTLI_OPERATION_FINISH</code></li> <li><code>chunkSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> <strong>Default:</strong> <code>16 * 1024</code></li> <li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Key-value object containing indexed <a href="#zlib_brotli_constants">Brotli parameters</a>.</li> </ul> <p>For example:</p> <pre><code class="language-js">const stream = zlib.createBrotliCompress({ chunkSize: 32 * 1024, params: { [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT, [zlib.constants.BROTLI_PARAM_QUALITY]: 4, [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size } }); </code></pre> <h2>Class: zlib.BrotliCompress<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/zlib.js#L793">[src]</a><span><a class="mark" href="#zlib_class_zlib_brotlicompress" id="zlib_class_zlib_brotlicompress">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <p>Compress data using the Brotli algorithm.</p> <h2>Class: zlib.BrotliDecompress<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/zlib.js#L801">[src]</a><span><a class="mark" href="#zlib_class_zlib_brotlidecompress" id="zlib_class_zlib_brotlidecompress">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <p>Decompress data using the Brotli algorithm.</p> <h2>Class: zlib.Deflate<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/zlib.js#L680">[src]</a><span><a class="mark" href="#zlib_class_zlib_deflate" id="zlib_class_zlib_deflate">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <p>Compress data using deflate.</p> <h2>Class: zlib.DeflateRaw<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/zlib.js#L708">[src]</a><span><a class="mark" href="#zlib_class_zlib_deflateraw" id="zlib_class_zlib_deflateraw">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <p>Compress data using deflate, and do not append a <code>zlib</code> header.</p> <h2>Class: zlib.Gunzip<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/zlib.js#L701">[src]</a><span><a class="mark" href="#zlib_class_zlib_gunzip" id="zlib_class_zlib_gunzip">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.0.0</td> <td><p>Trailing garbage at the end of the input stream will now result in an <code>'error'</code> event.</p></td></tr> <tr><td>v5.9.0</td> <td><p>Multiple concatenated gzip file members are supported now.</p></td></tr> <tr><td>v5.0.0</td> <td><p>A truncated input stream will now result in an <code>'error'</code> event.</p></td></tr> <tr><td>v0.5.8</td> <td><p><span>Added in: v0.5.8</span></p></td></tr> </tbody></table> </details> </div> <p>Decompress a gzip stream.</p> <h2>Class: zlib.Gzip<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/zlib.js#L694">[src]</a><span><a class="mark" href="#zlib_class_zlib_gzip" id="zlib_class_zlib_gzip">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <p>Compress data using gzip.</p> <h2>Class: zlib.Inflate<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/zlib.js#L687">[src]</a><span><a class="mark" href="#zlib_class_zlib_inflate" id="zlib_class_zlib_inflate">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v5.0.0</td> <td><p>A truncated input stream will now result in an <code>'error'</code> event.</p></td></tr> <tr><td>v0.5.8</td> <td><p><span>Added in: v0.5.8</span></p></td></tr> </tbody></table> </details> </div> <p>Decompress a deflate stream.</p> <h2>Class: zlib.InflateRaw<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/zlib.js#L716">[src]</a><span><a class="mark" href="#zlib_class_zlib_inflateraw" id="zlib_class_zlib_inflateraw">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v6.8.0</td> <td><p>Custom dictionaries are now supported by <code>InflateRaw</code>.</p></td></tr> <tr><td>v5.0.0</td> <td><p>A truncated input stream will now result in an <code>'error'</code> event.</p></td></tr> <tr><td>v0.5.8</td> <td><p><span>Added in: v0.5.8</span></p></td></tr> </tbody></table> </details> </div> <p>Decompress a raw deflate stream.</p> <h2>Class: zlib.Unzip<a class="srclink" href="https://github.com/nodejs/node/blob/5182a7ece0b71feeb9157f7aa348a15d53e32058/lib/zlib.js#L723">[src]</a><span><a class="mark" href="#zlib_class_zlib_unzip" id="zlib_class_zlib_unzip">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <p>Decompress either a Gzip- or Deflate-compressed stream by auto-detecting the header.</p> <h2>Class: zlib.ZlibBase<span><a class="mark" href="#zlib_class_zlib_zlibbase" id="zlib_class_zlib_zlibbase">#</a></span></h2> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v10.16.0</td> <td><p>This class was renamed from <code>Zlib</code> to <code>ZlibBase</code>.</p></td></tr> <tr><td>v0.5.8</td> <td><p><span>Added in: v0.5.8</span></p></td></tr> </tbody></table> </details> </div> <p>Not exported by the <code>zlib</code> module. It is documented here because it is the base class of the compressor/decompressor classes.</p> <p>This class inherits from <a href="#stream_class_stream_transform"><code>stream.Transform</code></a>, allowing <code>zlib</code> objects to be used in pipes and similar stream operations.</p> <h3>zlib.bytesRead<span><a class="mark" href="#zlib_zlib_bytesread" id="zlib_zlib_bytesread">#</a></span></h3> <div class="api_metadata"> <span>Added in: v8.1.0</span><span>Deprecated since: v10.0.0</span> </div> <p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#zlib_zlib_byteswritten"><code>zlib.bytesWritten</code></a> instead.</div><p></p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>Deprecated alias for <a href="#zlib_zlib_byteswritten"><code>zlib.bytesWritten</code></a>. This original name was chosen because it also made sense to interpret the value as the number of bytes read by the engine, but is inconsistent with other streams in Node.js that expose values under these names.</p> <h3>zlib.bytesWritten<span><a class="mark" href="#zlib_zlib_byteswritten" id="zlib_zlib_byteswritten">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.0.0</span> </div> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li> </ul> <p>The <code>zlib.bytesWritten</code> property specifies the number of bytes written to the engine, before the bytes are processed (compressed or decompressed, as appropriate for the derived class).</p> <h3>zlib.close([callback])<span><a class="mark" href="#zlib_zlib_close_callback" id="zlib_zlib_close_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.9.4</span> </div> <ul> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Close the underlying handle.</p> <h3>zlib.flush([kind, ]callback)<span><a class="mark" href="#zlib_zlib_flush_kind_callback" id="zlib_zlib_flush_kind_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <ul> <li><code>kind</code> <strong>Default:</strong> <code>zlib.constants.Z_FULL_FLUSH</code> for zlib-based streams, <code>zlib.constants.BROTLI_OPERATION_FLUSH</code> for Brotli-based streams.</li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>Flush pending data. Don't call this frivolously, premature flushes negatively impact the effectiveness of the compression algorithm.</p> <p>Calling this only flushes data from the internal <code>zlib</code> state, and does not perform flushing of any kind on the streams level. Rather, it behaves like a normal call to <code>.write()</code>, i.e. it will be queued up behind other pending writes and will only produce output when data is being read from the stream.</p> <h3>zlib.params(level, strategy, callback)<span><a class="mark" href="#zlib_zlib_params_level_strategy_callback" id="zlib_zlib_params_level_strategy_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.11.4</span> </div> <ul> <li><code>level</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>strategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <p>This function is only available for zlib-based streams, i.e. not Brotli.</p> <p>Dynamically update the compression level and compression strategy. Only applicable to deflate algorithm.</p> <h3>zlib.reset()<span><a class="mark" href="#zlib_zlib_reset" id="zlib_zlib_reset">#</a></span></h3> <div class="api_metadata"> <span>Added in: v0.7.0</span> </div> <p>Reset the compressor/decompressor to factory defaults. Only applicable to the inflate and deflate algorithms.</p> <h2>zlib.constants<span><a class="mark" href="#zlib_zlib_constants_1" id="zlib_zlib_constants_1">#</a></span></h2> <div class="api_metadata"> <span>Added in: v7.0.0</span> </div> <p>Provides an object enumerating Zlib-related constants.</p> <h2>zlib.createBrotliCompress([options])<span><a class="mark" href="#zlib_zlib_createbrotlicompress_options" id="zlib_zlib_createbrotlicompress_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><code>options</code> <a href="#zlib_class_brotlioptions" class="type"><brotli options></a></li> </ul> <p>Creates and returns a new <a href="#zlib_class_zlib_brotlicompress"><code>BrotliCompress</code></a> object.</p> <h2>zlib.createBrotliDecompress([options])<span><a class="mark" href="#zlib_zlib_createbrotlidecompress_options" id="zlib_zlib_createbrotlidecompress_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><code>options</code> <a href="#zlib_class_brotlioptions" class="type"><brotli options></a></li> </ul> <p>Creates and returns a new <a href="#zlib_class_zlib_brotlidecompress"><code>BrotliDecompress</code></a> object.</p> <h2>zlib.createDeflate([options])<span><a class="mark" href="#zlib_zlib_createdeflate_options" id="zlib_zlib_createdeflate_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Creates and returns a new <a href="#zlib_class_zlib_deflate"><code>Deflate</code></a> object.</p> <h2>zlib.createDeflateRaw([options])<span><a class="mark" href="#zlib_zlib_createdeflateraw_options" id="zlib_zlib_createdeflateraw_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Creates and returns a new <a href="#zlib_class_zlib_deflateraw"><code>DeflateRaw</code></a> object.</p> <p>An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when <code>windowBits</code> is set to 8 for raw deflate streams. zlib would automatically set <code>windowBits</code> to 9 if was initially set to 8. Newer versions of zlib will throw an exception, so Node.js restored the original behavior of upgrading a value of 8 to 9, since passing <code>windowBits = 9</code> to zlib actually results in a compressed stream that effectively uses an 8-bit window only.</p> <h2>zlib.createGunzip([options])<span><a class="mark" href="#zlib_zlib_creategunzip_options" id="zlib_zlib_creategunzip_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Creates and returns a new <a href="#zlib_class_zlib_gunzip"><code>Gunzip</code></a> object.</p> <h2>zlib.createGzip([options])<span><a class="mark" href="#zlib_zlib_creategzip_options" id="zlib_zlib_creategzip_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Creates and returns a new <a href="#zlib_class_zlib_gzip"><code>Gzip</code></a> object.</p> <h2>zlib.createInflate([options])<span><a class="mark" href="#zlib_zlib_createinflate_options" id="zlib_zlib_createinflate_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Creates and returns a new <a href="#zlib_class_zlib_inflate"><code>Inflate</code></a> object.</p> <h2>zlib.createInflateRaw([options])<span><a class="mark" href="#zlib_zlib_createinflateraw_options" id="zlib_zlib_createinflateraw_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Creates and returns a new <a href="#zlib_class_zlib_inflateraw"><code>InflateRaw</code></a> object.</p> <h2>zlib.createUnzip([options])<span><a class="mark" href="#zlib_zlib_createunzip_options" id="zlib_zlib_createunzip_options">#</a></span></h2> <div class="api_metadata"> <span>Added in: v0.5.8</span> </div> <ul> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Creates and returns a new <a href="#zlib_class_zlib_unzip"><code>Unzip</code></a> object.</p> <h2>Convenience Methods<span><a class="mark" href="#zlib_convenience_methods" id="zlib_convenience_methods">#</a></span></h2> <p>All of these take a <a href="#buffer_class_buffer"><code>Buffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><code>DataView</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or string as the first argument, an optional second argument to supply options to the <code>zlib</code> classes and will call the supplied callback with <code>callback(error, result)</code>.</p> <p>Every method has a <code>*Sync</code> counterpart, which accept the same arguments, but without a callback.</p> <h3>zlib.brotliCompress(buffer[, options], callback)<span><a class="mark" href="#zlib_zlib_brotlicompress_buffer_options_callback" id="zlib_zlib_brotlicompress_buffer_options_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="#zlib_class_brotlioptions" class="type"><brotli options></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <h3>zlib.brotliCompressSync(buffer[, options])<span><a class="mark" href="#zlib_zlib_brotlicompresssync_buffer_options" id="zlib_zlib_brotlicompresssync_buffer_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="#zlib_class_brotlioptions" class="type"><brotli options></a></li> </ul> <p>Compress a chunk of data with <a href="#zlib_class_zlib_brotlicompress"><code>BrotliCompress</code></a>.</p> <h3>zlib.brotliDecompress(buffer[, options], callback)<span><a class="mark" href="#zlib_zlib_brotlidecompress_buffer_options_callback" id="zlib_zlib_brotlidecompress_buffer_options_callback">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="#zlib_class_brotlioptions" class="type"><brotli options></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <h3>zlib.brotliDecompressSync(buffer[, options])<span><a class="mark" href="#zlib_zlib_brotlidecompresssync_buffer_options" id="zlib_zlib_brotlidecompresssync_buffer_options">#</a></span></h3> <div class="api_metadata"> <span>Added in: v10.16.0</span> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="#zlib_class_brotlioptions" class="type"><brotli options></a></li> </ul> <p>Decompress a chunk of data with <a href="#zlib_class_zlib_brotlidecompress"><code>BrotliDecompress</code></a>.</p> <h3>zlib.deflate(buffer[, options], callback)<span><a class="mark" href="#zlib_zlib_deflate_buffer_options_callback" id="zlib_zlib_deflate_buffer_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.6.0</td> <td><p><span>Added in: v0.6.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <h3>zlib.deflateSync(buffer[, options])<span><a class="mark" href="#zlib_zlib_deflatesync_buffer_options" id="zlib_zlib_deflatesync_buffer_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.11.12</td> <td><p><span>Added in: v0.11.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Compress a chunk of data with <a href="#zlib_class_zlib_deflate"><code>Deflate</code></a>.</p> <h3>zlib.deflateRaw(buffer[, options], callback)<span><a class="mark" href="#zlib_zlib_deflateraw_buffer_options_callback" id="zlib_zlib_deflateraw_buffer_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.6.0</td> <td><p><span>Added in: v0.6.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <h3>zlib.deflateRawSync(buffer[, options])<span><a class="mark" href="#zlib_zlib_deflaterawsync_buffer_options" id="zlib_zlib_deflaterawsync_buffer_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.11.12</td> <td><p><span>Added in: v0.11.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Compress a chunk of data with <a href="#zlib_class_zlib_deflateraw"><code>DeflateRaw</code></a>.</p> <h3>zlib.gunzip(buffer[, options], callback)<span><a class="mark" href="#zlib_zlib_gunzip_buffer_options_callback" id="zlib_zlib_gunzip_buffer_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.6.0</td> <td><p><span>Added in: v0.6.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <h3>zlib.gunzipSync(buffer[, options])<span><a class="mark" href="#zlib_zlib_gunzipsync_buffer_options" id="zlib_zlib_gunzipsync_buffer_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.11.12</td> <td><p><span>Added in: v0.11.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Decompress a chunk of data with <a href="#zlib_class_zlib_gunzip"><code>Gunzip</code></a>.</p> <h3>zlib.gzip(buffer[, options], callback)<span><a class="mark" href="#zlib_zlib_gzip_buffer_options_callback" id="zlib_zlib_gzip_buffer_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.6.0</td> <td><p><span>Added in: v0.6.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <h3>zlib.gzipSync(buffer[, options])<span><a class="mark" href="#zlib_zlib_gzipsync_buffer_options" id="zlib_zlib_gzipsync_buffer_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.11.12</td> <td><p><span>Added in: v0.11.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Compress a chunk of data with <a href="#zlib_class_zlib_gzip"><code>Gzip</code></a>.</p> <h3>zlib.inflate(buffer[, options], callback)<span><a class="mark" href="#zlib_zlib_inflate_buffer_options_callback" id="zlib_zlib_inflate_buffer_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.6.0</td> <td><p><span>Added in: v0.6.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <h3>zlib.inflateSync(buffer[, options])<span><a class="mark" href="#zlib_zlib_inflatesync_buffer_options" id="zlib_zlib_inflatesync_buffer_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.11.12</td> <td><p><span>Added in: v0.11.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Decompress a chunk of data with <a href="#zlib_class_zlib_inflate"><code>Inflate</code></a>.</p> <h3>zlib.inflateRaw(buffer[, options], callback)<span><a class="mark" href="#zlib_zlib_inflateraw_buffer_options_callback" id="zlib_zlib_inflateraw_buffer_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.6.0</td> <td><p><span>Added in: v0.6.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <h3>zlib.inflateRawSync(buffer[, options])<span><a class="mark" href="#zlib_zlib_inflaterawsync_buffer_options" id="zlib_zlib_inflaterawsync_buffer_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.11.12</td> <td><p><span>Added in: v0.11.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Decompress a chunk of data with <a href="#zlib_class_zlib_inflateraw"><code>InflateRaw</code></a>.</p> <h3>zlib.unzip(buffer[, options], callback)<span><a class="mark" href="#zlib_zlib_unzip_buffer_options_callback" id="zlib_zlib_unzip_buffer_options_callback">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.6.0</td> <td><p><span>Added in: v0.6.0</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> <li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li> </ul> <h3>zlib.unzipSync(buffer[, options])<span><a class="mark" href="#zlib_zlib_unzipsync_buffer_options" id="zlib_zlib_unzipsync_buffer_options">#</a></span></h3> <div class="api_metadata"> <details class="changelog"><summary>History</summary> <table> <tbody><tr><th>Version</th><th>Changes</th></tr> <tr><td>v9.4.0</td> <td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr> <tr><td>v8.0.0</td> <td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr> <tr><td>v0.11.12</td> <td><p><span>Added in: v0.11.12</span></p></td></tr> </tbody></table> </details> </div> <ul> <li><code>buffer</code> <a href="#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type"><TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type"><DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type"><ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li> <li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li> </ul> <p>Decompress a chunk of data with <a href="#zlib_class_zlib_unzip"><code>Unzip</code></a>.</p> </div> </div> </div> <script src="assets/sh_main.js"></script> <script src="assets/sh_javascript.min.js"></script> <script>highlight(undefined, undefined, 'pre');</script> </body> </html>