ÿØÿà JFIF ` ` ÿþxØ
| Server IP : 109.234.164.53 / Your IP : 216.73.216.110 Web Server : Apache System : Linux cervelle.o2switch.net 4.18.0-553.32.1.lve.el8.x86_64 #1 SMP Thu Dec 19 13:14:03 UTC 2024 x86_64 User : computer3 ( 1098) PHP Version : 7.1.33 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : OFF | Pkexec : OFF Directory : /opt/alt/alt-nodejs9/root/lib/node_modules/npm/html/html/api/ |
Upload File : |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>About this Documentation | Node.js v9.11.2 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>
<!--introduced_in=v0.10.0-->
<ul>
<li><a class="nav-documentation" href="documentation.html">About these Docs</a></li>
<li><a class="nav-synopsis" href="synopsis.html">Usage & Example</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a class="nav-assert" href="assert.html">Assertion Testing</a></li>
<li><a class="nav-async_hooks" href="async_hooks.html">Async Hooks</a></li>
<li><a class="nav-buffer" href="buffer.html">Buffer</a></li>
<li><a class="nav-addons" href="addons.html">C++ Addons</a></li>
<li><a class="nav-n-api" href="n-api.html">C/C++ Addons - N-API</a></li>
<li><a class="nav-child_process" href="child_process.html">Child Processes</a></li>
<li><a class="nav-cluster" href="cluster.html">Cluster</a></li>
<li><a class="nav-cli" href="cli.html">Command Line Options</a></li>
<li><a class="nav-console" href="console.html">Console</a></li>
<li><a class="nav-crypto" href="crypto.html">Crypto</a></li>
<li><a class="nav-debugger" href="debugger.html">Debugger</a></li>
<li><a class="nav-deprecations" href="deprecations.html">Deprecated APIs</a></li>
<li><a class="nav-dns" href="dns.html">DNS</a></li>
<li><a class="nav-domain" href="domain.html">Domain</a></li>
<li><a class="nav-esm" href="esm.html">ECMAScript Modules</a></li>
<li><a class="nav-errors" href="errors.html">Errors</a></li>
<li><a class="nav-events" href="events.html">Events</a></li>
<li><a class="nav-fs" href="fs.html">File System</a></li>
<li><a class="nav-globals" href="globals.html">Globals</a></li>
<li><a class="nav-http" href="http.html">HTTP</a></li>
<li><a class="nav-http2" href="http2.html">HTTP/2</a></li>
<li><a class="nav-https" href="https.html">HTTPS</a></li>
<li><a class="nav-inspector" href="inspector.html">Inspector</a></li>
<li><a class="nav-intl" href="intl.html">Internationalization</a></li>
<li><a class="nav-modules" href="modules.html">Modules</a></li>
<li><a class="nav-net" href="net.html">Net</a></li>
<li><a class="nav-os" href="os.html">OS</a></li>
<li><a class="nav-path" href="path.html">Path</a></li>
<li><a class="nav-perf_hooks" href="perf_hooks.html">Performance Hooks</a></li>
<li><a class="nav-process" href="process.html">Process</a></li>
<li><a class="nav-punycode" href="punycode.html">Punycode</a></li>
<li><a class="nav-querystring" href="querystring.html">Query Strings</a></li>
<li><a class="nav-readline" href="readline.html">Readline</a></li>
<li><a class="nav-repl" href="repl.html">REPL</a></li>
<li><a class="nav-stream" href="stream.html">Stream</a></li>
<li><a class="nav-string_decoder" href="string_decoder.html">String Decoder</a></li>
<li><a class="nav-timers" href="timers.html">Timers</a></li>
<li><a class="nav-tls" href="tls.html">TLS/SSL</a></li>
<li><a class="nav-tracing" href="tracing.html">Tracing</a></li>
<li><a class="nav-tty" href="tty.html">TTY</a></li>
<li><a class="nav-dgram" href="dgram.html">UDP/Datagram</a></li>
<li><a class="nav-url" href="url.html">URL</a></li>
<li><a class="nav-util" href="util.html">Utilities</a></li>
<li><a class="nav-v8" href="v8.html">V8</a></li>
<li><a class="nav-vm" href="vm.html">VM</a></li>
<li><a class="nav-zlib" href="zlib.html">ZLIB</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a class="nav-https-github-com-nodejs-node" href="https://github.com/nodejs/node">GitHub Repo & Issue Tracker</a></li>
<li><a class="nav-https-groups-google-com-group-nodejs" href="https://groups.google.com/group/nodejs">Mailing List</a></li>
</ul>
</div>
<div id="column1" data-id="all" class="interior">
<header>
<h1>Node.js v9.11.2 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-v9.x/api/all.html">9.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v8.x/api/all.html">8.x <b>LTS</b></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 <b>LTS</b></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 <b>LTS</b></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><span class="stability_undefined"><a href="#documentation_about_this_documentation">About this Documentation</a></span><ul>
<li><span class="stability_undefined"><a href="#documentation_contributing">Contributing</a></span></li>
<li><span class="stability_undefined"><a href="#documentation_stability_index">Stability Index</a></span></li>
<li><span class="stability_1"><a href="#documentation_json_output">JSON Output</a></span></li>
<li><span class="stability_undefined"><a href="#documentation_syscalls_and_man_pages">Syscalls and man pages</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#synopsis_usage">Usage</a></span><ul>
<li><span class="stability_undefined"><a href="#synopsis_example">Example</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#assert_assert">Assert</a></span><ul>
<li><span class="stability_undefined"><a href="#assert_strict_mode">Strict mode</a></span></li>
<li><span class="stability_0"><a href="#assert_legacy_mode">Legacy mode</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_value_message">assert(value[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_deepequal_actual_expected_message">assert.deepEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_deepstrictequal_actual_expected_message">assert.deepStrictEqual(actual, expected[, message])</a></span><ul>
<li><span class="stability_undefined"><a href="#assert_comparison_details">Comparison details</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#assert_assert_doesnotthrow_block_error_message">assert.doesNotThrow(block[, error][, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_equal_actual_expected_message">assert.equal(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_fail_message">assert.fail([message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_fail_actual_expected_message_operator_stackstartfunction">assert.fail(actual, expected[, message[, operator[, stackStartFunction]]])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_iferror_value">assert.ifError(value)</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_notdeepequal_actual_expected_message">assert.notDeepEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_notdeepstrictequal_actual_expected_message">assert.notDeepStrictEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_notequal_actual_expected_message">assert.notEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_notstrictequal_actual_expected_message">assert.notStrictEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_ok_value_message">assert.ok(value[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_strictequal_actual_expected_message">assert.strictEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_throws_block_error_message">assert.throws(block[, error][, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_caveats">Caveats</a></span></li>
</ul>
</li>
<li><span class="stability_1"><a href="#async_hooks_async_hooks">Async Hooks</a></span><ul>
<li><span class="stability_undefined"><a href="#async_hooks_terminology">Terminology</a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_public_api">Public API</a></span><ul>
<li><span class="stability_undefined"><a href="#async_hooks_overview">Overview</a></span><ul>
<li><span class="stability_undefined"><a href="#async_hooks_async_hooks_createhook_callbacks"><code>async_hooks.createHook(callbacks)</code></a></span><ul>
<li><span class="stability_undefined"><a href="#async_hooks_error_handling">Error Handling</a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_printing_in_asynchooks_callbacks">Printing in AsyncHooks callbacks</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#async_hooks_asynchook_enable"><code>asyncHook.enable()</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_asynchook_disable"><code>asyncHook.disable()</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_hook_callbacks">Hook Callbacks</a></span><ul>
<li><span class="stability_undefined"><a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init(asyncId, type, triggerAsyncId, resource)</code></a></span><ul>
<li><span class="stability_undefined"><a href="#async_hooks_type"><code>type</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_triggerid"><code>triggerId</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_resource"><code>resource</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_asynchronous_context_example">Asynchronous context example</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#async_hooks_before_asyncid"><code>before(asyncId)</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_after_asyncid"><code>after(asyncId)</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_destroy_asyncid"><code>destroy(asyncId)</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_promiseresolve_asyncid"><code>promiseResolve(asyncId)</code></a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#async_hooks_async_hooks_executionasyncid"><code>async_hooks.executionAsyncId()</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_async_hooks_triggerasyncid"><code>async_hooks.triggerAsyncId()</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#async_hooks_promise_execution_tracking">Promise execution tracking</a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_javascript_embedder_api">JavaScript Embedder API</a></span><ul>
<li><span class="stability_undefined"><a href="#async_hooks_class_asyncresource"><code>class AsyncResource()</code></a></span><ul>
<li><span class="stability_undefined"><a href="#async_hooks_asyncresource_type_options"><code>AsyncResource(type[, options])</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args"><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code></a></span></li>
<li><span class="stability_0"><a href="#async_hooks_asyncresource_emitbefore"><code>asyncResource.emitBefore()</code></a></span></li>
<li><span class="stability_0"><a href="#async_hooks_asyncresource_emitafter"><code>asyncResource.emitAfter()</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_asyncresource_emitdestroy"><code>asyncResource.emitDestroy()</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_asyncresource_asyncid"><code>asyncResource.asyncId()</code></a></span></li>
<li><span class="stability_undefined"><a href="#async_hooks_asyncresource_triggerasyncid"><code>asyncResource.triggerAsyncId()</code></a></span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#buffer_buffer">Buffer</a></span><ul>
<li><span class="stability_undefined"><a href="#buffer_buffer_from_buffer_alloc_and_buffer_allocunsafe"><code>Buffer.from()</code>, <code>Buffer.alloc()</code>, and <code>Buffer.allocUnsafe()</code></a></span><ul>
<li><span class="stability_undefined"><a href="#buffer_the_zero_fill_buffers_command_line_option">The <code>--zero-fill-buffers</code> command line option</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_what_makes_buffer_allocunsafe_and_buffer_allocunsafeslow_unsafe">What makes <code>Buffer.allocUnsafe()</code> and <code>Buffer.allocUnsafeSlow()</code> "unsafe"?</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#buffer_buffers_and_character_encodings">Buffers and Character Encodings</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buffers_and_typedarray">Buffers and TypedArray</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buffers_and_iteration">Buffers and iteration</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_buffer">Class: Buffer</a></span><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><span class="stability_undefined"><a href="#buffer_class_method_buffer_alloc_size_fill_encoding">Class Method: Buffer.alloc(size[, fill[, encoding]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_allocunsafe_size">Class Method: Buffer.allocUnsafe(size)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_allocunsafeslow_size">Class Method: Buffer.allocUnsafeSlow(size)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_bytelength_string_encoding">Class Method: Buffer.byteLength(string[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_compare_buf1_buf2">Class Method: Buffer.compare(buf1, buf2)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_concat_list_totallength">Class Method: Buffer.concat(list[, totalLength])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_from_array">Class Method: Buffer.from(array)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length">Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_from_buffer">Class Method: Buffer.from(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_from_string_encoding">Class Method: Buffer.from(string[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_from_object_offsetorencoding_length">Class Method: Buffer.from(object[, offsetOrEncoding[, length]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_isbuffer_obj">Class Method: Buffer.isBuffer(obj)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_isencoding_encoding">Class Method: Buffer.isEncoding(encoding)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_property_buffer_poolsize">Class Property: Buffer.poolSize</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_index">buf[index]</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_buffer">buf.buffer</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend">buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_copy_target_targetstart_sourcestart_sourceend">buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_entries">buf.entries()</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_equals_otherbuffer">buf.equals(otherBuffer)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_fill_value_offset_end_encoding">buf.fill(value[, offset[, end]][, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_includes_value_byteoffset_encoding">buf.includes(value[, byteOffset][, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_indexof_value_byteoffset_encoding">buf.indexOf(value[, byteOffset][, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_keys">buf.keys()</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_lastindexof_value_byteoffset_encoding">buf.lastIndexOf(value[, byteOffset][, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_length">buf.length</a></span></li>
<li><span class="stability_0"><a href="#buffer_buf_parent">buf.parent</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readdoublebe_offset_noassert">buf.readDoubleBE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readdoublele_offset_noassert">buf.readDoubleLE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readfloatbe_offset_noassert">buf.readFloatBE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readfloatle_offset_noassert">buf.readFloatLE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readint8_offset_noassert">buf.readInt8(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readint16be_offset_noassert">buf.readInt16BE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readint16le_offset_noassert">buf.readInt16LE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readint32be_offset_noassert">buf.readInt32BE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readint32le_offset_noassert">buf.readInt32LE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readintbe_offset_bytelength_noassert">buf.readIntBE(offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readintle_offset_bytelength_noassert">buf.readIntLE(offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuint8_offset_noassert">buf.readUInt8(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuint16be_offset_noassert">buf.readUInt16BE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuint16le_offset_noassert">buf.readUInt16LE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuint32be_offset_noassert">buf.readUInt32BE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuint32le_offset_noassert">buf.readUInt32LE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuintbe_offset_bytelength_noassert">buf.readUIntBE(offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuintle_offset_bytelength_noassert">buf.readUIntLE(offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_slice_start_end">buf.slice([start[, end]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_swap16">buf.swap16()</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_swap32">buf.swap32()</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_swap64">buf.swap64()</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_tojson">buf.toJSON()</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_tostring_encoding_start_end">buf.toString([encoding[, start[, end]]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_values">buf.values()</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_write_string_offset_length_encoding">buf.write(string[, offset[, length]][, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writedoublebe_value_offset_noassert">buf.writeDoubleBE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writedoublele_value_offset_noassert">buf.writeDoubleLE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writefloatbe_value_offset_noassert">buf.writeFloatBE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writefloatle_value_offset_noassert">buf.writeFloatLE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeint8_value_offset_noassert">buf.writeInt8(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeint16be_value_offset_noassert">buf.writeInt16BE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeint16le_value_offset_noassert">buf.writeInt16LE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeint32be_value_offset_noassert">buf.writeInt32BE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeint32le_value_offset_noassert">buf.writeInt32LE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeintbe_value_offset_bytelength_noassert">buf.writeIntBE(value, offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeintle_value_offset_bytelength_noassert">buf.writeIntLE(value, offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuint8_value_offset_noassert">buf.writeUInt8(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuint16be_value_offset_noassert">buf.writeUInt16BE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuint16le_value_offset_noassert">buf.writeUInt16LE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuint32be_value_offset_noassert">buf.writeUInt32BE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuint32le_value_offset_noassert">buf.writeUInt32LE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuintbe_value_offset_bytelength_noassert">buf.writeUIntBE(value, offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuintle_value_offset_bytelength_noassert">buf.writeUIntLE(value, offset, byteLength[, noAssert])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#buffer_buffer_inspect_max_bytes">buffer.INSPECT_MAX_BYTES</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buffer_kmaxlength">buffer.kMaxLength</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buffer_transcode_source_fromenc_toenc">buffer.transcode(source, fromEnc, toEnc)</a></span></li>
<li><span class="stability_0"><a href="#buffer_class_slowbuffer">Class: SlowBuffer</a></span><ul>
<li><span class="stability_0"><a href="#buffer_new_slowbuffer_size">new SlowBuffer(size)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#buffer_buffer_constants">Buffer Constants</a></span><ul>
<li><span class="stability_undefined"><a href="#buffer_buffer_constants_max_length">buffer.constants.MAX_LENGTH</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buffer_constants_max_string_length">buffer.constants.MAX_STRING_LENGTH</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#addons_c_addons">C++ Addons</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_hello_world">Hello world</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_building">Building</a></span></li>
<li><span class="stability_undefined"><a href="#addons_linking_to_node_js_own_dependencies">Linking to Node.js' own dependencies</a></span></li>
<li><span class="stability_undefined"><a href="#addons_loading_addons_using_require">Loading Addons using require()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#addons_native_abstractions_for_node_js">Native Abstractions for Node.js</a></span></li>
<li><span class="stability_1"><a href="#addons_n_api">N-API</a></span></li>
<li><span class="stability_undefined"><a href="#addons_addon_examples">Addon examples</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_function_arguments">Function arguments</a></span></li>
<li><span class="stability_undefined"><a href="#addons_callbacks">Callbacks</a></span></li>
<li><span class="stability_undefined"><a href="#addons_object_factory">Object factory</a></span></li>
<li><span class="stability_undefined"><a href="#addons_function_factory">Function factory</a></span></li>
<li><span class="stability_undefined"><a href="#addons_wrapping_c_objects">Wrapping C++ objects</a></span></li>
<li><span class="stability_undefined"><a href="#addons_factory_of_wrapped_objects">Factory of wrapped objects</a></span></li>
<li><span class="stability_undefined"><a href="#addons_passing_wrapped_objects_around">Passing wrapped objects around</a></span></li>
<li><span class="stability_undefined"><a href="#addons_atexit_hooks">AtExit hooks</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_void_atexit_callback_args">void AtExit(callback, args)</a></span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#n_api_n_api">N-API</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_basic_n_api_data_types">Basic N-API Data Types</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_status">napi_status</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_extended_error_info">napi_extended_error_info</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_env">napi_env</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_value">napi_value</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_n_api_memory_management_types">N-API Memory Management types</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_handle_scope">napi_handle_scope</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_escapable_handle_scope">napi_escapable_handle_scope</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_ref">napi_ref</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_n_api_callback_types">N-API Callback types</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_callback_info">napi_callback_info</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_callback">napi_callback</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_finalize">napi_finalize</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_async_execute_callback">napi_async_execute_callback</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_async_complete_callback">napi_async_complete_callback</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_error_handling">Error Handling</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_return_values">Return values</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_get_last_error_info">napi_get_last_error_info</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_exceptions">Exceptions</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_throw">napi_throw</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_throw_error">napi_throw_error</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_throw_type_error">napi_throw_type_error</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_throw_range_error">napi_throw_range_error</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_is_error">napi_is_error</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_error">napi_create_error</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_type_error">napi_create_type_error</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_range_error">napi_create_range_error</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_and_clear_last_exception">napi_get_and_clear_last_exception</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_is_exception_pending">napi_is_exception_pending</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_fatal_exception">napi_fatal_exception</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_fatal_errors">Fatal Errors</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_fatal_error">napi_fatal_error</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_object_lifetime_management">Object Lifetime management</a></span><ul>
<li><span class="stability_undefined"><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></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_open_handle_scope">napi_open_handle_scope</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_close_handle_scope">napi_close_handle_scope</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_open_escapable_handle_scope">napi_open_escapable_handle_scope</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_close_escapable_handle_scope">napi_close_escapable_handle_scope</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_escape_handle">napi_escape_handle</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><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></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_create_reference">napi_create_reference</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_delete_reference">napi_delete_reference</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_reference_ref">napi_reference_ref</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_reference_unref">napi_reference_unref</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_reference_value">napi_get_reference_value</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_module_registration">Module registration</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_working_with_javascript_values">Working with JavaScript Values</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_enum_types">Enum types</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_valuetype">napi_valuetype</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_typedarray_type">napi_typedarray_type</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_object_creation_functions">Object Creation Functions</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_create_array">napi_create_array</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_array_with_length">napi_create_array_with_length</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_arraybuffer">napi_create_arraybuffer</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_buffer">napi_create_buffer</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_buffer_copy">napi_create_buffer_copy</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_external">napi_create_external</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_external_arraybuffer">napi_create_external_arraybuffer</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_external_buffer">napi_create_external_buffer</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_function">napi_create_function</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_object">napi_create_object</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_symbol">napi_create_symbol</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_typedarray">napi_create_typedarray</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_dataview">napi_create_dataview</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_functions_to_convert_from_c_types_to_n_api">Functions to convert from C types to N-API</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_create_int32">napi_create_int32</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_uint32">napi_create_uint32</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_int64">napi_create_int64</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_double">napi_create_double</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_string_latin1">napi_create_string_latin1</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_string_utf16">napi_create_string_utf16</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_string_utf8">napi_create_string_utf8</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_functions_to_convert_from_n_api_to_c_types">Functions to convert from N-API to C types</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_get_array_length">napi_get_array_length</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_arraybuffer_info">napi_get_arraybuffer_info</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_buffer_info">napi_get_buffer_info</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_prototype">napi_get_prototype</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_typedarray_info">napi_get_typedarray_info</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_dataview_info">napi_get_dataview_info</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_value_bool">napi_get_value_bool</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_value_double">napi_get_value_double</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_value_external">napi_get_value_external</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_value_int32">napi_get_value_int32</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_value_int64">napi_get_value_int64</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_value_string_latin1">napi_get_value_string_latin1</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_value_string_utf8">napi_get_value_string_utf8</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_value_string_utf16">napi_get_value_string_utf16</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_value_uint32">napi_get_value_uint32</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_functions_to_get_global_instances">Functions to get global instances</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_get_boolean">napi_get_boolean</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_global">napi_get_global</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_null">napi_get_null</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_undefined">napi_get_undefined</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_working_with_javascript_values_abstract_operations">Working with JavaScript Values - Abstract Operations</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_coerce_to_bool">napi_coerce_to_bool</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_coerce_to_number">napi_coerce_to_number</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_coerce_to_object">napi_coerce_to_object</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_coerce_to_string">napi_coerce_to_string</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_typeof">napi_typeof</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_instanceof">napi_instanceof</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_is_array">napi_is_array</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_is_arraybuffer">napi_is_arraybuffer</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_is_buffer">napi_is_buffer</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_is_error_1">napi_is_error</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_is_typedarray">napi_is_typedarray</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_is_dataview">napi_is_dataview</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_strict_equals">napi_strict_equals</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_working_with_javascript_properties">Working with JavaScript Properties</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_structures">Structures</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_property_attributes">napi_property_attributes</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_property_descriptor">napi_property_descriptor</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_functions">Functions</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_get_property_names">napi_get_property_names</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_set_property">napi_set_property</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_property">napi_get_property</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_has_property">napi_has_property</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_delete_property">napi_delete_property</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_has_own_property">napi_has_own_property</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_set_named_property">napi_set_named_property</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_named_property">napi_get_named_property</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_has_named_property">napi_has_named_property</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_set_element">napi_set_element</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_element">napi_get_element</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_has_element">napi_has_element</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_delete_element">napi_delete_element</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_define_properties">napi_define_properties</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_working_with_javascript_functions">Working with JavaScript Functions</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_call_function">napi_call_function</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_create_function_1">napi_create_function</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_cb_info">napi_get_cb_info</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_new_target">napi_get_new_target</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_new_instance">napi_new_instance</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_object_wrap">Object Wrap</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_define_class">napi_define_class</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_wrap">napi_wrap</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_unwrap">napi_unwrap</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_remove_wrap">napi_remove_wrap</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_simple_asynchronous_operations">Simple Asynchronous Operations</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_create_async_work">napi_create_async_work</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_delete_async_work">napi_delete_async_work</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_queue_async_work">napi_queue_async_work</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_cancel_async_work">napi_cancel_async_work</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_custom_asynchronous_operations">Custom Asynchronous Operations</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_async_init">napi_async_init</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_async_destroy">napi_async_destroy</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_make_callback">napi_make_callback</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_open_callback_scope"><em>napi_open_callback_scope</em></a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_close_callback_scope"><em>napi_close_callback_scope</em></a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_version_management">Version Management</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_get_node_version">napi_get_node_version</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_get_version">napi_get_version</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_memory_management">Memory Management</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_adjust_external_memory">napi_adjust_external_memory</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_promises">Promises</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_create_promise">napi_create_promise</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_resolve_deferred">napi_resolve_deferred</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_reject_deferred">napi_reject_deferred</a></span></li>
<li><span class="stability_undefined"><a href="#n_api_napi_is_promise">napi_is_promise</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_script_execution">Script execution</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_run_script">napi_run_script</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#n_api_libuv_event_loop">libuv event loop</a></span><ul>
<li><span class="stability_undefined"><a href="#n_api_napi_get_uv_event_loop">napi_get_uv_event_loop</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#child_process_child_process">Child Process</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_asynchronous_process_creation">Asynchronous Process Creation</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_spawning_bat_and_cmd_files_on_windows">Spawning <code>.bat</code> and <code>.cmd</code> files on Windows</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_exec_command_options_callback">child_process.exec(command[, options][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_execfile_file_args_options_callback">child_process.execFile(file[, args][, options][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_fork_modulepath_args_options">child_process.fork(modulePath[, args][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_spawn_command_args_options">child_process.spawn(command[, args][, options])</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_options_detached">options.detached</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_options_stdio">options.stdio</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#child_process_synchronous_process_creation">Synchronous Process Creation</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_child_process_execfilesync_file_args_options">child_process.execFileSync(file[, args][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_execsync_command_options">child_process.execSync(command[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_spawnsync_command_args_options">child_process.spawnSync(command[, args][, options])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#child_process_class_childprocess">Class: ChildProcess</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_disconnect">Event: 'disconnect'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_exit">Event: 'exit'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_message">Event: 'message'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_subprocess_channel">subprocess.channel</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_subprocess_connected">subprocess.connected</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_subprocess_disconnect">subprocess.disconnect()</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_subprocess_kill_signal">subprocess.kill([signal])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_subprocess_killed">subprocess.killed</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_subprocess_pid">subprocess.pid</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_subprocess_send_message_sendhandle_options_callback">subprocess.send(message[, sendHandle[, options]][, callback])</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_example_sending_a_server_object">Example: sending a server object</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_example_sending_a_socket_object">Example: sending a socket object</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#child_process_subprocess_stderr">subprocess.stderr</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_subprocess_stdin">subprocess.stdin</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_subprocess_stdio">subprocess.stdio</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_subprocess_stdout">subprocess.stdout</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_shell_requirements">Shell Requirements</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_default_windows_shell">Default Windows Shell</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#cluster_cluster">Cluster</a></span><ul>
<li><span class="stability_undefined"><a href="#cluster_how_it_works">How It Works</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_class_worker">Class: Worker</a></span><ul>
<li><span class="stability_undefined"><a href="#cluster_event_disconnect">Event: 'disconnect'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_exit">Event: 'exit'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_listening">Event: 'listening'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_message">Event: 'message'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_online">Event: 'online'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_disconnect">worker.disconnect()</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_exitedafterdisconnect">worker.exitedAfterDisconnect</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_id">worker.id</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_isconnected">worker.isConnected()</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_isdead">worker.isDead()</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_kill_signal_sigterm">worker.kill([signal='SIGTERM'])</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_process">worker.process</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_send_message_sendhandle_callback">worker.send(message[, sendHandle][, callback])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#cluster_event_disconnect_1">Event: 'disconnect'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_exit_1">Event: 'exit'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_fork">Event: 'fork'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_listening_1">Event: 'listening'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_message_1">Event: 'message'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_online_1">Event: 'online'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_setup">Event: 'setup'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_disconnect_callback">cluster.disconnect([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_fork_env">cluster.fork([env])</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_ismaster">cluster.isMaster</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_isworker">cluster.isWorker</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_schedulingpolicy">cluster.schedulingPolicy</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_settings">cluster.settings</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_setupmaster_settings">cluster.setupMaster([settings])</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_worker">cluster.worker</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_workers">cluster.workers</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#cli_command_line_options">Command Line Options</a></span><ul>
<li><span class="stability_undefined"><a href="#cli_synopsis">Synopsis</a></span></li>
<li><span class="stability_undefined"><a href="#cli_options">Options</a></span><ul>
<li><span class="stability_undefined"><a href="#cli_v_version"><code>-v</code>, <code>--version</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_h_help"><code>-h</code>, <code>--help</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_e_eval_script"><code>-e</code>, <code>--eval "script"</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_p_print_script"><code>-p</code>, <code>--print "script"</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_c_check"><code>-c</code>, <code>--check</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_i_interactive"><code>-i</code>, <code>--interactive</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_r_require_module"><code>-r</code>, <code>--require module</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_inspect_host_port"><code>--inspect[=[host:]port]</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_inspect_brk_host_port"><code>--inspect-brk[=[host:]port]</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_inspect_port_host_port"><code>--inspect-port=[host:]port</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_no_deprecation"><code>--no-deprecation</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_trace_deprecation"><code>--trace-deprecation</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_throw_deprecation"><code>--throw-deprecation</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_no_warnings"><code>--no-warnings</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_abort_on_uncaught_exception"><code>--abort-on-uncaught-exception</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_trace_warnings"><code>--trace-warnings</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_redirect_warnings_file"><code>--redirect-warnings=file</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_trace_sync_io"><code>--trace-sync-io</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_no_force_async_hooks_checks"><code>--no-force-async-hooks-checks</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_trace_events_enabled"><code>--trace-events-enabled</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_trace_event_categories"><code>--trace-event-categories</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_trace_event_file_pattern"><code>--trace-event-file-pattern</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_zero_fill_buffers"><code>--zero-fill-buffers</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_preserve_symlinks"><code>--preserve-symlinks</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_track_heap_objects"><code>--track-heap-objects</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_prof_process"><code>--prof-process</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_v8_options"><code>--v8-options</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_tls_cipher_list_list"><code>--tls-cipher-list=list</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_enable_fips"><code>--enable-fips</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_force_fips"><code>--force-fips</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_openssl_config_file"><code>--openssl-config=file</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_use_openssl_ca_use_bundled_ca"><code>--use-openssl-ca</code>, <code>--use-bundled-ca</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_icu_data_dir_file"><code>--icu-data-dir=file</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli"><code>-</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_1"><code>--</code></a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#cli_environment_variables">Environment Variables</a></span><ul>
<li><span class="stability_undefined"><a href="#cli_node_debug_module"><code>NODE_DEBUG=module[,…]</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_path_path"><code>NODE_PATH=path[:…]</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_disable_colors_1"><code>NODE_DISABLE_COLORS=1</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_icu_data_file"><code>NODE_ICU_DATA=file</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_no_warnings_1"><code>NODE_NO_WARNINGS=1</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_options_options"><code>NODE_OPTIONS=options...</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_pending_deprecation_1"><code>NODE_PENDING_DEPRECATION=1</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_preserve_symlinks_1"><code>NODE_PRESERVE_SYMLINKS=1</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_repl_history_file"><code>NODE_REPL_HISTORY=file</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_extra_ca_certs_file"><code>NODE_EXTRA_CA_CERTS=file</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_openssl_conf_file"><code>OPENSSL_CONF=file</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_ssl_cert_dir_dir"><code>SSL_CERT_DIR=dir</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_ssl_cert_file_file"><code>SSL_CERT_FILE=file</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_redirect_warnings_file"><code>NODE_REDIRECT_WARNINGS=file</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE=size</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#console_console">Console</a></span><ul>
<li><span class="stability_undefined"><a href="#console_class_console">Class: Console</a></span><ul>
<li><span class="stability_undefined"><a href="#console_new_console_stdout_stderr">new Console(stdout[, stderr])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_assert_value_message_args">console.assert(value[, message][, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_clear">console.clear()</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_count_label">console.count([label])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_countreset_label_default">console.countReset([label='default'])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_debug_data_args">console.debug(data[, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_dir_obj_options">console.dir(obj[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_dirxml_data">console.dirxml(...data)</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_error_data_args">console.error([data][, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_group_label">console.group([...label])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_groupcollapsed">console.groupCollapsed()</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_groupend">console.groupEnd()</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_info_data_args">console.info([data][, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_log_data_args">console.log([data][, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_time_label">console.time(label)</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_timeend_label">console.timeEnd(label)</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_trace_message_args">console.trace([message][, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_warn_data_args">console.warn([data][, ...args])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#console_inspector_only_methods">Inspector only methods</a></span><ul>
<li><span class="stability_undefined"><a href="#console_console_marktimeline_label">console.markTimeline(label)</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_profile_label">console.profile([label])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_profileend">console.profileEnd()</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_table_array_columns">console.table(array[, columns])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_timestamp_label">console.timeStamp([label])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_timeline_label">console.timeline([label])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_timelineend_label">console.timelineEnd([label])</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#crypto_crypto">Crypto</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_determining_if_crypto_support_is_unavailable">Determining if crypto support is unavailable</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_class_certificate">Class: Certificate</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_certificate_exportchallenge_spkac">Certificate.exportChallenge(spkac)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_certificate_exportpublickey_spkac_encoding">Certificate.exportPublicKey(spkac[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_certificate_verifyspkac_spkac">Certificate.verifySpkac(spkac)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_legacy_api">Legacy API</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_new_crypto_certificate">new crypto.Certificate()</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_certificate_exportchallenge_spkac_1">certificate.exportChallenge(spkac)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_certificate_exportpublickey_spkac">certificate.exportPublicKey(spkac)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_certificate_verifyspkac_spkac_1">certificate.verifySpkac(spkac)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_cipher">Class: Cipher</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_cipher_final_outputencoding">cipher.final([outputEncoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_cipher_setaad_buffer">cipher.setAAD(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_cipher_getauthtag">cipher.getAuthTag()</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_cipher_setautopadding_autopadding">cipher.setAutoPadding([autoPadding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_cipher_update_data_inputencoding_outputencoding">cipher.update(data[, inputEncoding][, outputEncoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_decipher">Class: Decipher</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_decipher_final_outputencoding">decipher.final([outputEncoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_decipher_setaad_buffer">decipher.setAAD(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_decipher_setauthtag_buffer">decipher.setAuthTag(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_decipher_setautopadding_autopadding">decipher.setAutoPadding([autoPadding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_decipher_update_data_inputencoding_outputencoding">decipher.update(data[, inputEncoding][, outputEncoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_diffiehellman">Class: DiffieHellman</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_computesecret_otherpublickey_inputencoding_outputencoding">diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_generatekeys_encoding">diffieHellman.generateKeys([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_getgenerator_encoding">diffieHellman.getGenerator([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_getprime_encoding">diffieHellman.getPrime([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_getprivatekey_encoding">diffieHellman.getPrivateKey([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_getpublickey_encoding">diffieHellman.getPublicKey([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_setprivatekey_privatekey_encoding">diffieHellman.setPrivateKey(privateKey[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_setpublickey_publickey_encoding">diffieHellman.setPublicKey(publicKey[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_verifyerror">diffieHellman.verifyError</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_ecdh">Class: ECDH</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_ecdh_computesecret_otherpublickey_inputencoding_outputencoding">ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_ecdh_generatekeys_encoding_format">ecdh.generateKeys([encoding[, format]])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_ecdh_getprivatekey_encoding">ecdh.getPrivateKey([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_ecdh_getpublickey_encoding_format">ecdh.getPublicKey([encoding][, format])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_ecdh_setprivatekey_privatekey_encoding">ecdh.setPrivateKey(privateKey[, encoding])</a></span></li>
<li><span class="stability_0"><a href="#crypto_ecdh_setpublickey_publickey_encoding">ecdh.setPublicKey(publicKey[, encoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_hash">Class: Hash</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_hash_digest_encoding">hash.digest([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_hash_update_data_inputencoding">hash.update(data[, inputEncoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_hmac">Class: Hmac</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_hmac_digest_encoding">hmac.digest([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_hmac_update_data_inputencoding">hmac.update(data[, inputEncoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_sign">Class: Sign</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_sign_sign_privatekey_outputformat">sign.sign(privateKey[, outputFormat])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_sign_update_data_inputencoding">sign.update(data[, inputEncoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_verify">Class: Verify</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_verify_update_data_inputencoding">verify.update(data[, inputEncoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_verify_verify_object_signature_signatureformat">verify.verify(object, signature[, signatureFormat])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_crypto_module_methods_and_properties"><code>crypto</code> module methods and properties</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_crypto_constants">crypto.constants</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_default_encoding">crypto.DEFAULT_ENCODING</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_fips">crypto.fips</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createcipher_algorithm_password_options">crypto.createCipher(algorithm, password[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createcipheriv_algorithm_key_iv_options">crypto.createCipheriv(algorithm, key, iv[, options])</a></span></li>
<li><span class="stability_0"><a href="#crypto_crypto_createcredentials_details">crypto.createCredentials(details)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createdecipher_algorithm_password_options">crypto.createDecipher(algorithm, password[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options">crypto.createDecipheriv(algorithm, key, iv[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding">crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_creatediffiehellman_primelength_generator">crypto.createDiffieHellman(primeLength[, generator])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createecdh_curvename">crypto.createECDH(curveName)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createhash_algorithm_options">crypto.createHash(algorithm[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createhmac_algorithm_key_options">crypto.createHmac(algorithm, key[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createsign_algorithm_options">crypto.createSign(algorithm[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createverify_algorithm_options">crypto.createVerify(algorithm[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_getciphers">crypto.getCiphers()</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_getcurves">crypto.getCurves()</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_getdiffiehellman_groupname">crypto.getDiffieHellman(groupName)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_gethashes">crypto.getHashes()</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback">crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest">crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_privatedecrypt_privatekey_buffer">crypto.privateDecrypt(privateKey, buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_privateencrypt_privatekey_buffer">crypto.privateEncrypt(privateKey, buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_publicdecrypt_key_buffer">crypto.publicDecrypt(key, buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_publicencrypt_key_buffer">crypto.publicEncrypt(key, buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_randombytes_size_callback">crypto.randomBytes(size[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_randomfillsync_buffer_offset_size">crypto.randomFillSync(buffer[, offset][, size])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_randomfill_buffer_offset_size_callback">crypto.randomFill(buffer[, offset][, size], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_setengine_engine_flags">crypto.setEngine(engine[, flags])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_timingsafeequal_a_b">crypto.timingSafeEqual(a, b)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_notes">Notes</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_legacy_streams_api_pre_node_js_v0_10">Legacy Streams API (pre Node.js v0.10)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_recent_ecdh_changes">Recent ECDH Changes</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_support_for_weak_or_compromised_algorithms">Support for weak or compromised algorithms</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_crypto_constants_1">Crypto Constants</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_openssl_options">OpenSSL Options</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_openssl_engine_constants">OpenSSL Engine Constants</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_other_openssl_constants">Other OpenSSL Constants</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_node_js_crypto_constants">Node.js Crypto Constants</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#debugger_debugger">Debugger</a></span><ul>
<li><span class="stability_undefined"><a href="#debugger_watchers">Watchers</a></span></li>
<li><span class="stability_undefined"><a href="#debugger_command_reference">Command reference</a></span><ul>
<li><span class="stability_undefined"><a href="#debugger_stepping">Stepping</a></span></li>
<li><span class="stability_undefined"><a href="#debugger_breakpoints">Breakpoints</a></span></li>
<li><span class="stability_undefined"><a href="#debugger_information">Information</a></span></li>
<li><span class="stability_undefined"><a href="#debugger_execution_control">Execution control</a></span></li>
<li><span class="stability_undefined"><a href="#debugger_various">Various</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#debugger_advanced_usage">Advanced Usage</a></span><ul>
<li><span class="stability_undefined"><a href="#debugger_v8_inspector_integration_for_node_js">V8 Inspector Integration for Node.js</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#deprecations_deprecated_apis">Deprecated APIs</a></span><ul>
<li><span class="stability_undefined"><a href="#deprecations_un_deprecation">Un-deprecation</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_list_of_deprecated_apis">List of Deprecated APIs</a></span><ul>
<li><span class="stability_undefined"><a href="#deprecations_dep0001_http_outgoingmessage_prototype_flush">DEP0001: http.OutgoingMessage.prototype.flush</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0002_require_linklist">DEP0002: require('_linklist')</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0003_writablestate_buffer">DEP0003: _writableState.buffer</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0004_cryptostream_prototype_readystate">DEP0004: CryptoStream.prototype.readyState</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0005_buffer_constructor">DEP0005: Buffer() constructor</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0006_child_process_options_customfds">DEP0006: child_process options.customFds</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0007_replace_cluster_worker_suicide_with_worker_exitedafterdisconnect">DEP0007: Replace cluster worker.suicide with worker.exitedAfterDisconnect</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0008_require_constants">DEP0008: require('constants')</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0009_crypto_pbkdf2_without_digest">DEP0009: crypto.pbkdf2 without digest</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0010_crypto_createcredentials">DEP0010: crypto.createCredentials</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0011_crypto_credentials">DEP0011: crypto.Credentials</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0012_domain_dispose">DEP0012: Domain.dispose</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0013_fs_asynchronous_function_without_callback">DEP0013: fs asynchronous function without callback</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0014_fs_read_legacy_string_interface">DEP0014: fs.read legacy String interface</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0015_fs_readsync_legacy_string_interface">DEP0015: fs.readSync legacy String interface</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0016_global_root">DEP0016: GLOBAL/root</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0017_intl_v8breakiterator">DEP0017: Intl.v8BreakIterator</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0018_unhandled_promise_rejections">DEP0018: Unhandled promise rejections</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0019_require_resolved_outside_directory">DEP0019: require('.') resolved outside directory</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0020_server_connections">DEP0020: Server.connections</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0021_server_listenfd">DEP0021: Server.listenFD</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0022_os_tmpdir">DEP0022: os.tmpDir()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0023_os_getnetworkinterfaces">DEP0023: os.getNetworkInterfaces()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0024_replserver_prototype_converttocontext">DEP0024: REPLServer.prototype.convertToContext()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0025_require_sys">DEP0025: require('sys')</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0026_util_print">DEP0026: util.print()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0027_util_puts">DEP0027: util.puts()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0028_util_debug">DEP0028: util.debug()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0029_util_error">DEP0029: util.error()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0030_slowbuffer">DEP0030: SlowBuffer</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0031_ecdh_setpublickey">DEP0031: ecdh.setPublicKey()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0032_domain_module">DEP0032: domain module</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0033_eventemitter_listenercount">DEP0033: EventEmitter.listenerCount()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0034_fs_exists_path_callback">DEP0034: fs.exists(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0035_fs_lchmod_path_mode_callback">DEP0035: fs.lchmod(path, mode, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0036_fs_lchmodsync_path_mode">DEP0036: fs.lchmodSync(path, mode)</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0037_fs_lchown_path_uid_gid_callback">DEP0037: fs.lchown(path, uid, gid, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0038_fs_lchownsync_path_uid_gid">DEP0038: fs.lchownSync(path, uid, gid)</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0039_require_extensions">DEP0039: require.extensions</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0040_punycode_module">DEP0040: punycode module</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0041_node_repl_history_file_environment_variable">DEP0041: NODE_REPL_HISTORY_FILE environment variable</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0042_tls_cryptostream">DEP0042: tls.CryptoStream</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0043_tls_securepair">DEP0043: tls.SecurePair</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0044_util_isarray">DEP0044: util.isArray()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0045_util_isboolean">DEP0045: util.isBoolean()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0046_util_isbuffer">DEP0046: util.isBuffer()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0047_util_isdate">DEP0047: util.isDate()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0048_util_iserror">DEP0048: util.isError()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0049_util_isfunction">DEP0049: util.isFunction()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0050_util_isnull">DEP0050: util.isNull()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0051_util_isnullorundefined">DEP0051: util.isNullOrUndefined()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0052_util_isnumber">DEP0052: util.isNumber()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0053_util_isobject">DEP0053 util.isObject()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0054_util_isprimitive">DEP0054: util.isPrimitive()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0055_util_isregexp">DEP0055: util.isRegExp()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0056_util_isstring">DEP0056: util.isString()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0057_util_issymbol">DEP0057: util.isSymbol()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0058_util_isundefined">DEP0058: util.isUndefined()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0059_util_log">DEP0059: util.log()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0060_util_extend">DEP0060: util._extend()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0061_fs_syncwritestream">DEP0061: fs.SyncWriteStream</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0062_node_debug">DEP0062: node --debug</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0063_serverresponse_prototype_writeheader">DEP0063: ServerResponse.prototype.writeHeader()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0064_tls_createsecurepair">DEP0064: tls.createSecurePair()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0065_repl_repl_mode_magic_and_node_repl_mode_magic">DEP0065: repl.REPL_MODE_MAGIC and NODE_REPL_MODE=magic</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0066_outgoingmessage_headers_outgoingmessage_headernames">DEP0066: outgoingMessage._headers, outgoingMessage._headerNames</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0067_outgoingmessage_prototype_renderheaders">DEP0067: OutgoingMessage.prototype._renderHeaders</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0068_node_debug">DEP0068: node debug</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0069_vm_runindebugcontext_string">DEP0069: vm.runInDebugContext(string)</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0070_async_hooks_currentid">DEP0070: async_hooks.currentId()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0071_async_hooks_triggerid">DEP0071: async_hooks.triggerId()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0072_async_hooks_asyncresource_triggerid">DEP0072: async_hooks.AsyncResource.triggerId()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0073_several_internal_properties_of_net_server">DEP0073: Several internal properties of net.Server</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0074_replserver_bufferedcommand">DEP0074: REPLServer.bufferedCommand</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0075_replserver_parsereplkeyword">DEP0075: REPLServer.parseREPLKeyword()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0076_tls_parsecertstring">DEP0076: tls.parseCertString()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0077_module_debug">DEP0077: Module._debug()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0078_replserver_turnoffeditormode">DEP0078: REPLServer.turnOffEditorMode()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0079_custom_inspection_function_on_objects_via_inspect">DEP0079: Custom inspection function on Objects via .inspect()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0080_path_makelong">DEP0080: path._makeLong()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0081_fs_truncate_using_a_file_descriptor">DEP0081: fs.truncate() using a file descriptor</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0082_replserver_prototype_memory">DEP0082: REPLServer.prototype.memory()</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0083_disabling_ecdh_by_setting_ecdhcurve_to_false">DEP0083: Disabling ECDH by setting ecdhCurve to false</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0085_asynchooks_sensitive_api">DEP0085: AsyncHooks Sensitive API</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0086_remove_runinasyncidscope">DEP0086: Remove runInAsyncIdScope</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0089_require_assert">DEP0089: require('assert')</a></span></li>
<li><span class="stability_undefined"><a href="#deprecations_dep0098_asynchooks_embedder_asyncresource_emit_span_class_type_lt_before_after_gt_span_apis">DEP0098: AsyncHooks Embedder AsyncResource.emit<span class="type"><Before,After></span> APIs</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#dns_dns">DNS</a></span><ul>
<li><span class="stability_undefined"><a href="#dns_class_dns_resolver">Class dns.Resolver</a></span><ul>
<li><span class="stability_undefined"><a href="#dns_resolver_cancel">resolver.cancel()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#dns_dns_getservers">dns.getServers()</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_lookup_hostname_options_callback">dns.lookup(hostname[, options], callback)</a></span><ul>
<li><span class="stability_undefined"><a href="#dns_supported_getaddrinfo_flags">Supported getaddrinfo flags</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#dns_dns_lookupservice_address_port_callback">dns.lookupService(address, port, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolve_hostname_rrtype_callback">dns.resolve(hostname[, rrtype], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolve4_hostname_options_callback">dns.resolve4(hostname[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolve6_hostname_options_callback">dns.resolve6(hostname[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvecname_hostname_callback">dns.resolveCname(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvemx_hostname_callback">dns.resolveMx(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvenaptr_hostname_callback">dns.resolveNaptr(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvens_hostname_callback">dns.resolveNs(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolveptr_hostname_callback">dns.resolvePtr(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvesoa_hostname_callback">dns.resolveSoa(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvesrv_hostname_callback">dns.resolveSrv(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvetxt_hostname_callback">dns.resolveTxt(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolveany_hostname_callback">dns.resolveAny(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_reverse_ip_callback">dns.reverse(ip, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_setservers_servers">dns.setServers(servers)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_error_codes">Error codes</a></span></li>
<li><span class="stability_undefined"><a href="#dns_implementation_considerations">Implementation considerations</a></span><ul>
<li><span class="stability_undefined"><a href="#dns_dns_lookup"><code>dns.lookup()</code></a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolve_dns_resolve_and_dns_reverse"><code>dns.resolve()</code>, <code>dns.resolve*()</code> and <code>dns.reverse()</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#domain_domain">Domain</a></span><ul>
<li><span class="stability_undefined"><a href="#domain_warning_don_t_ignore_errors">Warning: Don't Ignore Errors!</a></span></li>
<li><span class="stability_undefined"><a href="#domain_additions_to_error_objects">Additions to Error objects</a></span></li>
<li><span class="stability_undefined"><a href="#domain_implicit_binding">Implicit Binding</a></span></li>
<li><span class="stability_undefined"><a href="#domain_explicit_binding">Explicit Binding</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_create">domain.create()</a></span></li>
<li><span class="stability_undefined"><a href="#domain_class_domain">Class: Domain</a></span><ul>
<li><span class="stability_undefined"><a href="#domain_domain_members">domain.members</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_add_emitter">domain.add(emitter)</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_bind_callback">domain.bind(callback)</a></span><ul>
<li><span class="stability_undefined"><a href="#domain_example">Example</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#domain_domain_enter">domain.enter()</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_exit">domain.exit()</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_intercept_callback">domain.intercept(callback)</a></span><ul>
<li><span class="stability_undefined"><a href="#domain_example_1">Example</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#domain_domain_remove_emitter">domain.remove(emitter)</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_run_fn_args">domain.run(fn[, ...args])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#domain_domains_and_promises">Domains and Promises</a></span></li>
</ul>
</li>
<li><span class="stability_1"><a href="#esm_ecmascript_modules">ECMAScript Modules</a></span><ul>
<li><span class="stability_undefined"><a href="#esm_enabling">Enabling</a></span></li>
<li><span class="stability_undefined"><a href="#esm_features">Features</a></span><ul>
<li><span class="stability_undefined"><a href="#esm_supported">Supported</a></span></li>
<li><span class="stability_undefined"><a href="#esm_unsupported">Unsupported</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#esm_notable_differences_between_import_and_require">Notable differences between <code>import</code> and <code>require</code></a></span><ul>
<li><span class="stability_undefined"><a href="#esm_no_node_path">No NODE_PATH</a></span></li>
<li><span class="stability_undefined"><a href="#esm_no_require_extensions">No <code>require.extensions</code></a></span></li>
<li><span class="stability_undefined"><a href="#esm_no_require_cache">No <code>require.cache</code></a></span></li>
<li><span class="stability_undefined"><a href="#esm_url_based_paths">URL based paths</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#esm_interop_with_existing_modules">Interop with existing modules</a></span></li>
<li><span class="stability_undefined"><a href="#esm_loader_hooks">Loader hooks</a></span><ul>
<li><span class="stability_undefined"><a href="#esm_resolve_hook">Resolve hook</a></span></li>
<li><span class="stability_undefined"><a href="#esm_dynamic_instantiate_hook">Dynamic instantiate hook</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#errors_errors">Errors</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_error_propagation_and_interception">Error Propagation and Interception</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_error_first_callbacks">Error-first callbacks</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#errors_class_error">Class: Error</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_new_error_message">new Error(message)</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_capturestacktrace_targetobject_constructoropt">Error.captureStackTrace(targetObject[, constructorOpt])</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_stacktracelimit">Error.stackTraceLimit</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_code">error.code</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_message">error.message</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_stack">error.stack</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#errors_class_assertionerror">Class: AssertionError</a></span></li>
<li><span class="stability_undefined"><a href="#errors_class_rangeerror">Class: RangeError</a></span></li>
<li><span class="stability_undefined"><a href="#errors_class_referenceerror">Class: ReferenceError</a></span></li>
<li><span class="stability_undefined"><a href="#errors_class_syntaxerror">Class: SyntaxError</a></span></li>
<li><span class="stability_undefined"><a href="#errors_class_typeerror">Class: TypeError</a></span></li>
<li><span class="stability_undefined"><a href="#errors_exceptions_vs_errors">Exceptions vs. Errors</a></span></li>
<li><span class="stability_undefined"><a href="#errors_system_errors">System Errors</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_class_system_error">Class: System Error</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_error_code_1">error.code</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_errno">error.errno</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_syscall">error.syscall</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_path">error.path</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_address">error.address</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_port">error.port</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#errors_common_system_errors">Common System Errors</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#errors_node_js_error_codes">Node.js Error Codes</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_err_arg_not_iterable">ERR_ARG_NOT_ITERABLE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_assertion">ERR_ASSERTION</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_async_callback">ERR_ASYNC_CALLBACK</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_async_type">ERR_ASYNC_TYPE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_buffer_out_of_bounds">ERR_BUFFER_OUT_OF_BOUNDS</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_buffer_too_large">ERR_BUFFER_TOO_LARGE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_child_closed_before_reply">ERR_CHILD_CLOSED_BEFORE_REPLY</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_console_writable_stream">ERR_CONSOLE_WRITABLE_STREAM</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_cpu_usage">ERR_CPU_USAGE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_crypto_custom_engine_not_supported">ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_crypto_ecdh_invalid_format">ERR_CRYPTO_ECDH_INVALID_FORMAT</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_crypto_engine_unknown">ERR_CRYPTO_ENGINE_UNKNOWN</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_crypto_fips_forced">ERR_CRYPTO_FIPS_FORCED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_crypto_fips_unavailable">ERR_CRYPTO_FIPS_UNAVAILABLE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_crypto_hash_digest_no_utf16">ERR_CRYPTO_HASH_DIGEST_NO_UTF16</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_crypto_hash_finalized">ERR_CRYPTO_HASH_FINALIZED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_crypto_hash_update_failed">ERR_CRYPTO_HASH_UPDATE_FAILED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_crypto_invalid_digest">ERR_CRYPTO_INVALID_DIGEST</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_crypto_sign_key_required">ERR_CRYPTO_SIGN_KEY_REQUIRED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_crypto_timing_safe_equal_length">ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_dns_set_servers_failed">ERR_DNS_SET_SERVERS_FAILED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_domain_callback_not_available">ERR_DOMAIN_CALLBACK_NOT_AVAILABLE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_domain_cannot_set_uncaught_exception_capture">ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_encoding_invalid_encoded_data">ERR_ENCODING_INVALID_ENCODED_DATA</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_encoding_not_supported">ERR_ENCODING_NOT_SUPPORTED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_falsy_value_rejection">ERR_FALSY_VALUE_REJECTION</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http_headers_sent">ERR_HTTP_HEADERS_SENT</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http_invalid_status_code">ERR_HTTP_INVALID_STATUS_CODE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http_trailer_invalid">ERR_HTTP_TRAILER_INVALID</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_altsvc_invalid_origin">ERR_HTTP2_ALTSVC_INVALID_ORIGIN</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_altsvc_length">ERR_HTTP2_ALTSVC_LENGTH</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_connect_authority">ERR_HTTP2_CONNECT_AUTHORITY</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_connect_path">ERR_HTTP2_CONNECT_PATH</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_connect_scheme">ERR_HTTP2_CONNECT_SCHEME</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_goaway_session">ERR_HTTP2_GOAWAY_SESSION</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_header_single_value">ERR_HTTP2_HEADER_SINGLE_VALUE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_headers_after_respond">ERR_HTTP2_HEADERS_AFTER_RESPOND</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_headers_sent">ERR_HTTP2_HEADERS_SENT</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_info_status_not_allowed">ERR_HTTP2_INFO_STATUS_NOT_ALLOWED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_invalid_connection_headers">ERR_HTTP2_INVALID_CONNECTION_HEADERS</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_invalid_header_value">ERR_HTTP2_INVALID_HEADER_VALUE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_invalid_info_status">ERR_HTTP2_INVALID_INFO_STATUS</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_invalid_packed_settings_length">ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_invalid_pseudoheader">ERR_HTTP2_INVALID_PSEUDOHEADER</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_invalid_session">ERR_HTTP2_INVALID_SESSION</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_invalid_setting_value">ERR_HTTP2_INVALID_SETTING_VALUE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_invalid_stream">ERR_HTTP2_INVALID_STREAM</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_max_pending_settings_ack">ERR_HTTP2_MAX_PENDING_SETTINGS_ACK</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_no_socket_manipulation">ERR_HTTP2_NO_SOCKET_MANIPULATION</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_out_of_streams">ERR_HTTP2_OUT_OF_STREAMS</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_payload_forbidden">ERR_HTTP2_PAYLOAD_FORBIDDEN</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_ping_cancel">ERR_HTTP2_PING_CANCEL</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_ping_length">ERR_HTTP2_PING_LENGTH</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_pseudoheader_not_allowed">ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_push_disabled">ERR_HTTP2_PUSH_DISABLED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_send_file">ERR_HTTP2_SEND_FILE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_session_error">ERR_HTTP2_SESSION_ERROR</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_socket_bound">ERR_HTTP2_SOCKET_BOUND</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_status_101">ERR_HTTP2_STATUS_101</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_status_invalid">ERR_HTTP2_STATUS_INVALID</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_stream_cancel">ERR_HTTP2_STREAM_CANCEL</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_stream_error">ERR_HTTP2_STREAM_ERROR</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_stream_self_dependency">ERR_HTTP2_STREAM_SELF_DEPENDENCY</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_http2_unsupported_protocol">ERR_HTTP2_UNSUPPORTED_PROTOCOL</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_index_out_of_range">ERR_INDEX_OUT_OF_RANGE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_inspector_already_connected">ERR_INSPECTOR_ALREADY_CONNECTED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_inspector_closed">ERR_INSPECTOR_CLOSED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_inspector_not_available">ERR_INSPECTOR_NOT_AVAILABLE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_inspector_not_connected">ERR_INSPECTOR_NOT_CONNECTED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_arg_type">ERR_INVALID_ARG_TYPE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_arg_value">ERR_INVALID_ARG_VALUE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_array_length">ERR_INVALID_ARRAY_LENGTH</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_async_id">ERR_INVALID_ASYNC_ID</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_buffer_size">ERR_INVALID_BUFFER_SIZE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_callback">ERR_INVALID_CALLBACK</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_char">ERR_INVALID_CHAR</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_cursor_pos">ERR_INVALID_CURSOR_POS</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_domain_name">ERR_INVALID_DOMAIN_NAME</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_fd">ERR_INVALID_FD</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_fd_type">ERR_INVALID_FD_TYPE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_file_url_host">ERR_INVALID_FILE_URL_HOST</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_file_url_path">ERR_INVALID_FILE_URL_PATH</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_handle_type">ERR_INVALID_HANDLE_TYPE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_http_token">ERR_INVALID_HTTP_TOKEN</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_ip_address">ERR_INVALID_IP_ADDRESS</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_opt_value">ERR_INVALID_OPT_VALUE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_opt_value_encoding">ERR_INVALID_OPT_VALUE_ENCODING</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_performance_mark">ERR_INVALID_PERFORMANCE_MARK</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_protocol">ERR_INVALID_PROTOCOL</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_repl_eval_config">ERR_INVALID_REPL_EVAL_CONFIG</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_sync_fork_input">ERR_INVALID_SYNC_FORK_INPUT</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_this">ERR_INVALID_THIS</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_tuple">ERR_INVALID_TUPLE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_uri">ERR_INVALID_URI</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_url">ERR_INVALID_URL</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_invalid_url_scheme">ERR_INVALID_URL_SCHEME</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_ipc_channel_closed">ERR_IPC_CHANNEL_CLOSED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_ipc_disconnected">ERR_IPC_DISCONNECTED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_ipc_one_pipe">ERR_IPC_ONE_PIPE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_ipc_sync_fork">ERR_IPC_SYNC_FORK</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_method_not_implemented">ERR_METHOD_NOT_IMPLEMENTED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_missing_args">ERR_MISSING_ARGS</a></span></li>
<li><span class="stability_1"><a href="#errors_err_missing_module">ERR_MISSING_MODULE</a></span></li>
<li><span class="stability_1"><a href="#errors_err_module_resolution_legacy">ERR_MODULE_RESOLUTION_LEGACY</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_multiple_callback">ERR_MULTIPLE_CALLBACK</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_napi_cons_function">ERR_NAPI_CONS_FUNCTION</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_napi_invalid_dataview_args">ERR_NAPI_INVALID_DATAVIEW_ARGS</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_napi_invalid_typedarray_alignment">ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_napi_invalid_typedarray_length">ERR_NAPI_INVALID_TYPEDARRAY_LENGTH</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_no_crypto">ERR_NO_CRYPTO</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_no_icu">ERR_NO_ICU</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_no_longer_supported">ERR_NO_LONGER_SUPPORTED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_out_of_range">ERR_OUT_OF_RANGE</a></span></li>
<li><span class="stability_1"><a href="#errors_err_require_esm">ERR_REQUIRE_ESM</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_server_already_listen">ERR_SERVER_ALREADY_LISTEN</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_socket_already_bound">ERR_SOCKET_ALREADY_BOUND</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_socket_bad_buffer_size">ERR_SOCKET_BAD_BUFFER_SIZE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_socket_bad_port">ERR_SOCKET_BAD_PORT</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_socket_bad_type">ERR_SOCKET_BAD_TYPE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_socket_buffer_size">ERR_SOCKET_BUFFER_SIZE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_socket_cannot_send">ERR_SOCKET_CANNOT_SEND</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_socket_closed">ERR_SOCKET_CLOSED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_socket_dgram_not_running">ERR_SOCKET_DGRAM_NOT_RUNNING</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_stderr_close">ERR_STDERR_CLOSE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_stdout_close">ERR_STDOUT_CLOSE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_stream_cannot_pipe">ERR_STREAM_CANNOT_PIPE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_stream_null_values">ERR_STREAM_NULL_VALUES</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_stream_push_after_eof">ERR_STREAM_PUSH_AFTER_EOF</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_stream_read_not_implemented">ERR_STREAM_READ_NOT_IMPLEMENTED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_stream_unshift_after_end_event">ERR_STREAM_UNSHIFT_AFTER_END_EVENT</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_stream_wrap">ERR_STREAM_WRAP</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_stream_write_after_end">ERR_STREAM_WRITE_AFTER_END</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_tls_cert_altname_invalid">ERR_TLS_CERT_ALTNAME_INVALID</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_tls_dh_param_size">ERR_TLS_DH_PARAM_SIZE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_tls_handshake_timeout">ERR_TLS_HANDSHAKE_TIMEOUT</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_tls_required_server_name">ERR_TLS_REQUIRED_SERVER_NAME</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_tls_session_attack">ERR_TLS_SESSION_ATTACK</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_transform_already_transforming">ERR_TRANSFORM_ALREADY_TRANSFORMING</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_transform_with_length_0">ERR_TRANSFORM_WITH_LENGTH_0</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_uncaught_exception_capture_already_set">ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_unescaped_characters">ERR_UNESCAPED_CHARACTERS</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_unhandled_error">ERR_UNHANDLED_ERROR</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_unknown_encoding">ERR_UNKNOWN_ENCODING</a></span></li>
<li><span class="stability_1"><a href="#errors_err_unknown_file_extension">ERR_UNKNOWN_FILE_EXTENSION</a></span></li>
<li><span class="stability_1"><a href="#errors_err_unknown_module_format">ERR_UNKNOWN_MODULE_FORMAT</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_unknown_signal">ERR_UNKNOWN_SIGNAL</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_unknown_stdin_type">ERR_UNKNOWN_STDIN_TYPE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_unknown_stream_type">ERR_UNKNOWN_STREAM_TYPE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_v8breakiterator">ERR_V8BREAKITERATOR</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_valid_performance_entry_type">ERR_VALID_PERFORMANCE_ENTRY_TYPE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_value_out_of_range">ERR_VALUE_OUT_OF_RANGE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_vm_module_already_linked">ERR_VM_MODULE_ALREADY_LINKED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_vm_module_different_context">ERR_VM_MODULE_DIFFERENT_CONTEXT</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_vm_module_linking_errored">ERR_VM_MODULE_LINKING_ERRORED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_vm_module_not_linked">ERR_VM_MODULE_NOT_LINKED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_vm_module_not_module">ERR_VM_MODULE_NOT_MODULE</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_vm_module_status">ERR_VM_MODULE_STATUS</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_zlib_binding_closed">ERR_ZLIB_BINDING_CLOSED</a></span></li>
<li><span class="stability_undefined"><a href="#errors_err_zlib_initialization_failed">ERR_ZLIB_INITIALIZATION_FAILED</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#events_events">Events</a></span><ul>
<li><span class="stability_undefined"><a href="#events_passing_arguments_and_this_to_listeners">Passing arguments and <code>this</code> to listeners</a></span></li>
<li><span class="stability_undefined"><a href="#events_asynchronous_vs_synchronous">Asynchronous vs. Synchronous</a></span></li>
<li><span class="stability_undefined"><a href="#events_handling_events_only_once">Handling events only once</a></span></li>
<li><span class="stability_undefined"><a href="#events_error_events">Error events</a></span></li>
<li><span class="stability_undefined"><a href="#events_class_eventemitter">Class: EventEmitter</a></span><ul>
<li><span class="stability_undefined"><a href="#events_event_newlistener">Event: 'newListener'</a></span></li>
<li><span class="stability_undefined"><a href="#events_event_removelistener">Event: 'removeListener'</a></span></li>
<li><span class="stability_0"><a href="#events_eventemitter_listenercount_emitter_eventname">EventEmitter.listenerCount(emitter, eventName)</a></span></li>
<li><span class="stability_undefined"><a href="#events_eventemitter_defaultmaxlisteners">EventEmitter.defaultMaxListeners</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_addlistener_eventname_listener">emitter.addListener(eventName, listener)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_emit_eventname_args">emitter.emit(eventName[, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_eventnames">emitter.eventNames()</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_getmaxlisteners">emitter.getMaxListeners()</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_listenercount_eventname">emitter.listenerCount(eventName)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_listeners_eventname">emitter.listeners(eventName)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_on_eventname_listener">emitter.on(eventName, listener)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_once_eventname_listener">emitter.once(eventName, listener)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_prependlistener_eventname_listener">emitter.prependListener(eventName, listener)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_prependoncelistener_eventname_listener">emitter.prependOnceListener(eventName, listener)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_removealllisteners_eventname">emitter.removeAllListeners([eventName])</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_removelistener_eventname_listener">emitter.removeListener(eventName, listener)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_setmaxlisteners_n">emitter.setMaxListeners(n)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_rawlisteners_eventname">emitter.rawListeners(eventName)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#fs_file_system">File System</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_file_paths">File paths</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_url_object_support">URL object support</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_file_descriptors">File Descriptors</a></span></li>
<li><span class="stability_undefined"><a href="#fs_threadpool_usage">Threadpool Usage</a></span></li>
<li><span class="stability_undefined"><a href="#fs_class_fs_fswatcher">Class: fs.FSWatcher</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_event_change">Event: 'change'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_watcher_close">watcher.close()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_class_fs_readstream">Class: fs.ReadStream</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_event_open">Event: 'open'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_readstream_bytesread">readStream.bytesRead</a></span></li>
<li><span class="stability_undefined"><a href="#fs_readstream_path">readStream.path</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_class_fs_stats">Class: fs.Stats</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_stats_isblockdevice">stats.isBlockDevice()</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_ischaracterdevice">stats.isCharacterDevice()</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_isdirectory">stats.isDirectory()</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_isfifo">stats.isFIFO()</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_isfile">stats.isFile()</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_issocket">stats.isSocket()</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_issymboliclink">stats.isSymbolicLink()</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_dev">stats.dev</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_ino">stats.ino</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_mode">stats.mode</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_nlink">stats.nlink</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_uid">stats.uid</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_gid">stats.gid</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_rdev">stats.rdev</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_size">stats.size</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_blksize">stats.blksize</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_blocks">stats.blocks</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_atimems">stats.atimeMs</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_mtimems">stats.mtimeMs</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_ctimems">stats.ctimeMs</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_birthtimems">stats.birthtimeMs</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_atime">stats.atime</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_mtime">stats.mtime</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_ctime">stats.ctime</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stats_birthtime">stats.birthtime</a></span></li>
<li><span class="stability_undefined"><a href="#fs_stat_time_values">Stat Time Values</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_class_fs_writestream">Class: fs.WriteStream</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_event_close_1">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_event_open_1">Event: 'open'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_writestream_byteswritten">writeStream.bytesWritten</a></span></li>
<li><span class="stability_undefined"><a href="#fs_writestream_path">writeStream.path</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_fs_access_path_mode_callback">fs.access(path[, mode], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_accesssync_path_mode">fs.accessSync(path[, mode])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_appendfile_file_data_options_callback">fs.appendFile(file, data[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_appendfilesync_file_data_options">fs.appendFileSync(file, data[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_chmod_path_mode_callback">fs.chmod(path, mode, callback)</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_file_modes">File modes</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_fs_chmodsync_path_mode">fs.chmodSync(path, mode)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_chown_path_uid_gid_callback">fs.chown(path, uid, gid, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_chownsync_path_uid_gid">fs.chownSync(path, uid, gid)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_close_fd_callback">fs.close(fd, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_closesync_fd">fs.closeSync(fd)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_constants">fs.constants</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_copyfile_src_dest_flags_callback">fs.copyFile(src, dest[, flags], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_copyfilesync_src_dest_flags">fs.copyFileSync(src, dest[, flags])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_createreadstream_path_options">fs.createReadStream(path[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_createwritestream_path_options">fs.createWriteStream(path[, options])</a></span></li>
<li><span class="stability_0"><a href="#fs_fs_exists_path_callback">fs.exists(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_existssync_path">fs.existsSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fchmod_fd_mode_callback">fs.fchmod(fd, mode, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fchmodsync_fd_mode">fs.fchmodSync(fd, mode)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fchown_fd_uid_gid_callback">fs.fchown(fd, uid, gid, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fchownsync_fd_uid_gid">fs.fchownSync(fd, uid, gid)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fdatasync_fd_callback">fs.fdatasync(fd, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fdatasyncsync_fd">fs.fdatasyncSync(fd)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fstat_fd_callback">fs.fstat(fd, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fstatsync_fd">fs.fstatSync(fd)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fsync_fd_callback">fs.fsync(fd, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fsyncsync_fd">fs.fsyncSync(fd)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_ftruncate_fd_len_callback">fs.ftruncate(fd[, len], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_ftruncatesync_fd_len">fs.ftruncateSync(fd[, len])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_futimes_fd_atime_mtime_callback">fs.futimes(fd, atime, mtime, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_futimessync_fd_atime_mtime">fs.futimesSync(fd, atime, mtime)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lchmod_path_mode_callback">fs.lchmod(path, mode, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lchmodsync_path_mode">fs.lchmodSync(path, mode)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lchown_path_uid_gid_callback">fs.lchown(path, uid, gid, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lchownsync_path_uid_gid">fs.lchownSync(path, uid, gid)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_link_existingpath_newpath_callback">fs.link(existingPath, newPath, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_linksync_existingpath_newpath">fs.linkSync(existingPath, newPath)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lstat_path_callback">fs.lstat(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lstatsync_path">fs.lstatSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_mkdir_path_mode_callback">fs.mkdir(path[, mode], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_mkdirsync_path_mode">fs.mkdirSync(path[, mode])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_mkdtemp_prefix_options_callback">fs.mkdtemp(prefix[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_mkdtempsync_prefix_options">fs.mkdtempSync(prefix[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_open_path_flags_mode_callback">fs.open(path, flags[, mode], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_opensync_path_flags_mode">fs.openSync(path, flags[, mode])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_read_fd_buffer_offset_length_position_callback">fs.read(fd, buffer, offset, length, position, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readdir_path_options_callback">fs.readdir(path[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readdirsync_path_options">fs.readdirSync(path[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readfile_path_options_callback">fs.readFile(path[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readfilesync_path_options">fs.readFileSync(path[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readlink_path_options_callback">fs.readlink(path[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readlinksync_path_options">fs.readlinkSync(path[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readsync_fd_buffer_offset_length_position">fs.readSync(fd, buffer, offset, length, position)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_realpath_path_options_callback">fs.realpath(path[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_realpath_native_path_options_callback">fs.realpath.native(path[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_realpathsync_path_options">fs.realpathSync(path[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_realpathsync_native_path_options">fs.realpathSync.native(path[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_rename_oldpath_newpath_callback">fs.rename(oldPath, newPath, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_renamesync_oldpath_newpath">fs.renameSync(oldPath, newPath)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_rmdir_path_callback">fs.rmdir(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_rmdirsync_path">fs.rmdirSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_stat_path_callback">fs.stat(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_statsync_path">fs.statSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_symlink_target_path_type_callback">fs.symlink(target, path[, type], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_symlinksync_target_path_type">fs.symlinkSync(target, path[, type])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_truncate_path_len_callback">fs.truncate(path[, len], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_truncatesync_path_len">fs.truncateSync(path[, len])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_unlink_path_callback">fs.unlink(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_unlinksync_path">fs.unlinkSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_unwatchfile_filename_listener">fs.unwatchFile(filename[, listener])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_utimes_path_atime_mtime_callback">fs.utimes(path, atime, mtime, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_utimessync_path_atime_mtime">fs.utimesSync(path, atime, mtime)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_watch_filename_options_listener">fs.watch(filename[, options][, listener])</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_caveats">Caveats</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_availability">Availability</a></span></li>
<li><span class="stability_undefined"><a href="#fs_inodes">Inodes</a></span></li>
<li><span class="stability_undefined"><a href="#fs_filename_argument">Filename Argument</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_fs_watchfile_filename_options_listener">fs.watchFile(filename[, options], listener)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_write_fd_buffer_offset_length_position_callback">fs.write(fd, buffer[, offset[, length[, position]]], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_write_fd_string_position_encoding_callback">fs.write(fd, string[, position[, encoding]], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_writefile_file_data_options_callback">fs.writeFile(file, data[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_writefilesync_file_data_options">fs.writeFileSync(file, data[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_writesync_fd_buffer_offset_length_position">fs.writeSync(fd, buffer[, offset[, length[, position]]])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_writesync_fd_string_position_encoding">fs.writeSync(fd, string[, position[, encoding]])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_constants_1">FS Constants</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_file_access_constants">File Access Constants</a></span></li>
<li><span class="stability_undefined"><a href="#fs_file_open_constants">File Open Constants</a></span></li>
<li><span class="stability_undefined"><a href="#fs_file_type_constants">File Type Constants</a></span></li>
<li><span class="stability_undefined"><a href="#fs_file_mode_constants">File Mode Constants</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#globals_global_objects">Global Objects</a></span><ul>
<li><span class="stability_undefined"><a href="#globals_class_buffer">Class: Buffer</a></span></li>
<li><span class="stability_undefined"><a href="#globals_dirname">__dirname</a></span></li>
<li><span class="stability_undefined"><a href="#globals_filename">__filename</a></span></li>
<li><span class="stability_undefined"><a href="#globals_clearimmediate_immediateobject">clearImmediate(immediateObject)</a></span></li>
<li><span class="stability_undefined"><a href="#globals_clearinterval_intervalobject">clearInterval(intervalObject)</a></span></li>
<li><span class="stability_undefined"><a href="#globals_cleartimeout_timeoutobject">clearTimeout(timeoutObject)</a></span></li>
<li><span class="stability_undefined"><a href="#globals_console">console</a></span></li>
<li><span class="stability_undefined"><a href="#globals_exports">exports</a></span></li>
<li><span class="stability_undefined"><a href="#globals_global">global</a></span></li>
<li><span class="stability_undefined"><a href="#globals_module">module</a></span></li>
<li><span class="stability_undefined"><a href="#globals_process">process</a></span></li>
<li><span class="stability_undefined"><a href="#globals_require">require()</a></span></li>
<li><span class="stability_undefined"><a href="#globals_setimmediate_callback_args">setImmediate(callback[, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#globals_setinterval_callback_delay_args">setInterval(callback, delay[, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#globals_settimeout_callback_delay_args">setTimeout(callback, delay[, ...args])</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#http_http">HTTP</a></span><ul>
<li><span class="stability_undefined"><a href="#http_class_http_agent">Class: http.Agent</a></span><ul>
<li><span class="stability_undefined"><a href="#http_new_agent_options">new Agent([options])</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_createconnection_options_callback">agent.createConnection(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_keepsocketalive_socket">agent.keepSocketAlive(socket)</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_reusesocket_socket_request">agent.reuseSocket(socket, request)</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_destroy">agent.destroy()</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_freesockets">agent.freeSockets</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_getname_options">agent.getName(options)</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_maxfreesockets">agent.maxFreeSockets</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_maxsockets">agent.maxSockets</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_requests">agent.requests</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_sockets">agent.sockets</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http_class_http_clientrequest">Class: http.ClientRequest</a></span><ul>
<li><span class="stability_undefined"><a href="#http_event_abort">Event: 'abort'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_connect">Event: 'connect'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_continue">Event: 'continue'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_response">Event: 'response'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_socket">Event: 'socket'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_timeout">Event: 'timeout'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_upgrade">Event: 'upgrade'</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_abort">request.abort()</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_aborted">request.aborted</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_connection">request.connection</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_end_data_encoding_callback">request.end([data[, encoding]][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_flushheaders">request.flushHeaders()</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_getheader_name">request.getHeader(name)</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_removeheader_name">request.removeHeader(name)</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_setheader_name_value">request.setHeader(name, value)</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_setnodelay_nodelay">request.setNoDelay([noDelay])</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_setsocketkeepalive_enable_initialdelay">request.setSocketKeepAlive([enable][, initialDelay])</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_settimeout_timeout_callback">request.setTimeout(timeout[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_socket">request.socket</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_write_chunk_encoding_callback">request.write(chunk[, encoding][, callback])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http_class_http_server">Class: http.Server</a></span><ul>
<li><span class="stability_undefined"><a href="#http_event_checkcontinue">Event: 'checkContinue'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_checkexpectation">Event: 'checkExpectation'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_clienterror">Event: 'clientError'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_connect_1">Event: 'connect'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_connection">Event: 'connection'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_request">Event: 'request'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_upgrade_1">Event: 'upgrade'</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_close_callback">server.close([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_listen">server.listen()</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_listening">server.listening</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_maxheaderscount">server.maxHeadersCount</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_settimeout_msecs_callback">server.setTimeout([msecs][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_timeout">server.timeout</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_keepalivetimeout">server.keepAliveTimeout</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http_class_http_serverresponse">Class: http.ServerResponse</a></span><ul>
<li><span class="stability_undefined"><a href="#http_event_close_1">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_finish">Event: 'finish'</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_addtrailers_headers">response.addTrailers(headers)</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_connection">response.connection</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_end_data_encoding_callback">response.end([data][, encoding][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_finished">response.finished</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_getheader_name">response.getHeader(name)</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_getheadernames">response.getHeaderNames()</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_getheaders">response.getHeaders()</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_hasheader_name">response.hasHeader(name)</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_headerssent">response.headersSent</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_removeheader_name">response.removeHeader(name)</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_senddate">response.sendDate</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_setheader_name_value">response.setHeader(name, value)</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_settimeout_msecs_callback">response.setTimeout(msecs[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_socket">response.socket</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_statuscode">response.statusCode</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_statusmessage">response.statusMessage</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_write_chunk_encoding_callback">response.write(chunk[, encoding][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_writecontinue">response.writeContinue()</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_writehead_statuscode_statusmessage_headers">response.writeHead(statusCode[, statusMessage][, headers])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http_class_http_incomingmessage">Class: http.IncomingMessage</a></span><ul>
<li><span class="stability_undefined"><a href="#http_event_aborted">Event: 'aborted'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_close_2">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_destroy_error">message.destroy([error])</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_headers">message.headers</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_httpversion">message.httpVersion</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_method">message.method</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_rawheaders">message.rawHeaders</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_rawtrailers">message.rawTrailers</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_settimeout_msecs_callback">message.setTimeout(msecs, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_socket">message.socket</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_statuscode">message.statusCode</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_statusmessage">message.statusMessage</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_trailers">message.trailers</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_url">message.url</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http_http_methods">http.METHODS</a></span></li>
<li><span class="stability_undefined"><a href="#http_http_status_codes">http.STATUS_CODES</a></span></li>
<li><span class="stability_undefined"><a href="#http_http_createserver_options_requestlistener">http.createServer([options][, requestListener])</a></span></li>
<li><span class="stability_undefined"><a href="#http_http_get_options_callback">http.get(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_http_globalagent">http.globalAgent</a></span></li>
<li><span class="stability_undefined"><a href="#http_http_request_options_callback">http.request(options[, callback])</a></span></li>
</ul>
</li>
<li><span class="stability_1"><a href="#http2_http_2">HTTP/2</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_core_api">Core API</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_server_side_example">Server-side example</a></span></li>
<li><span class="stability_undefined"><a href="#http2_client_side_example">Client-side example</a></span></li>
<li><span class="stability_undefined"><a href="#http2_class_http2session">Class: Http2Session</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_http2session_and_sockets">Http2Session and Sockets</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_connect">Event: 'connect'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_frameerror">Event: 'frameError'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_goaway">Event: 'goaway'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_localsettings">Event: 'localSettings'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_remotesettings">Event: 'remoteSettings'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_stream">Event: 'stream'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_timeout">Event: 'timeout'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_alpnprotocol">http2session.alpnProtocol</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_close_callback">http2session.close([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_closed">http2session.closed</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_destroy_error_code">http2session.destroy([error,][code])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_destroyed">http2session.destroyed</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_encrypted">http2session.encrypted</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_goaway_code_laststreamid_opaquedata">http2session.goaway([code, [lastStreamID, [opaqueData]]])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_localsettings">http2session.localSettings</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_originset">http2session.originSet</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_pendingsettingsack">http2session.pendingSettingsAck</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_ping_payload_callback">http2session.ping([payload, ]callback)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_ref">http2session.ref()</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_remotesettings">http2session.remoteSettings</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_settimeout_msecs_callback">http2session.setTimeout(msecs, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_socket">http2session.socket</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_state">http2session.state</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_settings_settings">http2session.settings(settings)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_type">http2session.type</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2session_unref">http2session.unref()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_class_serverhttp2session">Class: ServerHttp2Session</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_serverhttp2session_altsvc_alt_originorstream">serverhttp2session.altsvc(alt, originOrStream)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_specifying_alternative_services">Specifying alternative services</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_class_clienthttp2session">Class: ClientHttp2Session</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_event_altsvc">Event: 'altsvc'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_clienthttp2session_request_headers_options">clienthttp2session.request(headers[, options])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_class_http2stream">Class: Http2Stream</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_http2stream_lifecycle">Http2Stream Lifecycle</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_creation">Creation</a></span></li>
<li><span class="stability_undefined"><a href="#http2_destruction">Destruction</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_event_aborted">Event: 'aborted'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_close_1">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_error_1">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_frameerror_1">Event: 'frameError'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_timeout_1">Event: 'timeout'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_trailers">Event: 'trailers'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_aborted">http2stream.aborted</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_close_code_callback">http2stream.close(code[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_closed">http2stream.closed</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_destroyed">http2stream.destroyed</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_pending">http2stream.pending</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_priority_options">http2stream.priority(options)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_rstcode">http2stream.rstCode</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_sentheaders">http2stream.sentHeaders</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_sentinfoheaders">http2stream.sentInfoHeaders</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_senttrailers">http2stream.sentTrailers</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_session">http2stream.session</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_settimeout_msecs_callback">http2stream.setTimeout(msecs, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_state">http2stream.state</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_class_clienthttp2stream">Class: ClientHttp2Stream</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_event_continue">Event: 'continue'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_headers">Event: 'headers'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_push">Event: 'push'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_response">Event: 'response'</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_class_serverhttp2stream">Class: ServerHttp2Stream</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_http2stream_additionalheaders_headers">http2stream.additionalHeaders(headers)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_headerssent">http2stream.headersSent</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_pushallowed">http2stream.pushAllowed</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_pushstream_headers_options_callback">http2stream.pushStream(headers[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_respond_headers_options">http2stream.respond([headers[, options]])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_respondwithfd_fd_headers_options">http2stream.respondWithFD(fd[, headers[, options]])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2stream_respondwithfile_path_headers_options">http2stream.respondWithFile(path[, headers[, options]])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_class_http2server">Class: Http2Server</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_event_checkcontinue">Event: 'checkContinue'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_request">Event: 'request'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_session">Event: 'session'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_sessionerror">Event: 'sessionError'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_streamerror">Event: 'streamError'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_stream_1">Event: 'stream'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_timeout_2">Event: 'timeout'</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_class_http2secureserver">Class: Http2SecureServer</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_event_checkcontinue_1">Event: 'checkContinue'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_request_1">Event: 'request'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_session_1">Event: 'session'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_sessionerror_1">Event: 'sessionError'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_stream_2">Event: 'stream'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_timeout_3">Event: 'timeout'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_unknownprotocol">Event: 'unknownProtocol'</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_http2_createserver_options_onrequesthandler">http2.createServer(options[, onRequestHandler])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2_createsecureserver_options_onrequesthandler">http2.createSecureServer(options[, onRequestHandler])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2_connect_authority_options_listener">http2.connect(authority[, options][, listener])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2_constants">http2.constants</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_error_codes_for_rst_stream_and_goaway">Error Codes for RST_STREAM and GOAWAY</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_http2_getdefaultsettings">http2.getDefaultSettings()</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2_getpackedsettings_settings">http2.getPackedSettings(settings)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_http2_getunpackedsettings_buf">http2.getUnpackedSettings(buf)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_headers_object">Headers Object</a></span></li>
<li><span class="stability_undefined"><a href="#http2_settings_object">Settings Object</a></span></li>
<li><span class="stability_undefined"><a href="#http2_using_options_selectpadding">Using <code>options.selectPadding</code></a></span></li>
<li><span class="stability_undefined"><a href="#http2_error_handling">Error Handling</a></span></li>
<li><span class="stability_undefined"><a href="#http2_invalid_character_handling_in_header_names_and_values">Invalid character handling in header names and values</a></span></li>
<li><span class="stability_undefined"><a href="#http2_push_streams_on_the_client">Push streams on the client</a></span></li>
<li><span class="stability_undefined"><a href="#http2_supporting_the_connect_method">Supporting the CONNECT method</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_compatibility_api">Compatibility API</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_alpn_negotiation">ALPN negotiation</a></span></li>
<li><span class="stability_undefined"><a href="#http2_class_http2_http2serverrequest">Class: http2.Http2ServerRequest</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_event_aborted_1">Event: 'aborted'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_close_2">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_request_destroy_error">request.destroy([error])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_request_headers">request.headers</a></span></li>
<li><span class="stability_undefined"><a href="#http2_request_httpversion">request.httpVersion</a></span></li>
<li><span class="stability_undefined"><a href="#http2_request_method">request.method</a></span></li>
<li><span class="stability_undefined"><a href="#http2_request_rawheaders">request.rawHeaders</a></span></li>
<li><span class="stability_undefined"><a href="#http2_request_rawtrailers">request.rawTrailers</a></span></li>
<li><span class="stability_undefined"><a href="#http2_request_settimeout_msecs_callback">request.setTimeout(msecs, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_request_socket">request.socket</a></span></li>
<li><span class="stability_undefined"><a href="#http2_request_stream">request.stream</a></span></li>
<li><span class="stability_undefined"><a href="#http2_request_trailers">request.trailers</a></span></li>
<li><span class="stability_undefined"><a href="#http2_request_url">request.url</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_class_http2_http2serverresponse">Class: http2.Http2ServerResponse</a></span><ul>
<li><span class="stability_undefined"><a href="#http2_event_close_3">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_event_finish">Event: 'finish'</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_addtrailers_headers">response.addTrailers(headers)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_connection">response.connection</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_end_data_encoding_callback">response.end([data][, encoding][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_finished">response.finished</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_getheader_name">response.getHeader(name)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_getheadernames">response.getHeaderNames()</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_getheaders">response.getHeaders()</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_hasheader_name">response.hasHeader(name)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_headerssent">response.headersSent</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_removeheader_name">response.removeHeader(name)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_senddate">response.sendDate</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_setheader_name_value">response.setHeader(name, value)</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_settimeout_msecs_callback">response.setTimeout(msecs[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_socket">response.socket</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_statuscode">response.statusCode</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_statusmessage">response.statusMessage</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_stream">response.stream</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_write_chunk_encoding_callback">response.write(chunk[, encoding][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_writecontinue">response.writeContinue()</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_writehead_statuscode_statusmessage_headers">response.writeHead(statusCode[, statusMessage][, headers])</a></span></li>
<li><span class="stability_undefined"><a href="#http2_response_createpushresponse_headers_callback">response.createPushResponse(headers, callback)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http2_collecting_http_2_performance_metrics">Collecting HTTP/2 Performance Metrics</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#https_https">HTTPS</a></span><ul>
<li><span class="stability_undefined"><a href="#https_class_https_agent">Class: https.Agent</a></span></li>
<li><span class="stability_undefined"><a href="#https_class_https_server">Class: https.Server</a></span><ul>
<li><span class="stability_undefined"><a href="#https_server_close_callback">server.close([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#https_server_listen">server.listen()</a></span></li>
<li><span class="stability_undefined"><a href="#https_server_settimeout_msecs_callback">server.setTimeout([msecs][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#https_server_timeout">server.timeout</a></span></li>
<li><span class="stability_undefined"><a href="#https_server_keepalivetimeout">server.keepAliveTimeout</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#https_https_createserver_options_requestlistener">https.createServer([options][, requestListener])</a></span></li>
<li><span class="stability_undefined"><a href="#https_https_get_options_callback">https.get(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#https_https_globalagent">https.globalAgent</a></span></li>
<li><span class="stability_undefined"><a href="#https_https_request_options_callback">https.request(options[, callback])</a></span></li>
</ul>
</li>
<li><span class="stability_1"><a href="#inspector_inspector">Inspector</a></span><ul>
<li><span class="stability_undefined"><a href="#inspector_inspector_open_port_host_wait">inspector.open([port[, host[, wait]]])</a></span><ul>
<li><span class="stability_undefined"><a href="#inspector_inspector_close">inspector.close()</a></span></li>
<li><span class="stability_undefined"><a href="#inspector_inspector_url">inspector.url()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#inspector_class_inspector_session">Class: inspector.Session</a></span><ul>
<li><span class="stability_undefined"><a href="#inspector_constructor_new_inspector_session">Constructor: new inspector.Session()</a></span></li>
<li><span class="stability_undefined"><a href="#inspector_event_inspectornotification">Event: 'inspectorNotification'</a></span></li>
<li><span class="stability_undefined"><a href="#inspector_event_lt_inspector_protocol_method_gt">Event: <inspector-protocol-method></a></span></li>
<li><span class="stability_undefined"><a href="#inspector_session_connect">session.connect()</a></span></li>
<li><span class="stability_undefined"><a href="#inspector_session_post_method_params_callback">session.post(method[, params][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#inspector_session_disconnect">session.disconnect()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#inspector_example_usage">Example usage</a></span><ul>
<li><span class="stability_undefined"><a href="#inspector_cpu_profiler">CPU Profiler</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#intl_internationalization_support">Internationalization Support</a></span><ul>
<li><span class="stability_undefined"><a href="#intl_options_for_building_node_js">Options for building Node.js</a></span><ul>
<li><span class="stability_undefined"><a href="#intl_disable_all_internationalization_features_none">Disable all internationalization features (<code>none</code>)</a></span></li>
<li><span class="stability_undefined"><a href="#intl_build_with_a_pre_installed_icu_system_icu">Build with a pre-installed ICU (<code>system-icu</code>)</a></span></li>
<li><span class="stability_undefined"><a href="#intl_embed_a_limited_set_of_icu_data_small_icu">Embed a limited set of ICU data (<code>small-icu</code>)</a></span><ul>
<li><span class="stability_undefined"><a href="#intl_providing_icu_data_at_runtime">Providing ICU data at runtime</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#intl_embed_the_entire_icu_full_icu">Embed the entire ICU (<code>full-icu</code>)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#intl_detecting_internationalization_support">Detecting internationalization support</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#modules_modules">Modules</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_accessing_the_main_module">Accessing the main module</a></span></li>
<li><span class="stability_undefined"><a href="#modules_addenda_package_manager_tips">Addenda: Package Manager Tips</a></span></li>
<li><span class="stability_undefined"><a href="#modules_all_together">All Together...</a></span></li>
<li><span class="stability_undefined"><a href="#modules_caching">Caching</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_module_caching_caveats">Module Caching Caveats</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#modules_core_modules">Core Modules</a></span></li>
<li><span class="stability_undefined"><a href="#modules_cycles">Cycles</a></span></li>
<li><span class="stability_undefined"><a href="#modules_file_modules">File Modules</a></span></li>
<li><span class="stability_undefined"><a href="#modules_folders_as_modules">Folders as Modules</a></span></li>
<li><span class="stability_undefined"><a href="#modules_loading_from_node_modules_folders">Loading from <code>node_modules</code> Folders</a></span></li>
<li><span class="stability_undefined"><a href="#modules_loading_from_the_global_folders">Loading from the global folders</a></span></li>
<li><span class="stability_undefined"><a href="#modules_the_module_wrapper">The module wrapper</a></span></li>
<li><span class="stability_undefined"><a href="#modules_the_module_scope">The module scope</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_dirname">__dirname</a></span></li>
<li><span class="stability_undefined"><a href="#modules_filename">__filename</a></span></li>
<li><span class="stability_undefined"><a href="#modules_exports">exports</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module">module</a></span></li>
<li><span class="stability_undefined"><a href="#modules_require">require()</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_require_cache">require.cache</a></span></li>
<li><span class="stability_0"><a href="#modules_require_extensions">require.extensions</a></span></li>
<li><span class="stability_undefined"><a href="#modules_require_main">require.main</a></span></li>
<li><span class="stability_undefined"><a href="#modules_require_resolve_request_options">require.resolve(request[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#modules_require_resolve_paths_request">require.resolve.paths(request)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#modules_the_module_object">The <code>module</code> Object</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_module_children">module.children</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_exports">module.exports</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_exports_shortcut">exports shortcut</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#modules_module_filename">module.filename</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_id">module.id</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_loaded">module.loaded</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_parent">module.parent</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_paths">module.paths</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_require_id">module.require(id)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#modules_the_module_object_1">The <code>Module</code> Object</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_module_builtinmodules">module.builtinModules</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#net_net">Net</a></span><ul>
<li><span class="stability_undefined"><a href="#net_ipc_support">IPC Support</a></span><ul>
<li><span class="stability_undefined"><a href="#net_identifying_paths_for_ipc_connections">Identifying paths for IPC connections</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#net_class_net_server">Class: net.Server</a></span><ul>
<li><span class="stability_undefined"><a href="#net_new_net_server_options_connectionlistener">new net.Server([options][, connectionListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_connection">Event: 'connection'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_listening">Event: 'listening'</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_address">server.address()</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_close_callback">server.close([callback])</a></span></li>
<li><span class="stability_0"><a href="#net_server_connections">server.connections</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_getconnections_callback">server.getConnections(callback)</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_listen">server.listen()</a></span><ul>
<li><span class="stability_undefined"><a href="#net_server_listen_handle_backlog_callback">server.listen(handle[, backlog][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_listen_options_callback">server.listen(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_listen_path_backlog_callback">server.listen(path[, backlog][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_listen_port_host_backlog_callback">server.listen([port][, host][, backlog][, callback])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#net_server_listening">server.listening</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_maxconnections">server.maxConnections</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_ref">server.ref()</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_unref">server.unref()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#net_class_net_socket">Class: net.Socket</a></span><ul>
<li><span class="stability_undefined"><a href="#net_new_net_socket_options">new net.Socket([options])</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_close_1">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_connect">Event: 'connect'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_data">Event: 'data'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_drain">Event: 'drain'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_end">Event: 'end'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_error_1">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_lookup">Event: 'lookup'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_timeout">Event: 'timeout'</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_address">socket.address()</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_buffersize">socket.bufferSize</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_bytesread">socket.bytesRead</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_byteswritten">socket.bytesWritten</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_connect">socket.connect()</a></span><ul>
<li><span class="stability_undefined"><a href="#net_socket_connect_options_connectlistener">socket.connect(options[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_connect_path_connectlistener">socket.connect(path[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_connect_port_host_connectlistener">socket.connect(port[, host][, connectListener])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#net_socket_connecting">socket.connecting</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_destroy_exception">socket.destroy([exception])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_destroyed">socket.destroyed</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_end_data_encoding">socket.end([data][, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_localaddress">socket.localAddress</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_localport">socket.localPort</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_pause">socket.pause()</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_ref">socket.ref()</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_remoteaddress">socket.remoteAddress</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_remotefamily">socket.remoteFamily</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_remoteport">socket.remotePort</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_resume">socket.resume()</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_setencoding_encoding">socket.setEncoding([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_setkeepalive_enable_initialdelay">socket.setKeepAlive([enable][, initialDelay])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_setnodelay_nodelay">socket.setNoDelay([noDelay])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_settimeout_timeout_callback">socket.setTimeout(timeout[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_unref">socket.unref()</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_write_data_encoding_callback">socket.write(data[, encoding][, callback])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#net_net_connect">net.connect()</a></span><ul>
<li><span class="stability_undefined"><a href="#net_net_connect_options_connectlistener">net.connect(options[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_connect_path_connectlistener">net.connect(path[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_connect_port_host_connectlistener">net.connect(port[, host][, connectListener])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#net_net_createconnection">net.createConnection()</a></span><ul>
<li><span class="stability_undefined"><a href="#net_net_createconnection_options_connectlistener">net.createConnection(options[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_createconnection_path_connectlistener">net.createConnection(path[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_createconnection_port_host_connectlistener">net.createConnection(port[, host][, connectListener])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#net_net_createserver_options_connectionlistener">net.createServer([options][, connectionListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_isip_input">net.isIP(input)</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_isipv4_input">net.isIPv4(input)</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_isipv6_input">net.isIPv6(input)</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#os_os">OS</a></span><ul>
<li><span class="stability_undefined"><a href="#os_os_eol">os.EOL</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_arch">os.arch()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_constants">os.constants</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_cpus">os.cpus()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_endianness">os.endianness()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_freemem">os.freemem()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_homedir">os.homedir()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_hostname">os.hostname()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_loadavg">os.loadavg()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_networkinterfaces">os.networkInterfaces()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_platform">os.platform()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_release">os.release()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_tmpdir">os.tmpdir()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_totalmem">os.totalmem()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_type">os.type()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_uptime">os.uptime()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_userinfo_options">os.userInfo([options])</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_constants_1">OS Constants</a></span><ul>
<li><span class="stability_undefined"><a href="#os_signal_constants">Signal Constants</a></span></li>
<li><span class="stability_undefined"><a href="#os_error_constants">Error Constants</a></span><ul>
<li><span class="stability_undefined"><a href="#os_posix_error_constants">POSIX Error Constants</a></span></li>
<li><span class="stability_undefined"><a href="#os_windows_specific_error_constants">Windows Specific Error Constants</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#os_dlopen_constants">dlopen Constants</a></span></li>
<li><span class="stability_undefined"><a href="#os_libuv_constants">libuv Constants</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#path_path">Path</a></span><ul>
<li><span class="stability_undefined"><a href="#path_windows_vs_posix">Windows vs. POSIX</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_basename_path_ext">path.basename(path[, ext])</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_delimiter">path.delimiter</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_dirname_path">path.dirname(path)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_extname_path">path.extname(path)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_format_pathobject">path.format(pathObject)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_isabsolute_path">path.isAbsolute(path)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_join_paths">path.join([...paths])</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_normalize_path">path.normalize(path)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_parse_path">path.parse(path)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_posix">path.posix</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_relative_from_to">path.relative(from, to)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_resolve_paths">path.resolve([...paths])</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_sep">path.sep</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_tonamespacedpath_path">path.toNamespacedPath(path)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_win32">path.win32</a></span></li>
</ul>
</li>
<li><span class="stability_1"><a href="#perf_hooks_performance_timing_api">Performance Timing API</a></span><ul>
<li><span class="stability_undefined"><a href="#perf_hooks_class_performance">Class: Performance</a></span><ul>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_clearentries_name">performance.clearEntries(name)</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_clearfunctions_name">performance.clearFunctions([name])</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_cleargc">performance.clearGC()</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_clearmarks_name">performance.clearMarks([name])</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_clearmeasures_name">performance.clearMeasures([name])</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_getentries">performance.getEntries()</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_getentriesbyname_name_type">performance.getEntriesByName(name[, type])</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_getentriesbytype_type">performance.getEntriesByType(type)</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_mark_name">performance.mark([name])</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_maxentries">performance.maxEntries</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_measure_name_startmark_endmark">performance.measure(name, startMark, endMark)</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_nodetiming">performance.nodeTiming</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_now">performance.now()</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_timeorigin">performance.timeOrigin</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performance_timerify_fn">performance.timerify(fn)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#perf_hooks_class_performanceentry">Class: PerformanceEntry</a></span><ul>
<li><span class="stability_undefined"><a href="#perf_hooks_performanceentry_duration">performanceEntry.duration</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performanceentry_name">performanceEntry.name</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performanceentry_starttime">performanceEntry.startTime</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performanceentry_entrytype">performanceEntry.entryType</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performanceentry_kind">performanceEntry.kind</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#perf_hooks_class_performancenodetiming_extends_performanceentry">Class: PerformanceNodeTiming extends PerformanceEntry</a></span><ul>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_bootstrapcomplete">performanceNodeTiming.bootstrapComplete</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_clustersetupend">performanceNodeTiming.clusterSetupEnd</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_clustersetupstart">performanceNodeTiming.clusterSetupStart</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_loopexit">performanceNodeTiming.loopExit</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_loopstart">performanceNodeTiming.loopStart</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_moduleloadend">performanceNodeTiming.moduleLoadEnd</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_moduleloadstart">performanceNodeTiming.moduleLoadStart</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_nodestart">performanceNodeTiming.nodeStart</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_preloadmoduleloadend">performanceNodeTiming.preloadModuleLoadEnd</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_preloadmoduleloadstart">performanceNodeTiming.preloadModuleLoadStart</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_thirdpartymainend">performanceNodeTiming.thirdPartyMainEnd</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_thirdpartymainstart">performanceNodeTiming.thirdPartyMainStart</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performancenodetiming_v8start">performanceNodeTiming.v8Start</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#perf_hooks_class_performanceobserver_callback">Class: PerformanceObserver(callback)</a></span><ul>
<li><span class="stability_undefined"><a href="#perf_hooks_callback_performanceobservercallback_list_observer">Callback: PerformanceObserverCallback(list, observer)</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_class_performanceobserverentrylist">Class: PerformanceObserverEntryList</a></span><ul>
<li><span class="stability_undefined"><a href="#perf_hooks_performanceobserverentrylist_getentries">performanceObserverEntryList.getEntries()</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performanceobserverentrylist_getentriesbyname_name_type">performanceObserverEntryList.getEntriesByName(name[, type])</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performanceobserverentrylist_getentriesbytype_type">performanceObserverEntryList.getEntriesByType(type)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#perf_hooks_performanceobserver_disconnect">performanceObserver.disconnect()</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_performanceobserver_observe_options">performanceObserver.observe(options)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#perf_hooks_examples">Examples</a></span><ul>
<li><span class="stability_undefined"><a href="#perf_hooks_measuring_the_duration_of_async_operations">Measuring the duration of async operations</a></span></li>
<li><span class="stability_undefined"><a href="#perf_hooks_measuring_how_long_it_takes_to_load_dependencies">Measuring how long it takes to load dependencies</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#process_process">Process</a></span><ul>
<li><span class="stability_undefined"><a href="#process_process_events">Process Events</a></span><ul>
<li><span class="stability_undefined"><a href="#process_event_beforeexit">Event: 'beforeExit'</a></span></li>
<li><span class="stability_undefined"><a href="#process_event_disconnect">Event: 'disconnect'</a></span></li>
<li><span class="stability_undefined"><a href="#process_event_exit">Event: 'exit'</a></span></li>
<li><span class="stability_undefined"><a href="#process_event_message">Event: 'message'</a></span></li>
<li><span class="stability_undefined"><a href="#process_event_rejectionhandled">Event: 'rejectionHandled'</a></span></li>
<li><span class="stability_undefined"><a href="#process_event_uncaughtexception">Event: 'uncaughtException'</a></span><ul>
<li><span class="stability_undefined"><a href="#process_warning_using_uncaughtexception_correctly">Warning: Using <code>'uncaughtException'</code> correctly</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#process_event_unhandledrejection">Event: 'unhandledRejection'</a></span></li>
<li><span class="stability_undefined"><a href="#process_event_warning">Event: 'warning'</a></span><ul>
<li><span class="stability_undefined"><a href="#process_emitting_custom_warnings">Emitting custom warnings</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#process_signal_events">Signal Events</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#process_process_abort">process.abort()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_arch">process.arch</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_argv">process.argv</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_argv0">process.argv0</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_channel">process.channel</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_chdir_directory">process.chdir(directory)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_config">process.config</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_connected">process.connected</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_cpuusage_previousvalue">process.cpuUsage([previousValue])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_cwd">process.cwd()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_debugport">process.debugPort</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_disconnect">process.disconnect()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_dlopen_module_filename_flags">process.dlopen(module, filename[, flags])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_emitwarning_warning_options">process.emitWarning(warning[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_emitwarning_warning_type_code_ctor">process.emitWarning(warning[, type[, code]][, ctor])</a></span><ul>
<li><span class="stability_undefined"><a href="#process_avoiding_duplicate_warnings">Avoiding duplicate warnings</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#process_process_env">process.env</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_execargv">process.execArgv</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_execpath">process.execPath</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_exit_code">process.exit([code])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_exitcode">process.exitCode</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_getegid">process.getegid()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_geteuid">process.geteuid()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_getgid">process.getgid()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_getgroups">process.getgroups()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_getuid">process.getuid()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_hasuncaughtexceptioncapturecallback">process.hasUncaughtExceptionCaptureCallback()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_hrtime_time">process.hrtime([time])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_initgroups_user_extra_group">process.initgroups(user, extra_group)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_kill_pid_signal">process.kill(pid[, signal])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_mainmodule">process.mainModule</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_memoryusage">process.memoryUsage()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_nexttick_callback_args">process.nextTick(callback[, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_nodeprecation">process.noDeprecation</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_pid">process.pid</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_platform">process.platform</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_ppid">process.ppid</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_release">process.release</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_send_message_sendhandle_options_callback">process.send(message[, sendHandle[, options]][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_setegid_id">process.setegid(id)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_seteuid_id">process.seteuid(id)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_setgid_id">process.setgid(id)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_setgroups_groups">process.setgroups(groups)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_setuid_id">process.setuid(id)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_setuncaughtexceptioncapturecallback_fn">process.setUncaughtExceptionCaptureCallback(fn)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_stderr">process.stderr</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_stdin">process.stdin</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_stdout">process.stdout</a></span><ul>
<li><span class="stability_undefined"><a href="#process_a_note_on_process_i_o">A note on process I/O</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#process_process_throwdeprecation">process.throwDeprecation</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_title">process.title</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_tracedeprecation">process.traceDeprecation</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_umask_mask">process.umask([mask])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_uptime">process.uptime()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_version">process.version</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_versions">process.versions</a></span></li>
<li><span class="stability_undefined"><a href="#process_exit_codes">Exit Codes</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#punycode_punycode">Punycode</a></span><ul>
<li><span class="stability_undefined"><a href="#punycode_punycode_decode_string">punycode.decode(string)</a></span></li>
<li><span class="stability_undefined"><a href="#punycode_punycode_encode_string">punycode.encode(string)</a></span></li>
<li><span class="stability_undefined"><a href="#punycode_punycode_toascii_domain">punycode.toASCII(domain)</a></span></li>
<li><span class="stability_undefined"><a href="#punycode_punycode_tounicode_domain">punycode.toUnicode(domain)</a></span></li>
<li><span class="stability_undefined"><a href="#punycode_punycode_ucs2">punycode.ucs2</a></span><ul>
<li><span class="stability_undefined"><a href="#punycode_punycode_ucs2_decode_string">punycode.ucs2.decode(string)</a></span></li>
<li><span class="stability_undefined"><a href="#punycode_punycode_ucs2_encode_codepoints">punycode.ucs2.encode(codePoints)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#punycode_punycode_version">punycode.version</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#querystring_query_string">Query String</a></span><ul>
<li><span class="stability_undefined"><a href="#querystring_querystring_escape_str">querystring.escape(str)</a></span></li>
<li><span class="stability_undefined"><a href="#querystring_querystring_parse_str_sep_eq_options">querystring.parse(str[, sep[, eq[, options]]])</a></span></li>
<li><span class="stability_undefined"><a href="#querystring_querystring_stringify_obj_sep_eq_options">querystring.stringify(obj[, sep[, eq[, options]]])</a></span></li>
<li><span class="stability_undefined"><a href="#querystring_querystring_unescape_str">querystring.unescape(str)</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#readline_readline">Readline</a></span><ul>
<li><span class="stability_undefined"><a href="#readline_class_interface">Class: Interface</a></span><ul>
<li><span class="stability_undefined"><a href="#readline_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_line">Event: 'line'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_pause">Event: 'pause'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_resume">Event: 'resume'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_sigcont">Event: 'SIGCONT'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_sigint">Event: 'SIGINT'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_sigtstp">Event: 'SIGTSTP'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_close">rl.close()</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_pause">rl.pause()</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_prompt_preservecursor">rl.prompt([preserveCursor])</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_question_query_callback">rl.question(query, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_resume">rl.resume()</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_setprompt_prompt">rl.setPrompt(prompt)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_write_data_key">rl.write(data[, key])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#readline_readline_clearline_stream_dir">readline.clearLine(stream, dir)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_readline_clearscreendown_stream">readline.clearScreenDown(stream)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_readline_createinterface_options">readline.createInterface(options)</a></span><ul>
<li><span class="stability_undefined"><a href="#readline_use_of_the_completer_function">Use of the <code>completer</code> Function</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#readline_readline_cursorto_stream_x_y">readline.cursorTo(stream, x, y)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_readline_emitkeypressevents_stream_interface">readline.emitKeypressEvents(stream[, interface])</a></span></li>
<li><span class="stability_undefined"><a href="#readline_readline_movecursor_stream_dx_dy">readline.moveCursor(stream, dx, dy)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_example_tiny_cli">Example: Tiny CLI</a></span></li>
<li><span class="stability_undefined"><a href="#readline_example_read_file_stream_line_by_line">Example: Read File Stream Line-by-Line</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#repl_repl">REPL</a></span><ul>
<li><span class="stability_undefined"><a href="#repl_design_and_features">Design and Features</a></span><ul>
<li><span class="stability_undefined"><a href="#repl_commands_and_special_keys">Commands and Special Keys</a></span></li>
<li><span class="stability_undefined"><a href="#repl_default_evaluation">Default Evaluation</a></span><ul>
<li><span class="stability_undefined"><a href="#repl_javascript_expressions">JavaScript Expressions</a></span></li>
<li><span class="stability_undefined"><a href="#repl_global_and_local_scope">Global and Local Scope</a></span></li>
<li><span class="stability_undefined"><a href="#repl_accessing_core_node_js_modules">Accessing Core Node.js Modules</a></span></li>
<li><span class="stability_undefined"><a href="#repl_assignment_of_the_underscore_variable">Assignment of the <code>_</code> (underscore) variable</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#repl_custom_evaluation_functions">Custom Evaluation Functions</a></span><ul>
<li><span class="stability_undefined"><a href="#repl_recoverable_errors">Recoverable Errors</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#repl_customizing_repl_output">Customizing REPL Output</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#repl_class_replserver">Class: REPLServer</a></span><ul>
<li><span class="stability_undefined"><a href="#repl_event_exit">Event: 'exit'</a></span></li>
<li><span class="stability_undefined"><a href="#repl_event_reset">Event: 'reset'</a></span></li>
<li><span class="stability_undefined"><a href="#repl_replserver_definecommand_keyword_cmd">replServer.defineCommand(keyword, cmd)</a></span></li>
<li><span class="stability_undefined"><a href="#repl_replserver_displayprompt_preservecursor">replServer.displayPrompt([preserveCursor])</a></span></li>
<li><span class="stability_undefined"><a href="#repl_replserver_clearbufferedcommand">replServer.clearBufferedCommand()</a></span></li>
<li><span class="stability_undefined"><a href="#repl_replserver_parsereplkeyword_keyword_rest">replServer.parseREPLKeyword(keyword, [rest])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#repl_repl_start_options">repl.start([options])</a></span></li>
<li><span class="stability_undefined"><a href="#repl_the_node_js_repl">The Node.js REPL</a></span><ul>
<li><span class="stability_undefined"><a href="#repl_environment_variable_options">Environment Variable Options</a></span></li>
<li><span class="stability_undefined"><a href="#repl_persistent_history">Persistent History</a></span><ul>
<li><span class="stability_0"><a href="#repl_node_repl_history_file">NODE_REPL_HISTORY_FILE</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#repl_using_the_node_js_repl_with_advanced_line_editors">Using the Node.js REPL with advanced line-editors</a></span></li>
<li><span class="stability_undefined"><a href="#repl_starting_multiple_repl_instances_against_a_single_running_instance">Starting multiple REPL instances against a single running instance</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#stream_stream">Stream</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_organization_of_this_document">Organization of this Document</a></span></li>
<li><span class="stability_undefined"><a href="#stream_types_of_streams">Types of Streams</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_object_mode">Object Mode</a></span></li>
<li><span class="stability_undefined"><a href="#stream_buffering">Buffering</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_api_for_stream_consumers">API for Stream Consumers</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_writable_streams">Writable Streams</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_class_stream_writable">Class: stream.Writable</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_drain">Event: 'drain'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_finish">Event: 'finish'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_pipe">Event: 'pipe'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_unpipe">Event: 'unpipe'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_cork">writable.cork()</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_end_chunk_encoding_callback">writable.end([chunk][, encoding][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_setdefaultencoding_encoding">writable.setDefaultEncoding(encoding)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_uncork">writable.uncork()</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_writablehighwatermark">writable.writableHighWaterMark</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_writablelength">writable.writableLength</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_write_chunk_encoding_callback">writable.write(chunk[, encoding][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_destroy_error">writable.destroy([error])</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_readable_streams">Readable Streams</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_two_modes">Two Modes</a></span></li>
<li><span class="stability_undefined"><a href="#stream_three_states">Three States</a></span></li>
<li><span class="stability_undefined"><a href="#stream_choose_one">Choose One</a></span></li>
<li><span class="stability_undefined"><a href="#stream_class_stream_readable">Class: stream.Readable</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_event_close_1">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_data">Event: 'data'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_end">Event: 'end'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_error_1">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_readable">Event: 'readable'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_ispaused">readable.isPaused()</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_pause">readable.pause()</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_pipe_destination_options">readable.pipe(destination[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_readablehighwatermark">readable.readableHighWaterMark</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_read_size">readable.read([size])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_readablelength">readable.readableLength</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_resume">readable.resume()</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_setencoding_encoding">readable.setEncoding(encoding)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_unpipe_destination">readable.unpipe([destination])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_unshift_chunk">readable.unshift(chunk)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_wrap_stream">readable.wrap(stream)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_destroy_error">readable.destroy([error])</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_duplex_and_transform_streams">Duplex and Transform Streams</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_class_stream_duplex">Class: stream.Duplex</a></span></li>
<li><span class="stability_undefined"><a href="#stream_class_stream_transform">Class: stream.Transform</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_transform_destroy_error">transform.destroy([error])</a></span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_api_for_stream_implementers">API for Stream Implementers</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_simplified_construction">Simplified Construction</a></span></li>
<li><span class="stability_undefined"><a href="#stream_implementing_a_writable_stream">Implementing a Writable Stream</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_constructor_new_stream_writable_options">Constructor: new stream.Writable([options])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_write_chunk_encoding_callback_1">writable._write(chunk, encoding, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_writev_chunks_callback">writable._writev(chunks, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_destroy_err_callback">writable._destroy(err, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_final_callback">writable._final(callback)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_errors_while_writing">Errors While Writing</a></span></li>
<li><span class="stability_undefined"><a href="#stream_an_example_writable_stream">An Example Writable Stream</a></span></li>
<li><span class="stability_undefined"><a href="#stream_decoding_buffers_in_a_writable_stream">Decoding buffers in a Writable Stream</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_implementing_a_readable_stream">Implementing a Readable Stream</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_new_stream_readable_options">new stream.Readable([options])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_read_size_1">readable._read(size)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_destroy_err_callback">readable._destroy(err, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_push_chunk_encoding">readable.push(chunk[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_errors_while_reading">Errors While Reading</a></span></li>
<li><span class="stability_undefined"><a href="#stream_an_example_counting_stream">An Example Counting Stream</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_implementing_a_duplex_stream">Implementing a Duplex Stream</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_new_stream_duplex_options">new stream.Duplex(options)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_an_example_duplex_stream">An Example Duplex Stream</a></span></li>
<li><span class="stability_undefined"><a href="#stream_object_mode_duplex_streams">Object Mode Duplex Streams</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_implementing_a_transform_stream">Implementing a Transform Stream</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_new_stream_transform_options">new stream.Transform([options])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_events_finish_and_end">Events: 'finish' and 'end'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_transform_flush_callback">transform._flush(callback)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_transform_transform_chunk_encoding_callback">transform._transform(chunk, encoding, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_class_stream_passthrough">Class: stream.PassThrough</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_additional_notes">Additional Notes</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_compatibility_with_older_node_js_versions">Compatibility with Older Node.js Versions</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_read_0"><code>readable.read(0)</code></a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_push"><code>readable.push('')</code></a></span></li>
<li><span class="stability_undefined"><a href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#string_decoder_string_decoder">String Decoder</a></span><ul>
<li><span class="stability_undefined"><a href="#string_decoder_class_new_stringdecoder_encoding">Class: new StringDecoder([encoding])</a></span><ul>
<li><span class="stability_undefined"><a href="#string_decoder_stringdecoder_end_buffer">stringDecoder.end([buffer])</a></span></li>
<li><span class="stability_undefined"><a href="#string_decoder_stringdecoder_write_buffer">stringDecoder.write(buffer)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#timers_timers">Timers</a></span><ul>
<li><span class="stability_undefined"><a href="#timers_class_immediate">Class: Immediate</a></span><ul>
<li><span class="stability_undefined"><a href="#timers_immediate_ref">immediate.ref()</a></span></li>
<li><span class="stability_undefined"><a href="#timers_immediate_unref">immediate.unref()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#timers_class_timeout">Class: Timeout</a></span><ul>
<li><span class="stability_undefined"><a href="#timers_timeout_ref">timeout.ref()</a></span></li>
<li><span class="stability_undefined"><a href="#timers_timeout_unref">timeout.unref()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#timers_scheduling_timers">Scheduling Timers</a></span><ul>
<li><span class="stability_undefined"><a href="#timers_setimmediate_callback_args">setImmediate(callback[, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#timers_setinterval_callback_delay_args">setInterval(callback, delay[, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#timers_settimeout_callback_delay_args">setTimeout(callback, delay[, ...args])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#timers_cancelling_timers">Cancelling Timers</a></span><ul>
<li><span class="stability_undefined"><a href="#timers_clearimmediate_immediate">clearImmediate(immediate)</a></span></li>
<li><span class="stability_undefined"><a href="#timers_clearinterval_timeout">clearInterval(timeout)</a></span></li>
<li><span class="stability_undefined"><a href="#timers_cleartimeout_timeout">clearTimeout(timeout)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#tls_tls_ssl">TLS (SSL)</a></span><ul>
<li><span class="stability_undefined"><a href="#tls_tls_ssl_concepts">TLS/SSL Concepts</a></span><ul>
<li><span class="stability_undefined"><a href="#tls_perfect_forward_secrecy">Perfect Forward Secrecy</a></span></li>
<li><span class="stability_undefined"><a href="#tls_alpn_npn_and_sni">ALPN, NPN, and SNI</a></span></li>
<li><span class="stability_undefined"><a href="#tls_client_initiated_renegotiation_attack_mitigation">Client-initiated renegotiation attack mitigation</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#tls_modifying_the_default_tls_cipher_suite">Modifying the Default TLS Cipher suite</a></span></li>
<li><span class="stability_undefined"><a href="#tls_class_tls_server">Class: tls.Server</a></span><ul>
<li><span class="stability_undefined"><a href="#tls_event_newsession">Event: 'newSession'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_event_ocsprequest">Event: 'OCSPRequest'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_event_resumesession">Event: 'resumeSession'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_event_secureconnection">Event: 'secureConnection'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_event_tlsclienterror">Event: 'tlsClientError'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_addcontext_hostname_context">server.addContext(hostname, context)</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_address">server.address()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_close_callback">server.close([callback])</a></span></li>
<li><span class="stability_0"><a href="#tls_server_connections">server.connections</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_getticketkeys">server.getTicketKeys()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_listen">server.listen()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_setticketkeys_keys">server.setTicketKeys(keys)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#tls_class_tls_tlssocket">Class: tls.TLSSocket</a></span><ul>
<li><span class="stability_undefined"><a href="#tls_new_tls_tlssocket_socket_options">new tls.TLSSocket(socket[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_event_ocspresponse">Event: 'OCSPResponse'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_event_secureconnect">Event: 'secureConnect'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_address">tlsSocket.address()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_authorizationerror">tlsSocket.authorizationError</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_authorized">tlsSocket.authorized</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_disablerenegotiation">tlsSocket.disableRenegotiation()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_encrypted">tlsSocket.encrypted</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_getcipher">tlsSocket.getCipher()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_getephemeralkeyinfo">tlsSocket.getEphemeralKeyInfo()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_getfinished">tlsSocket.getFinished()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_getpeercertificate_detailed">tlsSocket.getPeerCertificate([detailed])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_getpeerfinished">tlsSocket.getPeerFinished()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_getprotocol">tlsSocket.getProtocol()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_getsession">tlsSocket.getSession()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_gettlsticket">tlsSocket.getTLSTicket()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_localaddress">tlsSocket.localAddress</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_localport">tlsSocket.localPort</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_remoteaddress">tlsSocket.remoteAddress</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_remotefamily">tlsSocket.remoteFamily</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_remoteport">tlsSocket.remotePort</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_renegotiate_options_callback">tlsSocket.renegotiate(options, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_setmaxsendfragment_size">tlsSocket.setMaxSendFragment(size)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#tls_tls_checkserveridentity_host_cert">tls.checkServerIdentity(host, cert)</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_connect_options_callback">tls.connect(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_connect_path_options_callback">tls.connect(path[, options][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_connect_port_host_options_callback">tls.connect(port[, host][, options][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_createsecurecontext_options">tls.createSecureContext(options)</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_createserver_options_secureconnectionlistener">tls.createServer([options][, secureConnectionListener])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_getciphers">tls.getCiphers()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_default_ecdh_curve">tls.DEFAULT_ECDH_CURVE</a></span></li>
<li><span class="stability_undefined"><a href="#tls_deprecated_apis">Deprecated APIs</a></span><ul>
<li><span class="stability_0"><a href="#tls_class_cryptostream">Class: CryptoStream</a></span><ul>
<li><span class="stability_undefined"><a href="#tls_cryptostream_byteswritten">cryptoStream.bytesWritten</a></span></li>
</ul>
</li>
<li><span class="stability_0"><a href="#tls_class_securepair">Class: SecurePair</a></span><ul>
<li><span class="stability_undefined"><a href="#tls_event_secure">Event: 'secure'</a></span></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><span class="stability_undefined"><a href="#tracing_tracing">Tracing</a></span></li>
<li><span class="stability_2"><a href="#tty_tty">TTY</a></span><ul>
<li><span class="stability_undefined"><a href="#tty_class_tty_readstream">Class: tty.ReadStream</a></span><ul>
<li><span class="stability_undefined"><a href="#tty_readstream_israw">readStream.isRaw</a></span></li>
<li><span class="stability_undefined"><a href="#tty_readstream_istty">readStream.isTTY</a></span></li>
<li><span class="stability_undefined"><a href="#tty_readstream_setrawmode_mode">readStream.setRawMode(mode)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#tty_class_tty_writestream">Class: tty.WriteStream</a></span><ul>
<li><span class="stability_undefined"><a href="#tty_event_resize">Event: 'resize'</a></span></li>
<li><span class="stability_undefined"><a href="#tty_writestream_columns">writeStream.columns</a></span></li>
<li><span class="stability_undefined"><a href="#tty_writestream_istty">writeStream.isTTY</a></span></li>
<li><span class="stability_undefined"><a href="#tty_writestream_rows">writeStream.rows</a></span></li>
<li><span class="stability_undefined"><a href="#tty_writestream_getcolordepth_env">writeStream.getColorDepth([env])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#tty_tty_isatty_fd">tty.isatty(fd)</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#dgram_udp_datagram_sockets">UDP / Datagram Sockets</a></span><ul>
<li><span class="stability_undefined"><a href="#dgram_class_dgram_socket">Class: dgram.Socket</a></span><ul>
<li><span class="stability_undefined"><a href="#dgram_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_event_listening">Event: 'listening'</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_event_message">Event: 'message'</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_addmembership_multicastaddress_multicastinterface">socket.addMembership(multicastAddress[, multicastInterface])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_address">socket.address()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_bind_port_address_callback">socket.bind([port][, address][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_bind_options_callback">socket.bind(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_close_callback">socket.close([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_dropmembership_multicastaddress_multicastinterface">socket.dropMembership(multicastAddress[, multicastInterface])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_getrecvbuffersize">socket.getRecvBufferSize()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_getsendbuffersize">socket.getSendBufferSize()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_ref">socket.ref()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_send_msg_offset_length_port_address_callback">socket.send(msg, [offset, length,] port [, address] [, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setbroadcast_flag">socket.setBroadcast(flag)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setmulticastinterface_multicastinterface">socket.setMulticastInterface(multicastInterface)</a></span><ul>
<li><span class="stability_undefined"><a href="#dgram_examples_ipv6_outgoing_multicast_interface">Examples: IPv6 Outgoing Multicast Interface</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_example_ipv4_outgoing_multicast_interface">Example: IPv4 Outgoing Multicast Interface</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_call_results">Call Results</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#dgram_socket_setmulticastloopback_flag">socket.setMulticastLoopback(flag)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setmulticastttl_ttl">socket.setMulticastTTL(ttl)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setrecvbuffersize_size">socket.setRecvBufferSize(size)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setsendbuffersize_size">socket.setSendBufferSize(size)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setttl_ttl">socket.setTTL(ttl)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_unref">socket.unref()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_change_to_asynchronous_socket_bind_behavior">Change to asynchronous <code>socket.bind()</code> behavior</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#dgram_dgram_module_functions"><code>dgram</code> module functions</a></span><ul>
<li><span class="stability_undefined"><a href="#dgram_dgram_createsocket_options_callback">dgram.createSocket(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_dgram_createsocket_type_callback">dgram.createSocket(type[, callback])</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#url_url">URL</a></span><ul>
<li><span class="stability_undefined"><a href="#url_url_strings_and_url_objects">URL Strings and URL Objects</a></span></li>
<li><span class="stability_undefined"><a href="#url_the_whatwg_url_api">The WHATWG URL API</a></span><ul>
<li><span class="stability_undefined"><a href="#url_class_url">Class: URL</a></span><ul>
<li><span class="stability_undefined"><a href="#url_constructor_new_url_input_base">Constructor: new URL(input[, base])</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_hash">url.hash</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_host">url.host</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_hostname">url.hostname</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_href">url.href</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_origin">url.origin</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_password">url.password</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_pathname">url.pathname</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_port">url.port</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_protocol">url.protocol</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_search">url.search</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_searchparams">url.searchParams</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_username">url.username</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_tostring">url.toString()</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_tojson">url.toJSON()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#url_class_urlsearchparams">Class: URLSearchParams</a></span><ul>
<li><span class="stability_undefined"><a href="#url_constructor_new_urlsearchparams">Constructor: new URLSearchParams()</a></span></li>
<li><span class="stability_undefined"><a href="#url_constructor_new_urlsearchparams_string">Constructor: new URLSearchParams(string)</a></span></li>
<li><span class="stability_undefined"><a href="#url_constructor_new_urlsearchparams_obj">Constructor: new URLSearchParams(obj)</a></span></li>
<li><span class="stability_undefined"><a href="#url_constructor_new_urlsearchparams_iterable">Constructor: new URLSearchParams(iterable)</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_append_name_value">urlSearchParams.append(name, value)</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_delete_name">urlSearchParams.delete(name)</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_entries">urlSearchParams.entries()</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_foreach_fn_thisarg">urlSearchParams.forEach(fn[, thisArg])</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_get_name">urlSearchParams.get(name)</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_getall_name">urlSearchParams.getAll(name)</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_has_name">urlSearchParams.has(name)</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_keys">urlSearchParams.keys()</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_set_name_value">urlSearchParams.set(name, value)</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_sort">urlSearchParams.sort()</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_tostring">urlSearchParams.toString()</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_values">urlSearchParams.values()</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlsearchparams_iterator">urlSearchParams[@@iterator]()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#url_url_domaintoascii_domain">url.domainToASCII(domain)</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_domaintounicode_domain">url.domainToUnicode(domain)</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_format_url_options">url.format(URL[, options])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#url_legacy_url_api">Legacy URL API</a></span><ul>
<li><span class="stability_undefined"><a href="#url_legacy_urlobject">Legacy urlObject</a></span><ul>
<li><span class="stability_undefined"><a href="#url_urlobject_auth">urlObject.auth</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlobject_hash">urlObject.hash</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlobject_host">urlObject.host</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlobject_hostname">urlObject.hostname</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlobject_href">urlObject.href</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlobject_path">urlObject.path</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlobject_pathname">urlObject.pathname</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlobject_port">urlObject.port</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlobject_protocol">urlObject.protocol</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlobject_query">urlObject.query</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlobject_search">urlObject.search</a></span></li>
<li><span class="stability_undefined"><a href="#url_urlobject_slashes">urlObject.slashes</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#url_url_format_urlobject">url.format(urlObject)</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost">url.parse(urlString[, parseQueryString[, slashesDenoteHost]])</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_resolve_from_to">url.resolve(from, to)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#url_percent_encoding_in_urls">Percent-Encoding in URLs</a></span><ul>
<li><span class="stability_undefined"><a href="#url_legacy_api">Legacy API</a></span></li>
<li><span class="stability_undefined"><a href="#url_whatwg_api">WHATWG API</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#util_util">Util</a></span><ul>
<li><span class="stability_undefined"><a href="#util_util_callbackify_original">util.callbackify(original)</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_debuglog_section">util.debuglog(section)</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_deprecate_function_string">util.deprecate(function, string)</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_format_format_args">util.format(format[, ...args])</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_getsystemerrorname_err">util.getSystemErrorName(err)</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_inherits_constructor_superconstructor">util.inherits(constructor, superConstructor)</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_inspect_object_options">util.inspect(object[, options])</a></span><ul>
<li><span class="stability_undefined"><a href="#util_customizing_util_inspect_colors">Customizing <code>util.inspect</code> colors</a></span></li>
<li><span class="stability_undefined"><a href="#util_custom_inspection_functions_on_objects">Custom inspection functions on Objects</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_inspect_custom">util.inspect.custom</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_inspect_defaultoptions">util.inspect.defaultOptions</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#util_util_isdeepstrictequal_val1_val2">util.isDeepStrictEqual(val1, val2)</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_promisify_original">util.promisify(original)</a></span><ul>
<li><span class="stability_undefined"><a href="#util_custom_promisified_functions">Custom promisified functions</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_promisify_custom">util.promisify.custom</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#util_class_util_textdecoder">Class: util.TextDecoder</a></span><ul>
<li><span class="stability_undefined"><a href="#util_whatwg_supported_encodings">WHATWG Supported Encodings</a></span><ul>
<li><span class="stability_undefined"><a href="#util_encodings_supported_without_icu">Encodings Supported Without ICU</a></span></li>
<li><span class="stability_undefined"><a href="#util_encodings_supported_by_default_with_icu">Encodings Supported by Default (With ICU)</a></span></li>
<li><span class="stability_undefined"><a href="#util_encodings_requiring_full_icu_data">Encodings Requiring Full ICU Data</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#util_new_textdecoder_encoding_options">new TextDecoder([encoding[, options]])</a></span></li>
<li><span class="stability_undefined"><a href="#util_textdecoder_decode_input_options">textDecoder.decode([input[, options]])</a></span></li>
<li><span class="stability_undefined"><a href="#util_textdecoder_encoding">textDecoder.encoding</a></span></li>
<li><span class="stability_undefined"><a href="#util_textdecoder_fatal">textDecoder.fatal</a></span></li>
<li><span class="stability_undefined"><a href="#util_textdecoder_ignorebom">textDecoder.ignoreBOM</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#util_class_util_textencoder">Class: util.TextEncoder</a></span><ul>
<li><span class="stability_undefined"><a href="#util_textencoder_encode_input">textEncoder.encode([input])</a></span></li>
<li><span class="stability_undefined"><a href="#util_textencoder_encoding">textEncoder.encoding</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#util_deprecated_apis">Deprecated APIs</a></span><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><span class="stability_undefined"><a href="#v8_v8">V8</a></span><ul>
<li><span class="stability_undefined"><a href="#v8_v8_cacheddataversiontag">v8.cachedDataVersionTag()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_v8_getheapspacestatistics">v8.getHeapSpaceStatistics()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_v8_getheapstatistics">v8.getHeapStatistics()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_v8_setflagsfromstring_flags">v8.setFlagsFromString(flags)</a></span></li>
<li><span class="stability_1"><a href="#v8_serialization_api">Serialization API</a></span><ul>
<li><span class="stability_undefined"><a href="#v8_v8_serialize_value">v8.serialize(value)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_v8_deserialize_buffer">v8.deserialize(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_class_v8_serializer">class: v8.Serializer</a></span><ul>
<li><span class="stability_undefined"><a href="#v8_new_serializer">new Serializer()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_writeheader">serializer.writeHeader()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_writevalue_value">serializer.writeValue(value)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_releasebuffer">serializer.releaseBuffer()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_transferarraybuffer_id_arraybuffer">serializer.transferArrayBuffer(id, arrayBuffer)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_writeuint32_value">serializer.writeUint32(value)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_writeuint64_hi_lo">serializer.writeUint64(hi, lo)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_writedouble_value">serializer.writeDouble(value)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_writerawbytes_buffer">serializer.writeRawBytes(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_writehostobject_object">serializer._writeHostObject(object)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_getdatacloneerror_message">serializer._getDataCloneError(message)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_getsharedarraybufferid_sharedarraybuffer">serializer._getSharedArrayBufferId(sharedArrayBuffer)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_serializer_settreatarraybufferviewsashostobjects_flag">serializer._setTreatArrayBufferViewsAsHostObjects(flag)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#v8_class_v8_deserializer">class: v8.Deserializer</a></span><ul>
<li><span class="stability_undefined"><a href="#v8_new_deserializer_buffer">new Deserializer(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_deserializer_readheader">deserializer.readHeader()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_deserializer_readvalue">deserializer.readValue()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_deserializer_transferarraybuffer_id_arraybuffer">deserializer.transferArrayBuffer(id, arrayBuffer)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_deserializer_getwireformatversion">deserializer.getWireFormatVersion()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_deserializer_readuint32">deserializer.readUint32()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_deserializer_readuint64">deserializer.readUint64()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_deserializer_readdouble">deserializer.readDouble()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_deserializer_readrawbytes_length">deserializer.readRawBytes(length)</a></span></li>
<li><span class="stability_undefined"><a href="#v8_deserializer_readhostobject">deserializer._readHostObject()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#v8_class_v8_defaultserializer">class: v8.DefaultSerializer</a></span></li>
<li><span class="stability_undefined"><a href="#v8_class_v8_defaultdeserializer">class: v8.DefaultDeserializer</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#vm_vm_executing_javascript">VM (Executing JavaScript)</a></span><ul>
<li><span class="stability_1"><a href="#vm_class_vm_module">Class: vm.Module</a></span><ul>
<li><span class="stability_undefined"><a href="#vm_constructor_new_vm_module_code_options">Constructor: new vm.Module(code[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_module_dependencyspecifiers">module.dependencySpecifiers</a></span></li>
<li><span class="stability_undefined"><a href="#vm_module_error">module.error</a></span></li>
<li><span class="stability_undefined"><a href="#vm_module_linkingstatus">module.linkingStatus</a></span></li>
<li><span class="stability_undefined"><a href="#vm_module_namespace">module.namespace</a></span></li>
<li><span class="stability_undefined"><a href="#vm_module_status">module.status</a></span></li>
<li><span class="stability_undefined"><a href="#vm_module_url">module.url</a></span></li>
<li><span class="stability_undefined"><a href="#vm_module_evaluate_options">module.evaluate([options])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_module_instantiate">module.instantiate()</a></span></li>
<li><span class="stability_undefined"><a href="#vm_module_link_linker">module.link(linker)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#vm_class_vm_script">Class: vm.Script</a></span><ul>
<li><span class="stability_undefined"><a href="#vm_new_vm_script_code_options">new vm.Script(code, options)</a></span></li>
<li><span class="stability_undefined"><a href="#vm_script_runincontext_contextifiedsandbox_options">script.runInContext(contextifiedSandbox[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_script_runinnewcontext_sandbox_options">script.runInNewContext([sandbox[, options]])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_script_runinthiscontext_options">script.runInThisContext([options])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#vm_vm_createcontext_sandbox_options">vm.createContext([sandbox[, options]])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_vm_iscontext_sandbox">vm.isContext(sandbox)</a></span></li>
<li><span class="stability_undefined"><a href="#vm_vm_runincontext_code_contextifiedsandbox_options">vm.runInContext(code, contextifiedSandbox[, options])</a></span></li>
<li><span class="stability_0"><a href="#vm_vm_runindebugcontext_code">vm.runInDebugContext(code)</a></span></li>
<li><span class="stability_undefined"><a href="#vm_vm_runinnewcontext_code_sandbox_options">vm.runInNewContext(code[, sandbox][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_vm_runinthiscontext_code_options">vm.runInThisContext(code[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_example_running_an_http_server_within_a_vm">Example: Running an HTTP Server within a VM</a></span></li>
<li><span class="stability_undefined"><a href="#vm_what_does_it_mean_to_contextify_an_object">What does it mean to "contextify" an object?</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#zlib_zlib">Zlib</a></span><ul>
<li><span class="stability_undefined"><a href="#zlib_threadpool_usage">Threadpool Usage</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_compressing_http_requests_and_responses">Compressing HTTP requests and responses</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_memory_usage_tuning">Memory Usage Tuning</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_flushing">Flushing</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_constants">Constants</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_options">Class Options</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_deflate">Class: zlib.Deflate</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_deflateraw">Class: zlib.DeflateRaw</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_gunzip">Class: zlib.Gunzip</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_gzip">Class: zlib.Gzip</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_inflate">Class: zlib.Inflate</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_inflateraw">Class: zlib.InflateRaw</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_unzip">Class: zlib.Unzip</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_zlib">Class: zlib.Zlib</a></span><ul>
<li><span class="stability_undefined"><a href="#zlib_zlib_bytesread">zlib.bytesRead</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_close_callback">zlib.close([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_flush_kind_callback">zlib.flush([kind], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_params_level_strategy_callback">zlib.params(level, strategy, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_reset">zlib.reset()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#zlib_zlib_constants">zlib.constants</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_createdeflate_options">zlib.createDeflate([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_createdeflateraw_options">zlib.createDeflateRaw([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_creategunzip_options">zlib.createGunzip([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_creategzip_options">zlib.createGzip([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_createinflate_options">zlib.createInflate([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_createinflateraw_options">zlib.createInflateRaw([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_createunzip_options">zlib.createUnzip([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_convenience_methods">Convenience Methods</a></span><ul>
<li><span class="stability_undefined"><a href="#zlib_zlib_deflate_buffer_options_callback">zlib.deflate(buffer[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_deflatesync_buffer_options">zlib.deflateSync(buffer[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_deflateraw_buffer_options_callback">zlib.deflateRaw(buffer[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_deflaterawsync_buffer_options">zlib.deflateRawSync(buffer[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_gunzip_buffer_options_callback">zlib.gunzip(buffer[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_gunzipsync_buffer_options">zlib.gunzipSync(buffer[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_gzip_buffer_options_callback">zlib.gzip(buffer[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_gzipsync_buffer_options">zlib.gzipSync(buffer[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_inflate_buffer_options_callback">zlib.inflate(buffer[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_inflatesync_buffer_options">zlib.inflateSync(buffer[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_inflateraw_buffer_options_callback">zlib.inflateRaw(buffer[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_inflaterawsync_buffer_options">zlib.inflateRawSync(buffer[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_unzip_buffer_options_callback">zlib.unzip(buffer[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_unzipsync_buffer_options">zlib.unzipSync(buffer[, options])</a></span></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div id="apicontent">
<!--lint disable prohibited-strings-->
<!-- [start-include:documentation.md] -->
<h1>About this Documentation<span><a class="mark" href="#documentation_about_this_documentation" id="documentation_about_this_documentation">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<!-- type=misc -->
<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>
<!--type=misc-->
<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>
<div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated This feature is known to be problematic, and changes may be planned. Do not rely on it. Use of the feature may cause warnings to be emitted. Backwards compatibility across major versions should not be expected.</div><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental This feature is still under active development and subject to non-backwards compatible changes, or even 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><div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable The API has proven satisfactory. Compatibility with the npm ecosystem is a high priority, and will not be broken unless absolutely necessary.</div><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.html#process_process_stderr"><code>stderr</code></a> and may be handled by
attaching a listener to the <a href="process.html#process_event_warning"><code>process.on('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><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><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">open(2)</a> and <a href="http://man7.org/linux/man-pages/man2/read.2.html">read(2)</a> define the interface between user programs
and the underlying operating system. Node 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>Some syscalls, like <a href="http://man7.org/linux/man-pages/man2/lchown.2.html">lchown(2)</a>, are BSD-specific. That means, for
example, that <a href="fs.html#fs_fs_lchown_path_uid_gid_callback"><code>fs.lchown()</code></a> only works on macOS and other BSD-derived
systems, and is not available on Linux.</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
issue 4760</a>.</p>
<!-- [end-include:documentation.md] -->
<!-- [start-include:synopsis.md] -->
<h1>Usage<span><a class="mark" href="#synopsis_usage" id="synopsis_usage">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<!--type=misc-->
<p><code>node [options] [V8 options] [script.js | -e "script" | - ] [arguments]</code></p>
<p>Please see the <a href="cli.html#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> character 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>, navigate into it:
Project folder can be named base on 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="lang-console">$ mkdir ~/projects
$ cd ~/projects
</code></pre>
<p>Windows CMD:</p>
<pre><code class="lang-console">> mkdir %USERPROFILE%\projects
> cd %USERPROFILE%\projects
</code></pre>
<p>Windows PowerShell:</p>
<pre><code class="lang-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="lang-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="lang-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="lang-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>
<!-- [end-include:synopsis.md] -->
<!-- [start-include:assert.md] -->
<h1>Assert<span><a class="mark" href="#assert_assert" id="assert_assert">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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>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>
<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>
</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.html#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="lang-js">const assert = require('assert').strict;
</code></pre>
<p>Example error diff (the <code>expected</code>, <code>actual</code>, and <code>Lines skipped</code> will be on a
single row):</p>
<pre><code class="lang-js">const assert = require('assert').strict;
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
</code></pre>
<pre><code class="lang-diff">AssertionError [ERR_ASSERTION]: Input A expected to deepStrictEqual 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>
<div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use strict mode instead.</div><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="lang-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="lang-js">// WARNING: This does not throw an AssertionError!
assert.deepEqual(/a/gi, new Date());
</code></pre>
<h2>assert(value[, message])<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> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></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])<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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Error names and messages are now properly compared</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>Set and Map 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>
</table>
</details>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p><strong>Strict mode</strong></p>
<p>An alias of <a href="assert.html#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a>.</p>
<p><strong>Legacy mode</strong></p>
<div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="assert.html#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a> instead.</div><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.html#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="lang-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>. Maps and Sets 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="lang-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, object is equal to itself
assert.deepEqual(obj1, obj2);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
// values of b are different
assert.deepEqual(obj1, obj3);
// OK, objects are equal
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}
// Prototypes are ignored
</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.html#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])<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>
<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>NaN 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>Error names and messages are now properly compared</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>Set and Map 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>
</table>
</details>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></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>
<div class="signature"><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.html#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>Object properties are compared unordered.</li>
<li>Map keys and Set 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/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en/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>
</div><pre><code class="lang-js">const assert = require('assert').strict;
assert.deepStrictEqual({ a: 1 }, { a: '1' });
// AssertionError: { a: 1 } deepStrictEqual { a: '1' }
// because 1 !== '1' using SameValue comparison
// The following objects don't have own properties
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);
assert.deepStrictEqual(object, fakeDate);
// AssertionError: {} deepStrictEqual Date {}
// Different [[Prototype]]
assert.deepStrictEqual(date, fakeDate);
// AssertionError: 2017-03-11T14:25:31.849Z deepStrictEqual Date {}
// Different type tags
assert.deepStrictEqual(NaN, NaN);
// OK, because of the SameValue comparison
assert.deepStrictEqual(new Number(1), new Number(2));
// Fails because the wrapped number is unwrapped and compared as well.
assert.deepStrictEqual(new String('foo'), Object('foo'));
// OK because the object and the string are identical when unwrapped.
assert.deepStrictEqual(-0, -0);
// OK
assert.deepStrictEqual(0, -0);
// AssertionError: 0 deepStrictEqual -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 });
// Fails because symbol1 !== symbol2!
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
assert.deepStrictEqual(weakMap1, weakMap3);
// Fails because weakMap3 has a property that weakMap1 does not contain!
</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.html#errors_class_error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
<h2>assert.doesNotThrow(block[, error][, message])<span><a class="mark" href="#assert_assert_doesnotthrow_block_error_message" id="assert_assert_doesnotthrow_block_error_message">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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>
</table>
</details>
</div><ul>
<li><code>block</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> <span class="type"><any></span></li>
</ul>
<p>Asserts that the function <code>block</code> does not throw an error. See
<a href="#assert_assert_throws_block_error_message"><code>assert.throws()</code></a> for more details.</p>
<p>Please note: Using <code>assert.doesNotThrow()</code> is actually not useful because there
is no benefit by 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>block</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>The following, for instance, will throw the <a href="errors.html#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="lang-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 (TypeError)..':</p>
<!-- eslint-disable no-restricted-syntax -->
<pre><code class="lang-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="lang-js">assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
TypeError,
'Whoops'
);
// Throws: AssertionError: Got unwanted exception (TypeError). Whoops
</code></pre>
<h2>assert.equal(actual, expected[, message])<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> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></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>
<div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual()</code></a> instead.</div><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="lang-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.html#errors_class_error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
<h2>assert.fail([message])<span><a class="mark" href="#assert_assert_fail_message" id="assert_assert_fail_message">#</a></span></h2>
<h2>assert.fail(actual, expected[, message[, operator[, stackStartFunction]]])<span><a class="mark" href="#assert_assert_fail_actual_expected_message_operator_stackstartfunction" id="assert_assert_fail_actual_expected_message_operator_stackstartfunction">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span> <strong>Default:</strong> <code>'Failed'</code></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> '!='</li>
<li><code>stackStartFunction</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>Throws an <code>AssertionError</code>. 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
the <code>message</code> parameter is an instance of an <a href="errors.html#errors_class_error"><code>Error</code></a> then it will be thrown
instead of the <code>AssertionError</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 only it will be used as the error message, the other arguments will be
stored as properties on the thrown object. If <code>stackStartFunction</code> is provided,
all stack frames above that function will be removed from stacktrace (see
<a href="errors.html#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="lang-js">const assert = require('assert').strict;
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><em>Note</em>: In the last two cases <code>actual</code>, <code>expected</code>, and <code>operator</code> have no
influence on the error message.</p>
<pre><code class="lang-js">assert.fail();
// AssertionError [ERR_ASSERTION]: Failed
assert.fail('boom');
// AssertionError [ERR_ASSERTION]: boom
assert.fail('a', 'b');
// AssertionError [ERR_ASSERTION]: 'a' != 'b'
</code></pre>
<p>Example use of <code>stackStartFunction</code> for truncating the exception's stacktrace:</p>
<pre><code class="lang-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)<span><a class="mark" href="#assert_assert_iferror_value" id="assert_assert_iferror_value">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.97</span>
</div><ul>
<li><code>value</code> <span class="type"><any></span></li>
</ul>
<p>Throws <code>value</code> if <code>value</code> is truthy. This is useful when testing the <code>error</code>
argument in callbacks.</p>
<pre><code class="lang-js">const assert = require('assert').strict;
assert.ifError(null);
// OK
assert.ifError(0);
// OK
assert.ifError(1);
// Throws 1
assert.ifError('error');
// Throws 'error'
assert.ifError(new Error());
// Throws Error
</code></pre>
<h2>assert.notDeepEqual(actual, expected[, message])<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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Error names and messages are now properly compared</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>Set and Map 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>
</table>
</details>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></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>
<div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#assert_assert_notdeepstrictequal_actual_expected_message"><code>assert.notDeepStrictEqual()</code></a> instead.</div><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="lang-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: obj1 and obj2 are not deeply equal
assert.notDeepEqual(obj1, obj3);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
assert.notDeepEqual(obj1, obj4);
// OK: obj1 and obj4 are not deeply equal
</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.html#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])<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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>-0 and +0 are not considered equal anymore.</p>
</td></tr>
<tr><td>v9.0.0</td>
<td><p>NaN 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>Error names and messages are now properly compared</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>Set and Map 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>
</table>
</details>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p>Tests for deep strict inequality. Opposite of <a href="assert.html#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a>.</p>
<pre><code class="lang-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.html#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])<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> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></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>
<div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#assert_assert_notstrictequal_actual_expected_message"><code>assert.notStrictEqual()</code></a> instead.</div><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="lang-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.html#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])<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">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></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="lang-js">const assert = require('assert').strict;
assert.notStrictEqual(1, 2);
// OK
assert.notStrictEqual(1, 1);
// AssertionError: 1 !== 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.html#errors_class_error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
<h2>assert.ok(value[, message])<span><a class="mark" href="#assert_assert_ok_value_message" id="assert_assert_ok_value_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>value</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></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.html#errors_class_error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
<pre><code class="lang-js">const assert = require('assert').strict;
assert.ok(true);
// OK
assert.ok(1);
// OK
assert.ok(false);
// throws "AssertionError: false == true"
assert.ok(0);
// throws "AssertionError: 0 == true"
assert.ok(false, 'it\'s false');
// throws "AssertionError: it's false"
</code></pre>
<h2>assert.strictEqual(actual, expected[, message])<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">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></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="lang-js">const assert = require('assert').strict;
assert.strictEqual(1, 2);
// AssertionError: 1 === 2
assert.strictEqual(1, 1);
// OK
assert.strictEqual(1, '1');
// AssertionError: 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.html#errors_class_error"><code>Error</code></a> then it will be thrown
instead of the <code>AssertionError</code>.</p>
<h2>assert.throws(block[, error][, message])<span><a class="mark" href="#assert_assert_throws_block_error_message" id="assert_assert_throws_block_error_message">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tr><th>Version</th><th>Changes</th></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>
</table>
</details>
</div><ul>
<li><code>block</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> | <span class="type"><object></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p>Expects the function <code>block</code> to throw an error.</p>
<p>If specified, <code>error</code> can be a constructor, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>, a validation
function, or an object where each property will be tested for.</p>
<p>If specified, <code>message</code> will be the message provided by the <code>AssertionError</code> if
the block fails to throw.</p>
<p>Validate instanceof using constructor:</p>
<pre><code class="lang-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="lang-js">assert.throws(
() => {
throw new Error('Wrong value');
},
/^Error: Wrong value$/
);
</code></pre>
<p>Custom error validation:</p>
<pre><code class="lang-js">assert.throws(
() => {
throw new Error('Wrong value');
},
function(err) {
if ((err instanceof Error) && /value/.test(err)) {
return true;
}
},
'unexpected error'
);
</code></pre>
<p>Custom error object / error instance:</p>
<pre><code class="lang-js">assert.throws(
() => {
const err = new TypeError('Wrong value');
err.code = 404;
throw err;
},
{
name: 'TypeError',
message: 'Wrong value'
// Note that only properties on the error object will be tested!
}
);
</code></pre>
<p>Note that <code>error</code> can not 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 below carefully if using a string as the second argument gets
considered:</p>
<!-- eslint-disable no-restricted-syntax -->
<pre><code class="lang-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.
// In that case both cases do not throw as neither is going to try to
// match for the error message thrown by the input function!
assert.throws(throwingFirst, 'Second');
assert.throws(throwingSecond, 'Second');
// 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 a 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>
<h2>Caveats<span><a class="mark" href="#assert_caveats" id="assert_caveats">#</a></span></h2>
<p>For the following cases, consider using ES2015 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is"><code>Object.is()</code></a>,
which uses the <a href="https://tc39.github.io/ecma262/#sec-samevaluezero">SameValueZero</a> comparison.</p>
<pre><code class="lang-js">const a = 0;
const b = -a;
assert.notStrictEqual(a, b);
// AssertionError: 0 !== -0
// Strict Equality Comparison doesn't distinguish between -0 and +0...
assert(!Object.is(a, b));
// but Object.is() does!
const str1 = 'foo';
const str2 = 'foo';
assert.strictEqual(str1 / 1, str2 / 1);
// AssertionError: NaN === NaN
// Strict Equality Comparison can't be used to check NaN...
assert(Object.is(str1 / 1, str2 / 1));
// but Object.is() can!
</code></pre>
<p>For more information, 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>
<!-- [end-include:assert.md] -->
<!-- [start-include:async_hooks.md] -->
<h1>Async Hooks<span><a class="mark" href="#async_hooks_async_hooks" id="async_hooks_async_hooks">#</a></span></h1>
<!--introduced_in=v8.1.0-->
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><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="lang-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. AsyncHook does not
explicitly distinguish between these different cases but will represent them
as the abstract concept that is a resource.</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="lang-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><code>async_hooks.createHook(callbacks)</code><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><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<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.html#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="lang-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="lang-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.writeSync(1, msg)</code>. This will print to
stdout because <code>1</code> is the file descriptor for stdout and will not invoke
AsyncHooks recursively because it is synchronous.</p>
<pre><code class="lang-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.writeSync(1, `${util.format(...args)}\n`);
}
</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><code>asyncHook.enable()</code><span><a class="mark" href="#async_hooks_asynchook_enable" id="async_hooks_asynchook_enable">#</a></span></h4>
<div class="signature"><ul>
<li>Returns: <a href="async_hooks.html#async_hooks_async_hooks_createhook_callbacks" class="type"><AsyncHook></a> A reference to <code>asyncHook</code>.</li>
</ul>
</div><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="lang-js">const async_hooks = require('async_hooks');
const hook = async_hooks.createHook(callbacks).enable();
</code></pre>
<h4><code>asyncHook.disable()</code><span><a class="mark" href="#async_hooks_asynchook_disable" id="async_hooks_asynchook_disable">#</a></span></h4>
<div class="signature"><ul>
<li>Returns: <a href="async_hooks.html#async_hooks_async_hooks_createhook_callbacks" class="type"><AsyncHook></a> A reference to <code>asyncHook</code>.</li>
</ul>
</div><p>Disable the callbacks for a given <code>AsyncHook</code> instance from the global pool of
AsyncHook callbacks to be executed. Once a hook has been disabled it will not
be called again until enabled.</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><code>init(asyncId, type, triggerAsyncId, resource)</code><span><a class="mark" href="#async_hooks_init_asyncid_type_triggerasyncid_resource" id="async_hooks_init_asyncid_type_triggerasyncid_resource">#</a></span></h5>
<div class="signature"><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>
</div><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="lang-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 process.</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="lang-text">FSEVENTWRAP, FSREQWRAP, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPPARSER,
JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP, SHUTDOWNWRAP,
SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVER, 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><em>Note:</em> 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>triggerId</code><span><a class="mark" href="#async_hooks_triggerid" id="async_hooks_triggerid">#</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="lang-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="lang-console">TCPSERVERWRAP(2): trigger: 1 execution: 1
TCPWRAP(4): trigger: 2 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 (side note: a <code>executionAsyncId()</code> of
<code>0</code> means it's 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
hostname 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 Promise that is being initialized, and a <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 Promise 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="lang-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.writeSync(1, `${indentStr}before: ${asyncId}\n`);
indent += 2;
},
after(asyncId) {
indent -= 2;
const indentStr = ' '.repeat(indent);
fs.writeSync(1, `${indentStr}after: ${asyncId}\n`);
},
destroy(asyncId) {
const indentStr = ' '.repeat(indent);
fs.writeSync(1, `${indentStr}destroy: ${asyncId}\n`);
},
}).enable();
require('net').createServer(() => {}).listen(8080, () => {
// Let's wait 10ms before logging the server started.
setTimeout(() => {
console.log('>>>', async_hooks.executionAsyncId());
}, 10);
});
</code></pre>
<p>Output from only starting the server:</p>
<pre><code class="lang-console">TCPSERVERWRAP(2): trigger: 1 execution: 1
TickObject(3): trigger: 2 execution: 1
before: 3
Timeout(4): trigger: 3 execution: 3
TIMERWRAP(5): trigger: 3 execution: 3
after: 3
destroy: 3
before: 5
before: 4
TTYWRAP(6): trigger: 4 execution: 4
SIGNALWRAP(7): trigger: 4 execution: 4
TTYWRAP(8): trigger: 4 execution: 4
>>> 4
TickObject(9): trigger: 4 execution: 4
after: 4
after: 5
before: 9
after: 9
destroy: 4
destroy: 9
destroy: 5
</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="lang-console">TTYWRAP(6) -> Timeout(4) -> TIMERWRAP(5) -> TickObject(3) -> 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><code>before(asyncId)</code><span><a class="mark" href="#async_hooks_before_asyncid" id="async_hooks_before_asyncid">#</a></span></h5>
<div class="signature"><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>
</div><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><code>after(asyncId)</code><span><a class="mark" href="#async_hooks_after_asyncid" id="async_hooks_after_asyncid">#</a></span></h5>
<div class="signature"><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>
</div><p>Called immediately after the callback specified in <code>before</code> is completed.</p>
<p><em>Note:</em> 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><code>destroy(asyncId)</code><span><a class="mark" href="#async_hooks_destroy_asyncid" id="async_hooks_destroy_asyncid">#</a></span></h5>
<div class="signature"><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>
</div><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><em>Note:</em> 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><code>promiseResolve(asyncId)</code><span><a class="mark" href="#async_hooks_promiseresolve_asyncid" id="async_hooks_promiseresolve_asyncid">#</a></span></h5>
<div class="signature"><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>
</div><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><em>Note:</em> This does not necessarily mean that the <code>Promise</code> is 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="lang-js">new Promise((resolve) => resolve(true)).then((a) => {});
</code></pre>
<p>calls the following callbacks:</p>
<pre><code class="lang-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><code>async_hooks.executionAsyncId()</code><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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.2.0</td>
<td><p>Renamed from currentId</p>
</td></tr>
<tr><td>v8.1.0</td>
<td><p><span>Added in: v8.1.0</span></p>
</td></tr>
</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="lang-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="lang-js">const server = net.createServer(function onConnection(conn) {
// Returns the ID of the server, not of the new connection, because the
// onConnection callback runs in the execution scope of the server's
// MakeCallback().
async_hooks.executionAsyncId();
}).listen(port, function onListening() {
// Returns the ID of a TickObject (i.e. process.nextTick()) because all
// callbacks passed to .listen() are wrapped in a nextTick().
async_hooks.executionAsyncId();
});
</code></pre>
<p>Note that promise contexts may not get precise executionAsyncIds by default.
See the section on <a href="#async_hooks_promise_execution_tracking">promise execution tracking</a>.</p>
<h4><code>async_hooks.triggerAsyncId()</code><span><a class="mark" href="#async_hooks_async_hooks_triggerasyncid" id="async_hooks_async_hooks_triggerasyncid">#</a></span></h4>
<div class="signature"><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>
</div><pre><code class="lang-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 triggerAsyncIds 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 asyncIds due to the relatively
expensive nature of the <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk">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>
<p>Here's an example:</p>
<pre><code class="lang-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 triggerAsyncId value is 0, 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. Example:</p>
<pre><code class="lang-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 asyncId 6 and the latter got asyncId 7.
During the execution of the <code>then</code> callback, we are executing in the context of
promise with asyncId 7. This promise was triggered by async resource 6.</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">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><code>class AsyncResource()</code><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="lang-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();
// Call AsyncHooks before callbacks.
// Deprecated: Use asyncResource.runInAsyncScope instead.
asyncResource.emitBefore();
// Call AsyncHooks after callbacks.
// Deprecated: Use asyncResource.runInAsyncScope instead.
asyncResource.emitAfter();
</code></pre>
<h4><code>AsyncResource(type[, options])</code><span><a class="mark" href="#async_hooks_asyncresource_type_options" id="async_hooks_asyncresource_type_options">#</a></span></h4>
<div class="signature"><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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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 asyncId is retrieved
and the sensitive API's <code>emitDestroy</code> is called with it.
<strong>Default:</strong> <code>false</code></li>
</ul>
</li>
</ul>
</div><p>Example usage:</p>
<pre><code class="lang-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><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code><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> <span class="type"><any></span> The receiver to be used for the function call.</li>
<li><code>...args</code> <span class="type"><any></span> 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><code>asyncResource.emitBefore()</code><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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="async_hooks.html#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args"><code>asyncResource.runInAsyncScope()</code></a> instead.</div><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><code>asyncResource.emitAfter()</code><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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="async_hooks.html#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args"><code>asyncResource.runInAsyncScope()</code></a> instead.</div><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><code>asyncResource.emitDestroy()</code><span><a class="mark" href="#async_hooks_asyncresource_emitdestroy" id="async_hooks_asyncresource_emitdestroy">#</a></span></h4>
<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><code>asyncResource.asyncId()</code><span><a class="mark" href="#async_hooks_asyncresource_asyncid" id="async_hooks_asyncresource_asyncid">#</a></span></h4>
<div class="signature"><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>
</div><h4><code>asyncResource.triggerAsyncId()</code><span><a class="mark" href="#async_hooks_asyncresource_triggerasyncid" id="async_hooks_asyncresource_triggerasyncid">#</a></span></h4>
<div class="signature"><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>
</div><!-- [end-include:async_hooks.md] -->
<!-- [start-include:buffer.md] -->
<h1>Buffer<span><a class="mark" href="#buffer_buffer" id="buffer_buffer">#</a></span></h1>
<!--introduced_in=v0.1.90-->
<!--lint disable maximum-line-length-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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 make it possible to interact with
octet streams in the context of things like TCP streams and file system
operations.</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="lang-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.html#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.html#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="lang-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>
<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>
</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="lang-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
win-1252-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>
<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>
</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 TypeArray object's <code>.buffer</code> property.</p>
<pre><code class="lang-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="lang-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.html#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a></li>
<li><a href="buffer.html#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="lang-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>
<tr><th>Version</th><th>Changes</th></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>
</table>
</details>
</div><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="buffer.html#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a> instead.</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> 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="lang-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>
<tr><th>Version</th><th>Changes</th></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>
</table>
</details>
</div><div class="api_stability api_stability_0"><a href="documentation.html#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><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="lang-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>
<tr><th>Version</th><th>Changes</th></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>
</table>
</details>
</div><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="buffer.html#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a> instead.</div><ul>
<li><code>buffer</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> An existing <code>Buffer</code> to copy data from.</li>
</ul>
<p>Copies the passed <code>buffer</code> data onto a new <code>Buffer</code> instance.</p>
<pre><code class="lang-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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>new Buffer(size) 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>
</table>
</details>
</div><div class="api_stability api_stability_0"><a href="documentation.html#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><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 the <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 <a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a> will be
thrown. A zero-length <code>Buffer</code> will be 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="lang-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>
<tr><th>Version</th><th>Changes</th></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>
</table>
</details>
</div><div class="api_stability api_stability_0"><a href="documentation.html#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><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="lang-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]])<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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.2.1</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>
</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.html#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="lang-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 the <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 <a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a> will be
thrown. A zero-length <code>Buffer</code> will be 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="lang-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="lang-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)<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>
<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>
</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 the <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 <a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a> will be
thrown. A zero-length <code>Buffer</code> will be 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="lang-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)<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 the <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 <a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a> will be
thrown. A zero-length <code>Buffer</code> will be 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="lang-js">// Need to keep around a few small chunks of memory
const store = [];
socket.on('readable', () => {
const data = socket.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])<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>
<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>
</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.html#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="lang-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)<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>
<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>
</table>
</details>
</div><ul>
<li><code>buf1</code> <a href="buffer.html#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.html#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="lang-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])<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>
<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>
</table>
</details>
</div><ul>
<li><code>list</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></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.html#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="lang-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)<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/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>Allocates a new <code>Buffer</code> using an <code>array</code> of octets.</p>
<pre><code class="lang-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]])<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="lang-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="lang-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)<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.html#buffer_class_buffer" class="type"><Buffer></a> An existing <code>Buffer</code> to copy data from.</li>
</ul>
<p>Copies the passed <code>buffer</code> data onto a new <code>Buffer</code> instance.</p>
<pre><code class="lang-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(string[, encoding])<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="lang-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.from(object[, offsetOrEncoding[, length]])<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="lang-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="lang-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.isBuffer(obj)<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)<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<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 number of bytes used to determine the size 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="lang-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>
<p>The <code>buffer</code> property references the underlying <code>ArrayBuffer</code> object based on
which this Buffer object is created.</p>
<pre><code class="lang-js">const arrayBuffer = new ArrayBuffer(16);
const buffer = Buffer.from(arrayBuffer);
console.log(buffer.buffer === arrayBuffer);
// Prints: true
</code></pre>
<h3>buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])<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>
<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>
</table>
</details>
</div><ul>
<li><code>target</code> <a href="buffer.html#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 compare to.</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="lang-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="lang-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 <code>RangeError</code> will be 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]]])<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.html#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
copying to. <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> at which to begin copying from.
<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="lang-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="lang-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="lang-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)<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>
<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>
</table>
</details>
</div><ul>
<li><code>otherBuffer</code> <a href="buffer.html#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> to compare to.</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="lang-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])<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>
<tr><th>Version</th><th>Changes</th></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>
</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.html#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 to fill <code>buf</code> with.</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> If <code>value</code> is a string, this is its encoding.
<strong>Default:</strong> <code>'utf8'</code></li>
<li>Returns: <a href="buffer.html#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. This is meant to be a small simplification to
allow the creation and filling of a <code>Buffer</code> to be done on a single line.</p>
<pre><code class="lang-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 or Integer.</p>
<p>If the final write of a <code>fill()</code> operation falls on a multi-byte character,
then only the first bytes of that character that fit into <code>buf</code> are written.</p>
<pre><code class="lang-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.</p>
<p>If no valid fill data remains, then the buffer is either zero-filled or no
filling is performed, depending on the input type. That behavior is dictated by
compatibility reasons and was changed to throwing an exception in Node.js v10,
so it's not recommended to rely on that.</p>
<pre><code class="lang-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])<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.html#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="lang-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])<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>
<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>
</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.html#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 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 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="lang-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. Any arguments
that coerce to <code>NaN</code> or 0, like <code>{}</code>, <code>[]</code>, <code>null</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/indexOf"><code>String#indexOf()</code></a>.</p>
<pre><code class="lang-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="lang-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])<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>
<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>
</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.html#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 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 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 <code>buf</code> is searched from back to front
instead of front to back.</p>
<pre><code class="lang-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="lang-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="lang-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="lang-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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_buf_buffer"><code>buf.buffer</code></a> instead.</div><p>The <code>buf.parent</code> property is a deprecated alias for <code>buf.buffer</code>.</p>
<h3>buf.readDoubleBE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readdoublebe_offset_noassert" id="buffer_buf_readdoublebe_offset_noassert">#</a></span></h3>
<h3>buf.readDoubleLE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readdoublele_offset_noassert" id="buffer_buf_readdoublele_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.15</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>.</li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>offset</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows <code>offset</code> to be beyond the end of <code>buf</code>, but
the resulting behavior is undefined.</p>
<pre><code class="lang-js">const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleBE());
// Prints: 8.20788039913184e-304
console.log(buf.readDoubleLE());
// Prints: 5.447603722011605e-270
console.log(buf.readDoubleLE(1));
// Throws an exception: RangeError: Index out of range
console.log(buf.readDoubleLE(1, true));
// Warning: reads passed end of buffer!
// This will result in a segmentation fault! Don't do this!
</code></pre>
<h3>buf.readFloatBE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readfloatbe_offset_noassert" id="buffer_buf_readfloatbe_offset_noassert">#</a></span></h3>
<h3>buf.readFloatLE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readfloatle_offset_noassert" id="buffer_buf_readfloatle_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.15</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 - 4</code>.</li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>offset</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows <code>offset</code> to be beyond the end of <code>buf</code>, but
the resulting behavior is undefined.</p>
<pre><code class="lang-js">const buf = Buffer.from([1, 2, 3, 4]);
console.log(buf.readFloatBE());
// Prints: 2.387939260590663e-38
console.log(buf.readFloatLE());
// Prints: 1.539989614439558e-36
console.log(buf.readFloatLE(1));
// Throws an exception: RangeError: Index out of range
console.log(buf.readFloatLE(1, true));
// Warning: reads passed end of buffer!
// This will result in a segmentation fault! Don't do this!
</code></pre>
<h3>buf.readInt8(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readint8_offset_noassert" id="buffer_buf_readint8_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.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 - 1</code>.</li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>offset</code> validation? <strong>Default:</strong> <code>false</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>Setting <code>noAssert</code> to <code>true</code> allows <code>offset</code> to be beyond the end of <code>buf</code>, but
the resulting behavior is undefined.</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<pre><code class="lang-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 an exception: RangeError: Index out of range
</code></pre>
<h3>buf.readInt16BE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readint16be_offset_noassert" id="buffer_buf_readint16be_offset_noassert">#</a></span></h3>
<h3>buf.readInt16LE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readint16le_offset_noassert" id="buffer_buf_readint16le_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.5</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 - 2</code>.</li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>offset</code> validation? <strong>Default:</strong> <code>false</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>Setting <code>noAssert</code> to <code>true</code> allows <code>offset</code> to be beyond the end of <code>buf</code>, but
the resulting behavior is undefined.</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<pre><code class="lang-js">const buf = Buffer.from([0, 5]);
console.log(buf.readInt16BE());
// Prints: 5
console.log(buf.readInt16LE());
// Prints: 1280
console.log(buf.readInt16LE(1));
// Throws an exception: RangeError: Index out of range
</code></pre>
<h3>buf.readInt32BE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readint32be_offset_noassert" id="buffer_buf_readint32be_offset_noassert">#</a></span></h3>
<h3>buf.readInt32LE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readint32le_offset_noassert" id="buffer_buf_readint32le_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.5</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 - 4</code>.</li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>offset</code> validation? <strong>Default:</strong> <code>false</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>Setting <code>noAssert</code> to <code>true</code> allows <code>offset</code> to be beyond the end of <code>buf</code>, but
the resulting behavior is undefined.</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<pre><code class="lang-js">const buf = Buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32BE());
// Prints: 5
console.log(buf.readInt32LE());
// Prints: 83886080
console.log(buf.readInt32LE(1));
// Throws an exception: RangeError: Index out of range
</code></pre>
<h3>buf.readIntBE(offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_readintbe_offset_bytelength_noassert" id="buffer_buf_readintbe_offset_bytelength_noassert">#</a></span></h3>
<h3>buf.readIntLE(offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_readintle_offset_bytelength_noassert" id="buffer_buf_readintle_offset_bytelength_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.15</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 - 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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>offset</code> and <code>byteLength</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows <code>offset</code> to be beyond the end of <code>buf</code>, but
the resulting behavior is undefined.</p>
<pre><code class="lang-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: RangeError [ERR_INDEX_OUT_OF_RANGE]: Index out of range
</code></pre>
<h3>buf.readUInt8(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readuint8_offset_noassert" id="buffer_buf_readuint8_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.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 - 1</code>.</li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>offset</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows <code>offset</code> to be beyond the end of <code>buf</code>, but
the resulting behavior is undefined.</p>
<pre><code class="lang-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 an exception: RangeError: Index out of range
</code></pre>
<h3>buf.readUInt16BE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readuint16be_offset_noassert" id="buffer_buf_readuint16be_offset_noassert">#</a></span></h3>
<h3>buf.readUInt16LE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readuint16le_offset_noassert" id="buffer_buf_readuint16le_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.5</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 - 2</code>.</li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>offset</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows <code>offset</code> to be beyond the end of <code>buf</code>, but
the resulting behavior is undefined.</p>
<pre><code class="lang-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 an exception: RangeError: Index out of range
</code></pre>
<h3>buf.readUInt32BE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readuint32be_offset_noassert" id="buffer_buf_readuint32be_offset_noassert">#</a></span></h3>
<h3>buf.readUInt32LE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readuint32le_offset_noassert" id="buffer_buf_readuint32le_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.5</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 - 4</code>.</li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>offset</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows <code>offset</code> to be beyond the end of <code>buf</code>, but
the resulting behavior is undefined.</p>
<pre><code class="lang-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 an exception: RangeError: Index out of range
</code></pre>
<h3>buf.readUIntBE(offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_readuintbe_offset_bytelength_noassert" id="buffer_buf_readuintbe_offset_bytelength_noassert">#</a></span></h3>
<h3>buf.readUIntLE(offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_readuintle_offset_bytelength_noassert" id="buffer_buf_readuintle_offset_bytelength_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.15</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 - 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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>offset</code> and <code>byteLength</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows <code>offset</code> to be beyond the end of <code>buf</code>, but
the resulting behavior is undefined.</p>
<pre><code class="lang-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 an exception: RangeError: Index out of range
</code></pre>
<h3>buf.slice([start[, end]])<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>
<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>
</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.html#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="lang-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="lang-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()<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.html#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 <code>RangeError</code> if <a href="#buffer_buf_length"><code>buf.length</code></a> is not a multiple of 2.</p>
<pre><code class="lang-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 an exception: RangeError: Buffer size must be a multiple of 16-bits
</code></pre>
<h3>buf.swap32()<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.html#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 <code>RangeError</code> if <a href="#buffer_buf_length"><code>buf.length</code></a> is not a multiple of 4.</p>
<pre><code class="lang-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 an exception: RangeError: Buffer size must be a multiple of 32-bits
</code></pre>
<h3>buf.swap64()<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.html#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 the byte-order <em>in-place</em>.
Throws a <code>RangeError</code> if <a href="#buffer_buf_length"><code>buf.length</code></a> is not a multiple of 8.</p>
<pre><code class="lang-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 an exception: RangeError: Buffer size must be a multiple of 64-bits
</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()<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="lang-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]]])<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 decode to. <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="lang-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="lang-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])<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 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 <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 a partial amount of <code>string</code> will
be written. However, partially encoded characters will not be written.</p>
<pre><code class="lang-js">const buf = Buffer.allocUnsafe(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.writeDoubleBE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writedoublebe_value_offset_noassert" id="buffer_buf_writedoublebe_value_offset_noassert">#</a></span></h3>
<h3>buf.writeDoubleLE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writedoublele_value_offset_noassert" id="buffer_buf_writedoublele_value_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>value</code> and <code>offset</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows the encoded form of <code>value</code> to extend beyond
the end of <code>buf</code>, but the resulting behavior is undefined.</p>
<pre><code class="lang-js">const buf = Buffer.allocUnsafe(8);
buf.writeDoubleBE(0xdeadbeefcafebabe, 0);
console.log(buf);
// Prints: <Buffer 43 eb d5 b7 dd f9 5f d7>
buf.writeDoubleLE(0xdeadbeefcafebabe, 0);
console.log(buf);
// Prints: <Buffer d7 5f f9 dd b7 d5 eb 43>
</code></pre>
<h3>buf.writeFloatBE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writefloatbe_value_offset_noassert" id="buffer_buf_writefloatbe_value_offset_noassert">#</a></span></h3>
<h3>buf.writeFloatLE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writefloatle_value_offset_noassert" id="buffer_buf_writefloatle_value_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>value</code> and <code>offset</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows the encoded form of <code>value</code> to extend beyond
the end of <code>buf</code>, but the resulting behavior is undefined.</p>
<pre><code class="lang-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[, noAssert])<span><a class="mark" href="#buffer_buf_writeint8_value_offset_noassert" id="buffer_buf_writeint8_value_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>value</code> and <code>offset</code> validation? <strong>Default:</strong> <code>false</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>Setting <code>noAssert</code> to <code>true</code> allows the encoded form of <code>value</code> to extend beyond
the end of <code>buf</code>, but the resulting behavior is undefined.</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>
<pre><code class="lang-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[, noAssert])<span><a class="mark" href="#buffer_buf_writeint16be_value_offset_noassert" id="buffer_buf_writeint16be_value_offset_noassert">#</a></span></h3>
<h3>buf.writeInt16LE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeint16le_value_offset_noassert" id="buffer_buf_writeint16le_value_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.5</span>
</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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>value</code> and <code>offset</code> validation? <strong>Default:</strong> <code>false</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>Setting <code>noAssert</code> to <code>true</code> allows the encoded form of <code>value</code> to extend beyond
the end of <code>buf</code>, but the resulting behavior is undefined.</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>
<pre><code class="lang-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[, noAssert])<span><a class="mark" href="#buffer_buf_writeint32be_value_offset_noassert" id="buffer_buf_writeint32be_value_offset_noassert">#</a></span></h3>
<h3>buf.writeInt32LE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeint32le_value_offset_noassert" id="buffer_buf_writeint32le_value_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.5</span>
</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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>value</code> and <code>offset</code> validation? <strong>Default:</strong> <code>false</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>Setting <code>noAssert</code> to <code>true</code> allows the encoded form of <code>value</code> to extend beyond
the end of <code>buf</code>, but the resulting behavior is undefined.</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>
<pre><code class="lang-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[, noAssert])<span><a class="mark" href="#buffer_buf_writeintbe_value_offset_bytelength_noassert" id="buffer_buf_writeintbe_value_offset_bytelength_noassert">#</a></span></h3>
<h3>buf.writeIntLE(value, offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_writeintle_value_offset_bytelength_noassert" id="buffer_buf_writeintle_value_offset_bytelength_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>value</code>, <code>offset</code>, and <code>byteLength</code> validation?
<strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows the encoded form of <code>value</code> to extend beyond
the end of <code>buf</code>, but the resulting behavior is undefined.</p>
<pre><code class="lang-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[, noAssert])<span><a class="mark" href="#buffer_buf_writeuint8_value_offset_noassert" id="buffer_buf_writeuint8_value_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>value</code> and <code>offset</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows the encoded form of <code>value</code> to extend beyond
the end of <code>buf</code>, but the resulting behavior is undefined.</p>
<pre><code class="lang-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[, noAssert])<span><a class="mark" href="#buffer_buf_writeuint16be_value_offset_noassert" id="buffer_buf_writeuint16be_value_offset_noassert">#</a></span></h3>
<h3>buf.writeUInt16LE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeuint16le_value_offset_noassert" id="buffer_buf_writeuint16le_value_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.5</span>
</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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>value</code> and <code>offset</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows the encoded form of <code>value</code> to extend beyond
the end of <code>buf</code>, but the resulting behavior is undefined.</p>
<pre><code class="lang-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[, noAssert])<span><a class="mark" href="#buffer_buf_writeuint32be_value_offset_noassert" id="buffer_buf_writeuint32be_value_offset_noassert">#</a></span></h3>
<h3>buf.writeUInt32LE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeuint32le_value_offset_noassert" id="buffer_buf_writeuint32le_value_offset_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.5</span>
</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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>value</code> and <code>offset</code> validation? <strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows the encoded form of <code>value</code> to extend beyond
the end of <code>buf</code>, but the resulting behavior is undefined.</p>
<pre><code class="lang-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[, noAssert])<span><a class="mark" href="#buffer_buf_writeuintbe_value_offset_bytelength_noassert" id="buffer_buf_writeuintbe_value_offset_bytelength_noassert">#</a></span></h3>
<h3>buf.writeUIntLE(value, offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_writeuintle_value_offset_bytelength_noassert" id="buffer_buf_writeuintle_value_offset_bytelength_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.5</span>
</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><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Skip <code>value</code>, <code>offset</code>, and <code>byteLength</code> validation?
<strong>Default:</strong> <code>false</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>
<p>Setting <code>noAssert</code> to <code>true</code> allows the encoded form of <code>value</code> to extend beyond
the end of <code>buf</code>, but the resulting behavior is undefined.</p>
<pre><code class="lang-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>
<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>
</table>
</details>
</div><ul>
<li><code>source</code> <a href="buffer.html#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>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="lang-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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow()</code></a> instead.</div><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="lang-js">// Need to keep around a few small chunks of memory
const store = [];
socket.on('readable', () => {
const data = socket.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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow()</code></a> instead.</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>SlowBuffer</code>.</li>
</ul>
<p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If the <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 <a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a> will be
thrown. A zero-length <code>Buffer</code> will be 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="lang-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>
<!-- [end-include:buffer.md] -->
<!-- [start-include:addons.md] -->
<h1>C++ Addons<span><a class="mark" href="#addons_c_addons" id="addons_c_addons">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<p>Node.js Addons are dynamically-linked shared objects, written in C++, that
can be loaded into Node.js using the <a href="modules.html#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="lang-js">module.exports.hello = () => 'world';
</code></pre>
<p>First, create the file <code>hello.cc</code>:</p>
<pre><code class="lang-cpp">// hello.cc
#include <node.h>
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
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"));
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "hello", Method);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, init)
} // namespace demo
</code></pre>
<p>Note that all Node.js Addons must export an initialization function following
the pattern:</p>
<pre><code class="lang-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 .node suffix).</p>
<p>In the <code>hello.cc</code> example, then, the initialization function is <code>init</code> and the
Addon module name is <code>addon</code>.</p>
<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="lang-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.html#modules_require"><code>require()</code></a> to the built <code>addon.node</code> module:</p>
<pre><code class="lang-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="lang-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.html#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.html#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.html#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>
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><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 version 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>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="lang-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, "hello", 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="lang-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="lang-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="lang-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="lang-cpp">// addon.cc
#include <node.h>
namespace demo {
using v8::Exception;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
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")));
return;
}
// Check the argument types
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong arguments")));
return;
}
// Perform the operation
double value = args[0]->NumberValue() + args[1]->NumberValue();
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="lang-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="lang-cpp">// addon.cc
#include <node.h>
namespace demo {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Null;
using v8::Object;
using v8::String;
using v8::Value;
void RunCallback(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Function> cb = Local<Function>::Cast(args[0]);
const unsigned argc = 1;
Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world") };
cb->Call(Null(isolate), argc, argv);
}
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="lang-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="lang-cpp">// addon.cc
#include <node.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) {
Isolate* isolate = args.GetIsolate();
Local<Object> obj = Object::New(isolate);
obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString());
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="lang-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="lang-cpp">// addon.cc
#include <node.h>
namespace demo {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
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"));
}
void CreateFunction(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
Local<Function> fn = tpl->GetFunction();
// omit this to make it anonymous
fn->SetName(String::NewFromUtf8(isolate, "theFunction"));
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="lang-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="lang-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="lang-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="lang-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::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"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "MyObject"),
tpl->GetFunction());
}
void MyObject::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
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<Context> context = isolate->GetCurrentContext();
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="lang-json">{
"targets": [
{
"target_name": "addon",
"sources": [
"addon.cc",
"myobject.cc"
]
}
]
}
</code></pre>
<p>Test it with:</p>
<pre><code class="lang-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>
<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="lang-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="lang-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="lang-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="lang-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::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"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
constructor.Reset(isolate, tpl->GetFunction());
}
void MyObject::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
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<Context> context = isolate->GetCurrentContext();
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="lang-json">{
"targets": [
{
"target_name": "addon",
"sources": [
"addon.cc",
"myobject.cc"
]
}
]
}
</code></pre>
<p>Test it with:</p>
<pre><code class="lang-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="lang-cpp">// addon.cc
#include <node.h>
#include <node_object_wrap.h>
#include "myobject.h"
namespace demo {
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();
MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
args[0]->ToObject());
MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
args[1]->ToObject());
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="lang-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="lang-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::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"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
constructor.Reset(isolate, tpl->GetFunction());
}
void MyObject::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
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<Context> context = isolate->GetCurrentContext();
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="lang-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 "AtExit" 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.
"AtExit" 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>
<div class="signature"><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>
</div><p>Registers exit hooks that run after the event loop has ended but before the VM
is killed.</p>
<p>AtExit 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 AtExit:</p>
<pre><code class="lang-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="lang-js">// test.js
require('./build/Release/addon');
</code></pre>
<!-- [end-include:addons.md] -->
<!-- [start-include:n-api.md] -->
<h1>N-API<span><a class="mark" href="#n_api_n_api" id="n_api_n_api">#</a></span></h1>
<!--introduced_in=v7.10.0-->
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><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 version to run on later versions of Node.js without
recompilation.</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 documentation for N-API is structured as follows:</p>
<ul>
<li><a href="#n_api_basic_n_api_data_types">Basic N-API Data Types</a></li>
<li><a href="#n_api_error_handling">Error Handling</a></li>
<li><a href="#n_api_object_lifetime_management">Object Lifetime Management</a></li>
<li><a href="#n_api_module_registration">Module Registration</a></li>
<li><a href="#n_api_working_with_javascript_values">Working with JavaScript Values</a></li>
<li><a href="#n_api_working_with_javascript_values_abstract_operations">Working with JavaScript Values - Abstract Operations</a></li>
<li><a href="#n_api_working_with_javascript_properties">Working with JavaScript Properties</a></li>
<li><a href="#n_api_working_with_javascript_functions">Working with JavaScript Functions</a></li>
<li><a href="#n_api_object_wrap">Object Wrap</a></li>
<li><a href="#n_api_simple_asynchronous_operations">Simple Asynchronous Operations</a></li>
<li><a href="#n_api_custom_asynchronous_operations">Custom Asynchronous Operations</a></li>
<li><a href="#n_api_promises">Promises</a></li>
<li><a href="#n_api_script_execution">Script Execution</a></li>
</ul>
<p>The N-API is a C API that ensures ABI stability across Node.js versions
and different compiler levels. However, we also understand that a C++
API can be easier to use in many cases. To support these cases we expect
there to be one or more C++ wrapper modules that provide an inlineable C++
API. Binaries built with these wrapper modules will depend on the symbols
for the N-API C based functions exported by Node.js. These wrappers are not
part of N-API, nor will they be maintained as part of Node.js. One such
example is: <a href="https://github.com/nodejs/node-api">node-api</a>.</p>
<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">node_api.h</a>
which is located in the src directory in the node development tree:</p>
<pre><code class="lang-C">#include <node_api.h>
</code></pre>
<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="lang-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_status_last
} 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="lang-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>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="lang-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="lang-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="lang-C">typedef void (*napi_async_execute_callback)(napi_env env, void* data);
</code></pre>
<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="lang-C">typedef void (*napi_async_complete_callback)(napi_env env,
napi_status status,
void* data);
</code></pre>
<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 napi_status 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="lang-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>
</div><pre><code class="lang-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>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 Object 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 Error 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 Error 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 napi_value that refers to the newly created
JavaScript Error 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="lang-text">originalName [code]
</code></pre>
<p>where originalName is the original name associated with the error
and code is the code that was provided. For example if the code
is 'ERR_ERROR_1' and a TypeError is being created the name will be:</p>
<pre><code class="lang-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>
</div><pre><code class="lang-C">NODE_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 <code>napi_value</code> for the Error to be thrown.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API throws the JavaScript Error 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>
</div><pre><code class="lang-C">NODE_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 Error 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>
</div><pre><code class="lang-C">NODE_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 TypeError 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>
</div><pre><code class="lang-C">NODE_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 RangeError 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>
</div><pre><code class="lang-C">NODE_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] msg</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>
</div><pre><code class="lang-C">NODE_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<pre><code> be associated with the error.
</code></pre></li>
<li><code>[in] msg</code>: napi_value that references a JavaScript String to be
used as the message for the Error.</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 Error 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>
</div><pre><code class="lang-C">NODE_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<pre><code> be associated with the error.
</code></pre></li>
<li><code>[in] msg</code>: napi_value that references a JavaScript String to be
used as the message for the Error.</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 TypeError 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>
</div><pre><code class="lang-C">NODE_EXTERN napi_status napi_create_range_error(napi_env env,
napi_value code,
const char* 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<pre><code> be associated with the error.
</code></pre></li>
<li><code>[in] msg</code>: napi_value that references a JavaScript String to be
used as the message for the Error.</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 RangeError 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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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 you want to pass 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>
</div><pre><code class="lang-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 than 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="lang-C">for (int i = 0; i < 1000000; i++) {
napi_value result;
napi_status status = napi_get_element(e, 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="lang-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(e, 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>
</div><pre><code class="lang-C">NODE_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>
</div><pre><code class="lang-C">NODE_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>
</div><pre><code class="lang-C">NODE_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>
</div><pre><code class="lang-C">NODE_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>
</div><pre><code class="lang-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 Object to be escaped.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the handle to the escaped
Object 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>
</div><pre><code class="lang-C">NODE_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 Object 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 Object 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>
</div><pre><code class="lang-C">NODE_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>
</div><pre><code class="lang-C">NODE_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>
</div><pre><code class="lang-C">NODE_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>
</div><pre><code class="lang-C">NODE_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 Object.</li>
<li><code>[out] result</code>: The <code>napi_value</code> for the Object 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 Object associated with the <code>napi_ref</code>. Otherwise, result
will be NULL.</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="lang-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="lang-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>For example, 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="lang-C">napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_property_descriptor desc =
{"hello", Method, 0, 0, 0, napi_default, 0};
if (status != napi_ok) return NULL;
status = napi_define_properties(env, exports, 1, &desc);
if (status != napi_ok) return NULL;
return exports;
}
</code></pre>
<p>For example, to set a function to be returned by the <code>require()</code> for the addon:</p>
<pre><code class="lang-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>For example, 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="lang-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, GetValue, SetValue, 0, napi_default, 0 },
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>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:</p>
<ol>
<li>Create a new JavaScript object</li>
<li>Convert from a primitive C type to an N-API value</li>
<li>Convert from N-API value to a primitive C type</li>
<li>Get global instances including <code>undefined</code> and <code>null</code></li>
</ol>
<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_valuetype<span><a class="mark" href="#n_api_napi_valuetype" id="n_api_napi_valuetype">#</a></span></h4>
<pre><code class="lang-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_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
Functions and Objects with external data.</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="lang-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_typedarray_type;
</code></pre>
<p>This represents the underlying binary scalar datatype of the TypedArray.
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>
</div><pre><code class="lang-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 Array.</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 Array 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>
</div><pre><code class="lang-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 Array.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript Array.</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 Array type.
The Array'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>
</div><pre><code class="lang-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 ArrayBuffer.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript ArrayBuffer.</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 ArrayBuffer.
ArrayBuffers are used to represent fixed-length binary data buffers. They are
normally used as a backing-buffer for TypedArray objects.
The ArrayBuffer 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 DataView object would need to be created.</p>
<p>JavaScript ArrayBuffer 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>
</div><pre><code class="lang-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 TypedArray 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>
</div><pre><code class="lang-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 Buffer'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 TypedArray will suffice.</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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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
ArrayBuffer.</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 ArrayBuffer 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 ArrayBuffer.</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 ArrayBuffer.
The underlying byte buffer of the ArrayBuffer is externally allocated and
managed. The caller must ensure that the byte buffer remains valid until the
finalize callback is called.</p>
<p>JavaScript ArrayBuffers 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>
</div><pre><code class="lang-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 ArrayBuffer 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 TypedArray will suffice.</p>
<p>For Node.js >=4 <code>Buffers</code> are Uint8Arrays.</p>
<h4>napi_create_function<span><a class="mark" href="#n_api_napi_create_function" id="n_api_napi_create_function">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div><pre><code class="lang-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>: A string representing the name of the function encoded as
UTF8.</li>
<li><code>[in] length</code>: The length of the utf8name in bytes, or
<code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li>
<li><code>[in] cb</code>: A function pointer to the native function to be invoked when the
created function is invoked from JavaScript.</li>
<li><code>[in] data</code>: Optional arbitrary context data to be passed into the native
function when it is invoked.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript function.</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 Function object.
It's used to wrap native functions so that they can be invoked from JavaScript.</p>
<p>JavaScript Functions are described in
<a href="https://tc39.github.io/ecma262/#sec-function-objects">Section 19.2</a>
of the ECMAScript Language Specification.</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>
</div><pre><code class="lang-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 Object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a default JavaScript Object.
It is the equivalent of doing <code>new Object()</code> in JavaScript.</p>
<p>The JavaScript Object 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>
</div><pre><code class="lang-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 napi_value which refers to a JavaScript
String to be set as the description for the symbol.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript Symbol.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript Symbol object from a UTF8-encoded C string</p>
<p>The JavaScript Symbol 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>
</div><pre><code class="lang-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 TypedArray.</li>
<li><code>[in] length</code>: Number of elements in the TypedArray.</li>
<li><code>[in] arraybuffer</code>: ArrayBuffer underlying the typed array.</li>
<li><code>[in] byte_offset</code>: The byte offset within the ArrayBuffer from which to
start projecting the TypedArray.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript TypedArray.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript TypedArray object over an existing ArrayBuffer.
TypedArray 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 (length * size_of_element) + byte_offset should
be <= the size in bytes of the array passed in. If not, a RangeError exception
is raised.</p>
<p>JavaScript TypedArray 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>
</div><pre><code class="lang-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 DataView.</li>
<li><code>[in] arraybuffer</code>: ArrayBuffer underlying the DataView.</li>
<li><code>[in] byte_offset</code>: The byte offset within the ArrayBuffer from which to
start projecting the DataView.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript DataView.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript DataView object over an existing ArrayBuffer.
DataView objects provide an array-like view over an underlying data buffer,
but one which allows items of different size and type in the ArrayBuffer.</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 RangeError exception is raised.</p>
<p>JavaScript DataView 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>
</div><pre><code class="lang-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 Number.</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
Number type.</p>
<p>The JavaScript Number 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>
</div><pre><code class="lang-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 Number.</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
Number type.</p>
<p>The JavaScript Number 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>
</div><pre><code class="lang-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 Number.</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
Number type.</p>
<p>The JavaScript Number 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>
</div><pre><code class="lang-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 Number.</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
Number type.</p>
<p>The JavaScript Number 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_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>
</div><pre><code class="lang-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 a 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 String.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript String object from a ISO-8859-1-encoded C string.</p>
<p>The JavaScript String 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>
</div><pre><code class="lang-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 String.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript String object from a UTF16-LE-encoded C string</p>
<p>The JavaScript String 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>
</div><pre><code class="lang-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 String.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript String object from a UTF8-encoded C string</p>
<p>The JavaScript String 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>
</div><pre><code class="lang-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 Array 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>Array 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>
</div><pre><code class="lang-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 ArrayBuffer being queried.</li>
<li><code>[out] data</code>: The underlying data buffer of the ArrayBuffer.</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 ArrayBuffer 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 ArrayBuffer 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 ArrayBuffer. 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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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 Object 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>
</div><pre><code class="lang-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 TypedArray whose
properties to query.</li>
<li><code>[out] type</code>: Scalar datatype of the elements within the TypedArray.</li>
<li><code>[out] length</code>: Number of elements in the TypedArray.</li>
<li><code>[out] data</code>: The data buffer underlying the typed array.</li>
<li><code>[out] byte_offset</code>: The byte offset within the data buffer from which
to start projecting the TypedArray.</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>
</div><pre><code class="lang-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 DataView whose
properties to query.</li>
<li><code>[out] byte_length</code>: Number of bytes in the DataView.</li>
<li><code>[out] data</code>: The data buffer underlying the DataView.</li>
<li><code>[out] arraybuffer</code>: ArrayBuffer underlying the DataView.</li>
<li><code>[out] byte_offset</code>: The byte offset within the data buffer from which
to start projecting the DataView.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns various properties of a DataView.</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>
</div><pre><code class="lang-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 Boolean.</li>
<li><code>[out] result</code>: C boolean primitive equivalent of the given JavaScript
Boolean.</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
Boolean.</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>
</div><pre><code class="lang-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 Number.</li>
<li><code>[out] result</code>: C double primitive equivalent of the given JavaScript
Number.</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
Number.</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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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 Number.</li>
<li><code>[out] result</code>: C int32 primitive equivalent of the given JavaScript Number.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code>
is passed in `napi_number_expected .</p>
<p>This API returns the C int32 primitive equivalent
of the given JavaScript Number. 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>
<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>
</div><pre><code class="lang-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 Number.</li>
<li><code>[out] result</code>: C int64 primitive equivalent of the given JavaScript Number.</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 int64 primitive equivalent of the given
JavaScript Number.</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>
</div><pre><code class="lang-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-String <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>
</div><pre><code class="lang-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-String <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>
</div><pre><code class="lang-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-String <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>
</div><pre><code class="lang-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 Number.</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>
</div><pre><code class="lang-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 Boolean 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>
</div><pre><code class="lang-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 Global Object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the global 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>
</div><pre><code class="lang-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 Null Object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the null 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>
</div><pre><code class="lang-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:</p>
<ol>
<li>Coerce JavaScript values to specific JavaScript types (such as Number or
String)</li>
<li>Check the type of a JavaScript value</li>
<li>Check for equality between two JavaScript values</li>
</ol>
<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>
</div><pre><code class="lang-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 Boolean.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation ToBoolean 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 Object.</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>
</div><pre><code class="lang-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 Number.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation ToNumber 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 Object.</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>
</div><pre><code class="lang-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 Object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation ToObject 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 Object.</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>
</div><pre><code class="lang-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 String.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation ToString 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 Object.</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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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 ArrayBuffer.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the Object 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>
</div><pre><code class="lang-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 Object passed in is a buffer.</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>
</div><pre><code class="lang-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 Error object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the Object passed in is an Error.</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>
</div><pre><code class="lang-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 TypedArray.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the Object 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>
</div><pre><code class="lang-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 DataView.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the Object passed in is a DataView.</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>
</div><pre><code class="lang-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>
<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 String, Number, or Symbol.</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="lang-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="lang-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="lang-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="lang-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="lang-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="lang-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="lang-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="lang-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, 0, 0, 0, fooValue, napi_default, 0 },
{ "bar", NULL, 0, 0, 0, barValue, napi_default, 0 }
}
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="lang-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="lang-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 String 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 napi_value 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>data</code>: The callback data passed into <code>method</code>, <code>getter</code> and <code>setter</code> if
this function is invoked.</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>
</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>
</div><pre><code class="lang-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 array of properties for the Object passed in</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>
</div><pre><code class="lang-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 Object 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>
</div><pre><code class="lang-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 Object 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>
</div><pre><code class="lang-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 Object 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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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 Object passed in has the named own property. <code>key</code> must
be a string or a Symbol, 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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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 Object 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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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 Object 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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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
DefineOwnProperty (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>
<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>
</div><pre><code class="lang-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="lang-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="lang-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_1" id="n_api_napi_create_function_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div><pre><code class="lang-C">napi_status napi_create_function(napi_env env,
const char* utf8name,
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] 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="lang-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="lang-js">const myaddon = require('./addon');
myaddon.sayHello();
</code></pre>
<p>The string passed to require is not necessarily the name passed into
<code>NAPI_MODULE</code> in the earlier snippet but the name of the target in <code>binding.gyp</code>
responsible for creating the <code>.node</code> file.</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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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="lang-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="lang-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>
<p>As an example:</p>
<pre><code class="lang-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>
</div><pre><code class="lang-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 utf8name 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>
<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>
</div><pre><code class="lang-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. This object <em>must</em> have been created from the <code>prototype</code> of
a constructor that was created using <code>napi_define_class()</code>.</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 proper of the reference.</p>
<p>This API may modify the prototype chain of the wrapper object. Afterward,
additional manipulation of the wrapper's prototype chain may cause
<code>napi_unwrap()</code> to fail.</p>
<p>Calling napi_wrap() a second time on an object will return an error. To
associate another native instance with the object, use napi_remove_wrap() 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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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, thereby
restoring the JavaScript object's prototype chain. If a finalize callback was
associated with the wrapping, it will no longer be called when the JavaScript
object becomes garbage-collected.</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. These functions implement the following interfaces:</p>
<pre><code class="lang-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 void* 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="lang-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>
<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>
</table>
</details>
</div><pre><code class="lang-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 async_hooks <a href="async_hooks.html#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.html#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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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.html#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>
</div><pre><code class="lang-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>
<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>
</table>
</details>
</div><pre><code class="lang-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><em>napi_open_callback_scope</em><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>
</div><pre><code class="lang-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 optional object associated with the async work
that will be passed to possible async_hooks <a href="async_hooks.html#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><em>napi_close_callback_scope</em><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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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 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.html#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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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="lang-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="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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>
</div><pre><code class="lang-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: v9.3.0</span>
</div><pre><code class="lang-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>
<!-- [end-include:n-api.md] -->
<!-- [start-include:child_process.md] -->
<h1>Child Process<span><a class="mark" href="#child_process_child_process" id="child_process_child_process">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<!--lint disable maximum-line-length-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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">popen(3)</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="lang-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.html#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.html#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.html#child_process_class_childprocess"><code>ChildProcess</code></a> instance. These objects
implement the Node.js <a href="events.html"><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="lang-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="lang-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])<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>
<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>
</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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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>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.
<strong>Default:</strong> <code>'/bin/sh'</code> on UNIX, <code>process.env.ComSpec</code> on Windows. See
<a href="#child_process_shell_requirements">Shell Requirements</a> and <a href="#child_process_default_windows_shell">Default Windows Shell</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> <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. 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">setuid(2)</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">setgid(2)</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><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.<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.html#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.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="child_process.html#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="lang-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>
<pre><code class="lang-js">const { exec } = require('child_process');
exec('cat *.js bad_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 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.html#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>
<p>The <code>options</code> argument may be passed as the second argument to customize how
the process is spawned. The default options are:</p>
<pre><code class="lang-js">const defaults = {
encoding: 'utf8',
timeout: 0,
maxBuffer: 200 * 1024,
killSignal: 'SIGTERM',
cwd: null,
env: null
};
</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">exec(3)</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 Promise for an object 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="lang-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])<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>
<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>
</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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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. 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">setuid(2)</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">setgid(2)</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><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.<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.html#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.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="child_process.html#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="lang-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 Promise for an object 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="lang-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])<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>
<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>
</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/Reference/Global_Objects/Array" class="type"><Array></a> List of string arguments.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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>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/Reference/Global_Objects/Array" class="type"><Array></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">setuid(2)</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">setgid(2)</a>).</li>
</ul>
</li>
<li>Returns: <a href="child_process.html#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.html#child_process_class_childprocess"><code>ChildProcess</code></a> object is returned. The returned
<a href="child_process.html#child_process_class_childprocess"><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.html#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">fork(2)</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])<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>
<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>
</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/Reference/Global_Objects/Array" class="type"><Array></a> List of string arguments.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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">setuid(2)</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">setgid(2)</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.html#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="lang-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.html#process_process_env"><code>process.env</code></a>.</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="lang-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="lang-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="lang-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">setsid(2)</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>, 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 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="lang-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="lang-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>
<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>
</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.html#child_process_class_childprocess"><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>[process.stdin, process.stdout, process.stderr]</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><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.</li>
<li><p><code>'ipc'</code> - Create an IPC channel for passing messages/file descriptors
between parent and child. A <a href="child_process.html#child_process_class_childprocess"><code>ChildProcess</code></a> may have at most <em>one</em> IPC stdio
file descriptor. Setting this option enables the <a href="child_process.html#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.html#process_process_send_message_sendhandle_options_callback"><code>process.send()</code></a>, <a href="process.html#process_process_disconnect"><code>process.disconnect()</code></a>,
<a href="process.html#process_event_disconnect"><code>process.on('disconnect')</code></a>, and <a href="process.html#process_event_message"><code>process.on('message')</code></a> within the
child.</p>
<p>Accessing the IPC channel fd in any way other than <a href="process.html#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><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.</li>
<li><a href="stream.html#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).</li>
<li>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.html#stream_stream" class="type"><Stream></a> objects can be shared.</li>
<li><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>.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-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.html#process_event_disconnect"><code>process.on('disconnect')</code></a> event
or the <a href="process.html#process_event_message"><code>process.on('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>See also: <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> and <a href="child_process.html#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])<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>
<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>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>
</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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.html#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 value which will be passed as stdin
to the spawned process.<ul>
<li>supplying this value will override <code>stdio[0]</code></li>
</ul>
</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. <strong>Default:</strong> <code>'pipe'</code><ul>
<li><code>stderr</code> by default will be output to the parent process' stderr unless
<code>stdio</code> is specified</li>
</ul>
</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">setuid(2)</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">setgid(2)</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.html#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.html#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])<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>
<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>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>
</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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.html#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 value which will be passed as stdin
to the spawned process.<ul>
<li>supplying this value will override <code>stdio[0]</code>.</li>
</ul>
</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. <strong>Default:</strong> <code>'pipe'</code><ul>
<li><code>stderr</code> by default will be output to the parent process' stderr unless
<code>stdio</code> is specified</li>
</ul>
</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.
<strong>Default:</strong> <code>'/bin/sh'</code> on UNIX, <code>process.env.ComSpec</code> on Windows. See
<a href="#child_process_shell_requirements">Shell Requirements</a> and <a href="#child_process_default_windows_shell">Default Windows Shell</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">setuid(2)</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">setgid(2)</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>
</ul>
</li>
<li>Returns: <a href="buffer.html#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.html#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])<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>
<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>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>
</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/Reference/Global_Objects/Array" class="type"><Array></a> List of string arguments.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.html#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 value which will be passed as stdin
to the spawned process.<ul>
<li>supplying this value will override <code>stdio[0]</code>.</li>
</ul>
</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">setuid(2)</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">setgid(2)</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>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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.html#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.html#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> The exit code of the child process.</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 used to kill the child process.</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.html"><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.html#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="#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.html#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>
<div class="signature"><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>
</div><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.html#child_process_subprocess_kill_signal"><code>subprocess.kill()</code></a> and <a href="child_process.html#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">waitpid(2)</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.html#net_server_listen_handle_backlog_callback" class="type"><Handle></a> A <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> or <a href="net.html#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.html#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.html#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">signal(7)</a> for a list of available signals.</p>
<pre><code class="lang-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.html#child_process_class_childprocess"><code>ChildProcess</code></a> object may emit an <a href="#net_event_error_1"><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">kill(2)</a> for reference.</p>
<p>Also note: 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 use of the <code>shell</code> option of <code>ChildProcess</code>, such
as in this example:</p>
<pre><code class="lang-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"><number></a> Integer</li>
</ul>
<p>Returns the process identifier (PID) of the child process.</p>
<p>Example:</p>
<pre><code class="lang-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.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>
<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>
</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.html#net_server_listen_handle_backlog_callback" class="type"><Handle></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>When an IPC channel has been established between the parent and child (
i.e. when using <a href="child_process.html#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.html#process_event_message"><code>process.on('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="lang-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="lang-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.html#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.html#process_event_message"><code>process.on('message')</code></a>
event. Rather, such messages are emitted using the
<code>process.on('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.html#process_event_message"><code>process.on('message')</code></a> event. Any data that is received
and buffered in the socket will not be sent to the child.</p>
<p>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 Boolean 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.
Defaults to <code>false</code>.</li>
</ul>
<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.html#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.html#child_process_class_childprocess"><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="lang-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="lang-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="lang-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="lang-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.html#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.html#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="lang-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.html#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>
<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>
<!-- [end-include:child_process.md] -->
<!-- [start-include:cluster.md] -->
<h1>Cluster<span><a class="mark" href="#cluster_cluster" id="cluster_cluster">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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="lang-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="lang-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>
<!--type=misc-->
<p>The worker processes are spawned using the <a href="child_process.html#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 Worker 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="lang-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.html#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="lang-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="lang-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>cluster.on('message')</code> event, 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.html#process_event_message"><code>process</code> event: <code>'message'</code></a>.</p>
<p>As an example, here is a cluster that keeps count of the number of requests
in the master process using the message system:</p>
<pre><code class="lang-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="lang-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>
<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>
</table>
</details>
</div><ul>
<li>Returns: <a href="cluster.html#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_server_close_callback"><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.html#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="lang-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.html#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="lang-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
cluster.workers</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>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.html#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.html#child_process_class_childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>All workers are created using <a href="child_process.html#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.html#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>
<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>
</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.html#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.html#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="lang-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.html#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
worker.disconnect()).</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="lang-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.html#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="lang-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.html#child_process_event_exit">child_process event: 'exit'</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.html#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="lang-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.html#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="lang-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>
<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>
</table>
</details>
</div><ul>
<li><code>worker</code> <a href="cluster.html#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.html#child_process_event_message">child_process event: 'message'</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="lang-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.html#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 'online' is emitted when the worker is running.</p>
<pre><code class="lang-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.html#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>
<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>
</table>
</details>
</div><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></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/Reference/Global_Objects/Array" class="type"><Array></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">setuid(2)</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">setgid(2)</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>
<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>
</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>
<p>Example:</p>
<pre><code class="lang-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="lang-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 cluster.workers 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 cluster.workers list happens
before last <code>'disconnect'</code> or <code>'exit'</code> event is emitted.</p>
<pre><code class="lang-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="lang-js">socket.on('data', (id) => {
const worker = cluster.workers[id];
});
</code></pre>
<!-- [end-include:cluster.md] -->
<!-- [start-include:cli.md] -->
<h1>Command Line Options<span><a class="mark" href="#cli_command_line_options" id="cli_command_line_options">#</a></span></h1>
<!--introduced_in=v5.9.1-->
<!--type=misc-->
<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 debug [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_repl">REPL</a>.</p>
<p><em>For more info about <code>node debug</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>
<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>
<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>-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>
<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>
</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>-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>
<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>
</table>
</details>
</div><p>Identical to <code>-e</code> but prints the result.</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">
<span>Added in: v5.0.0, v4.2.0</span>
</div><p>Syntax check the script without executing.</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>-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>--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 host:port. Default is 127.0.0.1:9229.</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/debugger-protocol-viewer/">Chrome Debugging Protocol</a>.</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 host:port and break at start of user script.
Default host:port is 127.0.0.1:9229.</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 host:port 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 127.0.0.1.</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>--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>--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>--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>--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>--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.html#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> (and through usage of the
<code>domain</code> module that uses it).</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>--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>--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>--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>--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-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>--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.html#buffer_buffer">Buffer</a> and <a href="buffer.html#buffer_class_slowbuffer">SlowBuffer</a>
instances.</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="lang-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>
<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>--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>--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>
<p>V8 options allow words to be separated by both dashes (<code>-</code>) or
underscores (<code>_</code>).</p>
<p>For example, <code>--stack-trace-limit</code> is equivalent to <code>--stack_trace_limit</code>.</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>--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>--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>--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>--use-openssl-ca</code>, <code>--use-bundled-ca</code><span><a class="mark" href="#cli_use_openssl_ca_use_bundled_ca" id="cli_use_openssl_ca_use_bundled_ca">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.11.0</span>
</div><p>Use OpenSSL's default CA store or use bundled Mozilla CA store as supplied by
current Node.js version. The default store is selectable at build-time.</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>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>See <code>SSL_CERT_DIR</code> and <code>SSL_CERT_FILE</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>-</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>
<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_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_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_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 (Intl 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 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>Node options that are allowed are:</p>
<ul>
<li><code>--enable-fips</code></li>
<li><code>--force-fips</code></li>
<li><code>--icu-data-dir</code></li>
<li><code>--inspect-brk</code></li>
<li><code>--inspect-port</code></li>
<li><code>--inspect</code></li>
<li><code>--no-deprecation</code></li>
<li><code>--no-warnings</code></li>
<li><code>--openssl-config</code></li>
<li><code>--redirect-warnings</code></li>
<li><code>--require</code>, <code>-r</code></li>
<li><code>--throw-deprecation</code></li>
<li><code>--tls-cipher-list</code></li>
<li><code>--trace-deprecation</code></li>
<li><code>--trace-events-categories</code></li>
<li><code>--trace-events-enabled</code></li>
<li><code>--trace-event-file-pattern</code></li>
<li><code>--trace-sync-io</code></li>
<li><code>--trace-warnings</code></li>
<li><code>--track-heap-objects</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_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_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_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.html#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>
<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>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>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>
<!-- [end-include:cli.md] -->
<!-- [start-include:console.md] -->
<h1>Console<span><a class="mark" href="#console_console" id="console_console">#</a></span></h1>
<!--introduced_in=v0.10.13-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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.html#process_process_stdout"><code>process.stdout</code></a> and
<a href="process.html#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.html#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="lang-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="lang-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>
<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.</p>
</td></tr>
</table>
</details>
</div><!--type=class-->
<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="lang-js">const { Console } = require('console');
</code></pre>
<pre><code class="lang-js">const { Console } = console;
</code></pre>
<h3>new Console(stdout[, stderr])<span><a class="mark" href="#console_new_console_stdout_stderr" id="console_new_console_stdout_stderr">#</a></span></h3>
<div class="signature"><ul>
<li><code>stdout</code> <a href="stream.html#stream_class_stream_writable" class="type"><stream.Writable></a></li>
<li><code>stderr</code> <a href="stream.html#stream_class_stream_writable" class="type"><stream.Writable></a></li>
</ul>
</div><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="lang-js">const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, 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.html#process_process_stdout"><code>process.stdout</code></a> and <a href="process.html#process_process_stderr"><code>process.stderr</code></a>. It is equivalent to calling:</p>
<pre><code class="lang-js">new Console(process.stdout, process.stderr);
</code></pre>
<h3>console.assert(value[, message][, ...args])<span><a class="mark" href="#console_console_assert_value_message_args" id="console_console_assert_value_message_args">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.101</span>
</div><ul>
<li><code>value</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
<li><code>...args</code> <span class="type"><any></span></li>
</ul>
<p>A simple assertion test that verifies whether <code>value</code> is truthy. If it is not,
an <code>AssertionError</code> is thrown. If provided, the error <code>message</code> is formatted
using <a href="util.html#util_util_format_format_args"><code>util.format()</code></a> and used as the error message.</p>
<pre><code class="lang-js">console.assert(true, 'does nothing');
// OK
console.assert(false, 'Whoops %s', 'didn\'t work');
// AssertionError: Whoops didn't work
</code></pre>
<p>The <code>console.assert()</code> method is implemented differently in Node.js than the
<code>console.assert()</code> method <a href="https://developer.mozilla.org/en-US/docs/Web/API/console/assert">available in browsers</a>.</p>
<p>Specifically, in browsers, calling <code>console.assert()</code> with a falsy
assertion will cause the <code>message</code> to be printed to the console without
interrupting execution of subsequent code. In Node.js, however, a falsy
assertion will cause an <code>AssertionError</code> to be thrown.</p>
<p>Functionality approximating that implemented by browsers can be implemented
by extending Node.js' <code>console</code> and overriding the <code>console.assert()</code> method.</p>
<p>In the following example, a simple module is created that extends and overrides
the default behavior of <code>console</code> in Node.js.</p>
<!-- eslint-disable func-name-matching -->
<pre><code class="lang-js">'use strict';
// Creates a simple extension of console with a
// new impl for assert without monkey-patching.
const myConsole = Object.create(console, {
assert: {
value: function assert(assertion, message, ...args) {
try {
console.assert(assertion, message, ...args);
} catch (err) {
console.error(err.stack);
}
},
configurable: true,
enumerable: true,
writable: true,
},
});
module.exports = myConsole;
</code></pre>
<p>This can then be used as a direct replacement for the built in console:</p>
<pre><code class="lang-js">const console = require('./myConsole');
console.assert(false, 'this message will print, but no error thrown');
console.log('this will also print');
</code></pre>
<h3>console.clear()<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])<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. Defaults to <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="lang-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='default'])<span><a class="mark" href="#console_console_countreset_label_default" id="console_console_countreset_label_default">#</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. Defaults to <code>'default'</code>.</li>
</ul>
<p>Resets the internal counter specific to <code>label</code>.</p>
<!-- eslint-skip -->
<pre><code class="lang-js">> console.count('abc');
abc: 1
undefined
> console.countReset('abc');
undefined
> console.count('abc');
abc: 1
undefined
>
</code></pre>
<h3>console.debug(data[, ...args])<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>
<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>
</table>
</details>
</div><ul>
<li><code>data</code> <span class="type"><any></span></li>
<li><code>...args</code> <span class="type"><any></span></li>
</ul>
<p>The <code>console.debug()</code> function is an alias for <a href="console.html#console_console_log_data_args"><code>console.log()</code></a>.</p>
<h3>console.dir(obj[, options])<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> <span class="type"><any></span></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>showHidden</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
<li><code>depth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
<li><code>colors</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>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>. An
optional <code>options</code> object may be passed to alter certain aspects of the
formatted string:</p>
<ul>
<li><p><code>showHidden</code> - if <code>true</code> then the object's non-enumerable and symbol
properties will be shown too. Defaults to <code>false</code>.</p>
</li>
<li><p><code>depth</code> - 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.
Defaults to <code>2</code>. To make it recurse indefinitely, pass <code>null</code>.</p>
</li>
<li><p><code>colors</code> - if <code>true</code>, then the output will be styled with ANSI color codes.
Defaults to <code>false</code>. Colors are customizable; see
<a href="util.html#util_customizing_util_inspect_colors">customizing <code>util.inspect()</code> colors</a>.</p>
</li>
</ul>
<h3>console.dirxml(...data)<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>
<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>
</table>
</details>
</div><ul>
<li><code>...data</code> <span class="type"><any></span></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])<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> <span class="type"><any></span></li>
<li><code>...args</code> <span class="type"><any></span></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">printf(3)</a> (the arguments are all passed to
<a href="util.html#util_util_format_format_args"><code>util.format()</code></a>).</p>
<pre><code class="lang-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.html#util_util_format_format_args"><code>util.format()</code></a> for more information.</p>
<h3>console.group([...label])<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> <span class="type"><any></span></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()<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()<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])<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> <span class="type"><any></span></li>
<li><code>...args</code> <span class="type"><any></span></li>
</ul>
<p>The <code>console.info()</code> function is an alias for <a href="console.html#console_console_log_data_args"><code>console.log()</code></a>.</p>
<h3>console.log([data][, ...args])<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> <span class="type"><any></span></li>
<li><code>...args</code> <span class="type"><any></span></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">printf(3)</a> (the arguments are all passed to
<a href="util.html#util_util_format_format_args"><code>util.format()</code></a>).</p>
<pre><code class="lang-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.html#util_util_format_format_args"><code>util.format()</code></a> for more information.</p>
<h3>console.time(label)<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> Defaults to <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)<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>
<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>
</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> Defaults to <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="lang-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.trace([message][, ...args])<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> <span class="type"><any></span></li>
<li><code>...args</code> <span class="type"><any></span></li>
</ul>
<p>Prints to <code>stderr</code> the string <code>'Trace :'</code>, followed by the <a href="util.html#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="lang-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])<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> <span class="type"><any></span></li>
<li><code>...args</code> <span class="type"><any></span></li>
</ul>
<p>The <code>console.warn()</code> function is an alias for <a href="console.html#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> Defaults to <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"><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="lang-js">console.profile('MyLabel');
// Some code
console.profileEnd();
// Adds the profile 'MyLabel' to the Profiles panel of the inspector.
</code></pre>
<h3>console.profileEnd()<span><a class="mark" href="#console_console_profileend" id="console_console_profileend">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div><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>
<h3>console.table(array[, columns])<span><a class="mark" href="#console_console_table_array_columns" id="console_console_table_array_columns">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div><ul>
<li><code>array</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/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li><code>columns</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>This method does not display anything unless used in the inspector. Prints to
<code>stdout</code> the array <code>array</code> formatted as a table.</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> Defaults to <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> Defaults to <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>
<!-- [end-include:console.md] -->
<!-- [start-include:crypto.md] -->
<h1>Crypto<span><a class="mark" href="#crypto_crypto" id="crypto_crypto">#</a></span></h1>
<!--introduced_in=v0.3.6-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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="lang-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="lang-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.0.2/apps/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.html#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.html#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="lang-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.html#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></li>
<li>Returns <a href="buffer.html#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="lang-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.html#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="lang-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="lang-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.html#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.html#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="lang-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.html#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.html#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="lang-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.html#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="lang-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_stream">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="lang-js">const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
let encrypted = '';
cipher.on('readable', () => {
const data = cipher.read();
if (data)
encrypted += data.toString('hex');
});
cipher.on('end', () => {
console.log(encrypted);
// Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504
});
cipher.write('some clear text data');
cipher.end();
</code></pre>
<p>Example: Using <code>Cipher</code> and piped streams:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const fs = require('fs');
const cipher = crypto.createCipher('aes192', 'a password');
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="lang-js">const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);
// Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504
</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></li>
</ul>
<p>Returns any remaining enciphered contents. If <code>outputEncoding</code>
parameter is one of <code>'latin1'</code>, <code>'base64'</code> or <code>'hex'</code>, a string is returned.
If an <code>outputEncoding</code> is not provided, a <a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a> is returned.</p>
<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)<span><a class="mark" href="#crypto_cipher_setaad_buffer" id="crypto_cipher_setaad_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
<li>Returns the <span class="type"><Cipher></span> for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (only <code>GCM</code> is 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>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><p>When using an authenticated encryption mode (only <code>GCM</code> is currently
supported), the <code>cipher.getAuthTag()</code> method returns a <a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a> containing
the <em>authentication tag</em> that has been computed from the given data.</p>
<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> Defaults to <code>true</code>.</li>
<li>Returns the <span class="type"><Cipher></span> 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>
<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>
</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.html#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></li>
<li><code>outputEncoding</code> <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,
its value must be one of <code>'utf8'</code>, <code>'ascii'</code>, or <code>'latin1'</code> and 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#buffer_class_buffer"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>. If <code>data</code> is a <a href="buffer.html#buffer_class_buffer"><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, and can be <code>'latin1'</code>, <code>'base64'</code> or <code>'hex'</code>. 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#buffer_class_buffer"><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_stream">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="lang-js">const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
let decrypted = '';
decipher.on('readable', () => {
const data = decipher.read();
if (data)
decrypted += data.toString('utf8');
});
decipher.on('end', () => {
console.log(decrypted);
// Prints: some clear text data
});
const encrypted =
'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
decipher.write(encrypted, 'hex');
decipher.end();
</code></pre>
<p>Example: Using <code>Decipher</code> and piped streams:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const fs = require('fs');
const decipher = crypto.createDecipher('aes192', 'a password');
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="lang-js">const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
const encrypted =
'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
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></li>
</ul>
<p>Returns any remaining deciphered contents. If <code>outputEncoding</code>
parameter is one of <code>'latin1'</code>, <code>'ascii'</code> or <code>'utf8'</code>, a string is returned.
If an <code>outputEncoding</code> is not provided, a <a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a> is returned.</p>
<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)<span><a class="mark" href="#crypto_decipher_setaad_buffer" id="crypto_decipher_setaad_buffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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 the <span class="type"><Cipher></span> for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (only <code>GCM</code> is 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>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>
<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>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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 the <span class="type"><Cipher></span> for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (only <code>GCM</code> is 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="http://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> Defaults to <code>true</code>.</li>
<li>Returns the <span class="type"><Cipher></span> 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>
<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>
</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.html#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></li>
<li><code>outputEncoding</code> <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,
its value must be one of <code>'latin1'</code>, <code>'base64'</code>, or <code>'hex'</code> and 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#buffer_class_buffer"><code>Buffer</code></a>. If <code>data</code> is a
<a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a> then <code>inputEncoding</code> is ignored.</p>
<p>The <code>outputEncoding</code> specifies the output format of the enciphered
data, and can be <code>'latin1'</code>, <code>'ascii'</code> or <code>'utf8'</code>. 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#buffer_class_buffer"><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="lang-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.html#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></li>
<li><code>outputEncoding</code> <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>. Encodings can be
<code>'latin1'</code>, <code>'hex'</code>, or <code>'base64'</code>. If the <code>inputEncoding</code> is not
provided, <code>otherPublicKey</code> is expected to be a <a href="buffer.html#buffer_class_buffer"><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#buffer_class_buffer"><code>Buffer</code></a> is returned.</p>
<h3>diffieHellman.generateKeys([encoding])<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></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. Encoding can be <code>'latin1'</code>, <code>'hex'</code>,
or <code>'base64'</code>. If <code>encoding</code> is provided a string is returned; otherwise a
<a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a> is returned.</p>
<h3>diffieHellman.getGenerator([encoding])<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></li>
</ul>
<p>Returns the Diffie-Hellman generator in the specified <code>encoding</code>, which can
be <code>'latin1'</code>, <code>'hex'</code>, or <code>'base64'</code>. If <code>encoding</code> is provided a string is
returned; otherwise a <a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a> is returned.</p>
<h3>diffieHellman.getPrime([encoding])<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></li>
</ul>
<p>Returns the Diffie-Hellman prime in the specified <code>encoding</code>, which can
be <code>'latin1'</code>, <code>'hex'</code>, or <code>'base64'</code>. If <code>encoding</code> is provided a string is
returned; otherwise a <a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a> is returned.</p>
<h3>diffieHellman.getPrivateKey([encoding])<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></li>
</ul>
<p>Returns the Diffie-Hellman private key in the specified <code>encoding</code>,
which can be <code>'latin1'</code>, <code>'hex'</code>, or <code>'base64'</code>. If <code>encoding</code> is provided a
string is returned; otherwise a <a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a> is returned.</p>
<h3>diffieHellman.getPublicKey([encoding])<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></li>
</ul>
<p>Returns the Diffie-Hellman public key in the specified <code>encoding</code>, which
can be <code>'latin1'</code>, <code>'hex'</code>, or <code>'base64'</code>. If <code>encoding</code> is provided a
string is returned; otherwise a <a href="buffer.html#buffer_class_buffer"><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.html#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></li>
</ul>
<p>Sets the Diffie-Hellman private key. If the <code>encoding</code> argument is provided
and is either <code>'latin1'</code>, <code>'hex'</code>, or <code>'base64'</code>, <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#buffer_class_buffer"><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.html#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></li>
</ul>
<p>Sets the Diffie-Hellman public key. If the <code>encoding</code> argument is provided
and is either <code>'latin1'</code>, <code>'hex'</code> or <code>'base64'</code>, <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#buffer_class_buffer"><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="lang-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>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>
<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.11.14</td>
<td><p><span>Added in: v0.11.14</span></p>
</td></tr>
</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.html#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></li>
<li><code>outputEncoding</code> <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>. Encodings can be
<code>'latin1'</code>, <code>'hex'</code>, or <code>'base64'</code>. If the <code>inputEncoding</code> is not
provided, <code>otherPublicKey</code> is expected to be a <a href="buffer.html#buffer_class_buffer"><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#buffer_class_buffer"><code>Buffer</code></a> is returned.</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></li>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Defaults to <code>uncompressed</code>.</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>The <code>encoding</code> argument can be <code>'latin1'</code>, <code>'hex'</code>, or <code>'base64'</code>. If
<code>encoding</code> is provided a string is returned; otherwise a <a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a>
is returned.</p>
<h3>ecdh.getPrivateKey([encoding])<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></li>
</ul>
<p>Returns the EC Diffie-Hellman private key in the specified <code>encoding</code>,
which can be <code>'latin1'</code>, <code>'hex'</code>, or <code>'base64'</code>. If <code>encoding</code> is provided
a string is returned; otherwise a <a href="buffer.html#buffer_class_buffer"><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></li>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Defaults to <code>uncompressed</code>.</li>
</ul>
<p>Returns the EC Diffie-Hellman public key in the specified <code>encoding</code> and
<code>format</code>.</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>The <code>encoding</code> argument can be <code>'latin1'</code>, <code>'hex'</code>, or <code>'base64'</code>. If
<code>encoding</code> is specified, a string is returned; otherwise a <a href="buffer.html#buffer_class_buffer"><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.html#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></li>
</ul>
<p>Sets the EC Diffie-Hellman private key. The <code>encoding</code> can be <code>'latin1'</code>,
<code>'hex'</code> or <code>'base64'</code>. 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#buffer_class_buffer"><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 ECDH 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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</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.html#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></li>
</ul>
<p>Sets the EC Diffie-Hellman public key. Key encoding can be <code>'latin1'</code>,
<code>'hex'</code> or <code>'base64'</code>. If <code>encoding</code> is provided <code>publicKey</code> is expected to
be a string; otherwise a <a href="buffer.html#buffer_class_buffer"><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="lang-js">const crypto = require('crypto');
const alice = crypto.createECDH('secp256k1');
const bob = crypto.createECDH('secp256k1');
// Note: This is a shortcut way to specify 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_stream">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.html#crypto_hash_update_data_inputencoding"><code>hash.update()</code></a> and <a href="crypto.html#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="lang-js">const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.on('readable', () => {
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="lang-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.html#crypto_hash_update_data_inputencoding"><code>hash.update()</code></a> and <a href="crypto.html#crypto_hash_digest_encoding"><code>hash.digest()</code></a> methods:</p>
<pre><code class="lang-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([encoding])<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></li>
</ul>
<p>Calculates the digest of all of the data passed to be hashed (using the
<a href="crypto.html#crypto_hash_update_data_inputencoding"><code>hash.update()</code></a> method). The <code>encoding</code> can be <code>'hex'</code>, <code>'latin1'</code> or
<code>'base64'</code>. If <code>encoding</code> is provided a string will be returned; otherwise
a <a href="buffer.html#buffer_class_buffer"><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>
<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>
</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.html#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></li>
</ul>
<p>Updates the hash content with the given <code>data</code>, the encoding of which
is given in <code>inputEncoding</code> and can be <code>'utf8'</code>, <code>'ascii'</code> or
<code>'latin1'</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#buffer_class_buffer"><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_stream">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="lang-js">const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret');
hmac.on('readable', () => {
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="lang-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="lang-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([encoding])<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></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>.
The <code>encoding</code> can be <code>'hex'</code>, <code>'latin1'</code> or <code>'base64'</code>. If <code>encoding</code> is
provided a string is returned; otherwise a <a href="buffer.html#buffer_class_buffer"><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>
<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>
</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.html#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></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> and can be <code>'utf8'</code>, <code>'ascii'</code> or
<code>'latin1'</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#buffer_class_buffer"><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_stream">stream</a>, where data to be signed is written and the
<a href="crypto.html#crypto_sign_sign_privatekey_outputformat"><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.html#crypto_sign_sign_privatekey_outputformat"><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="lang-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.html#crypto_sign_sign_privatekey_outputformat"><code>sign.sign()</code></a> methods:</p>
<pre><code class="lang-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="lang-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[, outputFormat])<span><a class="mark" href="#crypto_sign_sign_privatekey_outputformat" id="crypto_sign_sign_privatekey_outputformat">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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>
</table>
</details>
</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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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>
</ul>
</li>
<li><code>outputFormat</code> <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.html#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><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)</li>
<li><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</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><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.</li>
</ul>
<p>The <code>outputFormat</code> can specify one of <code>'latin1'</code>, <code>'hex'</code> or <code>'base64'</code>. If
<code>outputFormat</code> is provided a string is returned; otherwise a <a href="buffer.html#buffer_class_buffer"><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>
<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>
</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.html#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></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> and can be <code>'utf8'</code>, <code>'ascii'</code> or
<code>'latin1'</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#buffer_class_buffer"><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_stream">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_signatureformat"><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="lang-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_signatureformat"><code>verify.verify()</code></a> methods:</p>
<pre><code class="lang-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>
<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>
</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.html#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></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> and can be <code>'utf8'</code>, <code>'ascii'</code> or
<code>'latin1'</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#buffer_class_buffer"><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[, signatureFormat])<span><a class="mark" href="#crypto_verify_verify_object_signature_signatureformat" id="crypto_verify_verify_object_signature_signatureformat">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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>
</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.html#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>signatureFormat</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></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><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)</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><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.</li>
</ul>
<p>The <code>signature</code> argument is the previously calculated signature for the data, in
the <code>signatureFormat</code> which can be <code>'latin1'</code>, <code>'hex'</code> or <code>'base64'</code>.
If a <code>signatureFormat</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#buffer_class_buffer"><code>Buffer</code></a>,
<code>TypedArray</code>, or <code>DataView</code>.</p>
<p>Returns <code>true</code> or <code>false</code> depending on the validity of the signature for
the data and public key.</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><p>Returns 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>.</p>
<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>
</div><p>The default encoding to use for functions that can take either strings
or <a href="buffer.html#buffer_class_buffer">buffers</a>. The default value is <code>'buffer'</code>, which makes methods
default to <a href="buffer.html#buffer_class_buffer"><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>. This property may
become deprecated in a future Node.js release.</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>
</div><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>
<h3>crypto.createCipher(algorithm, password[, options])<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">
<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>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#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.html#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li>
</ul>
<p>Creates and returns a <code>Cipher</code> object that uses the given <code>algorithm</code> and
<code>password</code>. Optional <code>options</code> argument controls stream behavior.</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> 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#buffer_class_buffer"><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.0.2/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 PBKDF2 instead of
<a href="https://www.openssl.org/docs/man1.0.2/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.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback"><code>crypto.pbkdf2()</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])<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>
<tr><th>Version</th><th>Changes</th></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>
</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.html#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.html#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.html#stream_new_stream_transform_options"><code>stream.transform</code> options</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>). Optional <code>options</code> argument controls stream
behavior.</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> 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#buffer_class_buffer">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>
<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> instead.</div><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>
</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])<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">
<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>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#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.html#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li>
</ul>
<p>Creates and returns a <code>Decipher</code> object that uses the given <code>algorithm</code> and
<code>password</code> (key). Optional <code>options</code> argument controls stream behavior.</p>
<p>The implementation of <code>crypto.createDecipher()</code> derives keys using the OpenSSL
function <a href="https://www.openssl.org/docs/man1.0.2/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 PBKDF2 instead of
<a href="https://www.openssl.org/docs/man1.0.2/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.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback"><code>crypto.pbkdf2()</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])<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>
<tr><th>Version</th><th>Changes</th></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>
</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.html#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.html#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.html#stream_new_stream_transform_options"><code>stream.transform</code> options</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>). Optional <code>options</code> argument controls stream
behavior.</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> 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#buffer_class_buffer">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>
<h3>crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])<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>
<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>
</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.html#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></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.html#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> Defaults to
<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></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#buffer_class_buffer"><code>Buffer</code></a>. If
<code>generator</code> is not specified, the value <code>2</code> is used.</p>
<p>The <code>primeEncoding</code> and <code>generatorEncoding</code> arguments can be <code>'latin1'</code>,
<code>'hex'</code>, or <code>'base64'</code>.</p>
<p>If <code>primeEncoding</code> is specified, <code>prime</code> is expected to be a string; otherwise
a <a href="buffer.html#buffer_class_buffer"><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#buffer_class_buffer"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p>
<h3>crypto.createDiffieHellman(primeLength[, generator])<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.html#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> Defaults to
<code>2</code>.</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)<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>
</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.html#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])<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.html#stream_new_stream_transform_options"><code>stream.transform</code> options</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-message-digest-algorithms</code> will
display the available digest algorithms.</p>
<p>Example: generating the sha256 sum of a file</p>
<pre><code class="lang-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', () => {
const data = input.read();
if (data)
hash.update(data);
else {
console.log(`${hash.digest('hex')} ${filename}`);
}
});
</code></pre>
<h3>crypto.createHmac(algorithm, key[, options])<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.html#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.html#stream_new_stream_transform_options"><code>stream.transform</code> options</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-message-digest-algorithms</code> 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="lang-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', () => {
const data = input.read();
if (data)
hmac.update(data);
else {
console.log(`${hmac.digest('hex')} ${filename}`);
}
});
</code></pre>
<h3>crypto.createSign(algorithm[, options])<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.html#stream_constructor_new_stream_writable_options"><code>stream.Writable</code> options</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])<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.html#stream_constructor_new_stream_writable_options"><code>stream.Writable</code> options</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.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><p>Returns an array with the names of the supported cipher algorithms.</p>
<p>Example:</p>
<pre><code class="lang-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><p>Returns an array with the names of the supported elliptic curves.</p>
<p>Example:</p>
<pre><code class="lang-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>
</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="#fs_caveats">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="lang-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.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><p>Returns an array of the names of the supported hash algorithms,
such as <code>RSA-SHA256</code>.</p>
<p>Example:</p>
<pre><code class="lang-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>
<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>
</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.html#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></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.html#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></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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#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 null. By default, the successfully generated
<code>derivedKey</code> will be passed to the callback as a <a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a>. An error will be
thrown if any of the input arguments specify invalid values or types.</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 also be as unique as possible. It is recommended that the
salts are random and their lengths are at least 16 bytes. See
<a href="http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p>
<p>Example:</p>
<pre><code class="lang-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> may be used to change the way the <code>derivedKey</code>
is passed to the callback:</p>
<pre><code class="lang-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.html#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>
<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>
</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.html#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></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.html#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></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>
</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 Error will be thrown, otherwise the derived key will be
returned as a <a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a>.</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 also be as unique as possible. It is recommended that the
salts are random and their lengths are at least 16 bytes. See
<a href="http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p>
<p>Example:</p>
<pre><code class="lang-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.</p>
<pre><code class="lang-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><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><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.html#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>RSA_PKCS1_PADDING</code>, or <code>crypto.constants.RSA_PKCS1_OAEP_PADDING</code>.</li>
</ul>
</li>
<li><code>buffer</code> <a href="buffer.html#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.html#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>.</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><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><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.html#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>RSA_PKCS1_PADDING</code>.</li>
</ul>
</li>
<li><code>buffer</code> <a href="buffer.html#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.html#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>.</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><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><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.html#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>RSA_PKCS1_PADDING</code>.</li>
</ul>
</li>
<li><code>buffer</code> <a href="buffer.html#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.html#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>.</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><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><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.html#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>RSA_PKCS1_PADDING</code>, or <code>crypto.constants.RSA_PKCS1_OAEP_PADDING</code>.</li>
</ul>
</li>
<li><code>buffer</code> <a href="buffer.html#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.html#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#buffer_class_buffer"><code>Buffer</code></a> with encrypted content.</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>
<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>
</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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</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 Error object; otherwise it is null. The
<code>buf</code> argument is a <a href="buffer.html#buffer_class_buffer"><code>Buffer</code></a> containing the generated bytes.</p>
<pre><code class="lang-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#buffer_class_buffer"><code>Buffer</code></a>. An error will be thrown if
there is a problem generating the bytes.</p>
<pre><code class="lang-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.html#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>
<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</td>
<td><p><span>Added in: v7.10.0</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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> Defaults to <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> Defaults to <code>buffer.length - offset</code>.</li>
</ul>
<p>Synchronous version of <a href="#crypto_crypto_randomfill_buffer_offset_size_callback"><code>crypto.randomFill()</code></a>.</p>
<p>Returns <code>buffer</code></p>
<pre><code class="lang-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="lang-js">const a = new Uint32Array(10);
console.log(crypto.randomFillSync(a).toString('hex'));
const b = new Float64Array(10);
console.log(crypto.randomFillSync(a).toString('hex'));
const c = new DataView(new ArrayBuffer(10));
console.log(crypto.randomFillSync(a).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>
<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</td>
<td><p><span>Added in: v7.10.0</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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> Defaults to <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> Defaults to <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#buffer_class_buffer"><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="lang-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="lang-js">const a = new Uint32Array(10);
crypto.randomFill(a, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
const b = new Float64Array(10);
crypto.randomFill(b, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
const c = new DataView(new ArrayBuffer(10));
crypto.randomFill(c, (err, buf) => {
if (err) throw err;
console.log(buf.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.html#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.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.html#crypto_crypto_constants_1" class="type"><crypto.constants></a> Defaults to <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_ECDH</code></li>
<li><code>crypto.constants.ENGINE_METHOD_ECDSA</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_STORE</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>
<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.html#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.html#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>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#buffer_class_buffer"><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#stream_stream">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 Buffers. This
default was changed after Node.js v0.8 to use <a href="buffer.html#buffer_class_buffer"><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.html#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.html#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="http://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>
<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>
<table>
<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>
<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>
<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>
</table>
<h3>OpenSSL Engine Constants<span><a class="mark" href="#crypto_openssl_engine_constants" id="crypto_openssl_engine_constants">#</a></span></h3>
<table>
<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_ECDH</code></td>
<td>Limit engine usage to ECDH</td>
</tr>
<tr>
<td><code>ENGINE_METHOD_ECDSA</code></td>
<td>Limit engine usage to ECDSA</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_STORE</code></td>
<td>Limit engine usage to STORE</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>
</table>
<h3>Other OpenSSL Constants<span><a class="mark" href="#crypto_other_openssl_constants" id="crypto_other_openssl_constants">#</a></span></h3>
<table>
<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>NPN_ENABLED</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>
</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>
<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>
</table>
<!-- [end-include:crypto.md] -->
<!-- [start-include:debugger.md] -->
<h1>Debugger<span><a class="mark" href="#debugger_debugger" id="debugger_debugger">#</a></span></h1>
<!--introduced_in=v0.9.12-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><!-- type=misc -->
<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="lang-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="lang-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="lang-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>
<div class="signature"><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>
</div><h3>Breakpoints<span><a class="mark" href="#debugger_breakpoints" id="debugger_breakpoints">#</a></span></h3>
<div class="signature"><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
script.js</li>
<li><code>clearBreakpoint('script.js', 1)</code>, <code>cb(...)</code> - Clear breakpoint in script.js
on line 1</li>
</ul>
</div><p>It is also possible to set a breakpoint in a file (module) that
is not loaded yet:</p>
<pre><code class="lang-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>
<div class="signature"><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>
</div><h3>Execution control<span><a class="mark" href="#debugger_execution_control" id="debugger_execution_control">#</a></span></h3>
<div class="signature"><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>
</div><h3>Various<span><a class="mark" href="#debugger_various" id="debugger_various">#</a></span></h3>
<div class="signature"><ul>
<li><code>scripts</code> - List all loaded scripts</li>
<li><code>version</code> - Display V8's version</li>
</ul>
</div><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/debugger-protocol-viewer/">Chrome Debugging 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="lang-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/inspector.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>
<!-- [end-include:debugger.md] -->
<!-- [start-include:deprecations.md] -->
<h1>Deprecated APIs<span><a class="mark" href="#deprecations_deprecated_apis" id="deprecations_deprecated_apis">#</a></span></h1>
<!--introduced_in=v7.7.0-->
<p>Node.js may deprecate APIs when either: (a) use of the API is considered to be
unsafe, (b) an improved alternative API has been made 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 [<code>--pending-deprecation</code>][] 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 to identify code that either has been
removed or will soon be removed from Node.js.</p>
<h2>Un-deprecation<span><a class="mark" href="#deprecations_un_deprecation" id="deprecations_un_deprecation">#</a></span></h2>
<p>From time-to-time the deprecation of an API may be reversed. Such action may
happen in either a semver-minor or semver-major release. In such situations,
this document will be updated with information relevant to the decision.
<em>However, the deprecation identifier will not be modified</em>.</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>
<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>
<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>
<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>
<p>Type: Documentation-only</p>
<p>The <code>CryptoStream.prototype.readyState</code> property is deprecated and should not
be used.</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>
<p>Type: Documentation-only (supports [<code>--pending-deprecation</code>][])</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.html#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.html#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.html#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.html#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.html#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.html#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.html#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><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>
<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>
<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.html#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>
<p>Type: Documentation-only</p>
<p>The <code>constants</code> module has been 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>
<p>Type: End-of-life</p>
<p>Use of the <a href="crypto.html#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>
<p>Type: Runtime</p>
<p>The <a href="crypto.html#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>
<p>Type: Runtime</p>
<p>The <code>crypto.Credentials</code> class is deprecated. Please use <a href="tls.html#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>
<p>Type: End-of-Life</p>
<p><code>Domain.dispose()</code> is 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>
<p>Type: Runtime</p>
<p>Calling an asynchronous function without a callback is deprecated.</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>
<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 String interface is deprecated. Use the Buffer 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>
<p>Type: End-of-Life</p>
<p>The <a href="fs.html#fs_fs_readsync_fd_buffer_offset_length_position"><code>fs.readSync()</code></a> legacy String interface is deprecated. Use the Buffer
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>
<p>Type: Runtime</p>
<p>The <code>GLOBAL</code> and <code>root</code> aliases for the <code>global</code> property have been 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>
<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>
<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>
<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>
<p>Type: Runtime</p>
<p>The <a href="net.html#net_server_connections"><code>Server.connections</code></a> property is deprecated. Please use the
<a href="net.html#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>
<p>Type: Runtime</p>
<p>The <code>Server.listenFD()</code> method is deprecated. Please use
<a href="net.html#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>
<p>Type: Runtime</p>
<p>The <code>os.tmpDir()</code> API is deprecated. Please use <a href="os.html#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>
<p>Type: Runtime</p>
<p>The <code>os.getNetworkInterfaces()</code> method is deprecated. Please use the
<a href="os.html#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>
<p>Type: End-of-Life</p>
<p>The <code>REPLServer.prototype.convertToContext()</code> API is deprecated and should
not be used.</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>
<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>
<p>Type: Runtime</p>
<p>The <a href="util.html#util_util_print_strings"><code>util.print()</code></a> API is deprecated. Please use <a href="console.html#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>
<p>Type: Runtime</p>
<p>The <a href="util.html#util_util_puts_strings"><code>util.puts()</code></a> API is deprecated. Please use <a href="console.html#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>
<p>Type: Runtime</p>
<p>The <a href="util.html#util_util_debug_string"><code>util.debug()</code></a> API is deprecated. Please use <a href="console.html#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>
<p>Type: Runtime</p>
<p>The <a href="util.html#util_util_error_strings"><code>util.error()</code></a> API is deprecated. Please use <a href="console.html#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>
<p>Type: Documentation-only</p>
<p>The <a href="buffer.html#buffer_class_slowbuffer"><code>SlowBuffer</code></a> class has been deprecated. Please use
<a href="buffer.html#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>
<p>Type: Documentation-only</p>
<p>The <a href="crypto.html#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>
<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>
<p>Type: Documentation-only</p>
<p>The <a href="events.html#events_eventemitter_listenercount_emitter_eventname"><code>EventEmitter.listenerCount(emitter, eventName)</code></a> API has been
deprecated. Please use <a href="events.html#events_emitter_listenercount_eventname"><code>emitter.listenerCount(eventName)</code></a> instead.</p>
<p><a id="DEP0034"></a></p>
<h3>DEP0034: fs.exists(path, callback)<span><a class="mark" href="#deprecations_dep0034_fs_exists_path_callback" id="deprecations_dep0034_fs_exists_path_callback">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="fs.html#fs_fs_exists_path_callback"><code>fs.exists(path, callback)</code></a> API has been deprecated. Please use
<a href="#fs_fs_stat_path_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>
<p>Type: Documentation-only</p>
<p>The <a href="fs.html#fs_fs_lchmod_path_mode_callback"><code>fs.lchmod(path, mode, callback)</code></a> API has been 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>
<p>Type: Documentation-only</p>
<p>The <a href="fs.html#fs_fs_lchmodsync_path_mode"><code>fs.lchmodSync(path, mode)</code></a> API has been deprecated.</p>
<p><a id="DEP0037"></a></p>
<h3>DEP0037: fs.lchown(path, uid, gid, callback)<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>
<p>Type: Documentation-only</p>
<p>The <a href="fs.html#fs_fs_lchown_path_uid_gid_callback"><code>fs.lchown(path, uid, gid, callback)</code></a> API has been deprecated.</p>
<p><a id="DEP0038"></a></p>
<h3>DEP0038: fs.lchownSync(path, uid, gid)<span><a class="mark" href="#deprecations_dep0038_fs_lchownsync_path_uid_gid" id="deprecations_dep0038_fs_lchownsync_path_uid_gid">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="fs.html#fs_fs_lchownsync_path_uid_gid"><code>fs.lchownSync(path, uid, gid)</code></a> API has been 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>
<p>Type: Documentation-only</p>
<p>The <a href="modules.html#modules_require_extensions"><code>require.extensions</code></a> property has been 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>
<p>Type: Documentation-only</p>
<p>The <a href="punycode.html"><code>punycode</code></a> module has been 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>
<p>Type: Documentation-only</p>
<p>The <code>NODE_REPL_HISTORY_FILE</code> environment variable has been deprecated.</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>
<p>Type: Documentation-only</p>
<p>The <a href="tls.html#tls_class_cryptostream"><code>tls.CryptoStream</code></a> class has been deprecated. 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>
<p>Type: Documentation-only</p>
<p>The <a href="tls.html#tls_class_securepair"><code>tls.SecurePair</code></a> class has been 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>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isarray_object"><code>util.isArray()</code></a> API has been deprecated. Please use <code>Array.isArray()</code>
instead.</p>
<p><a id="DEP0045"></a></p>
<h3>DEP0045: util.isBoolean()<span><a class="mark" href="#deprecations_dep0045_util_isboolean" id="deprecations_dep0045_util_isboolean">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isboolean_object"><code>util.isBoolean()</code></a> API has been 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>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isbuffer_object"><code>util.isBuffer()</code></a> API has been deprecated. Please use
<a href="buffer.html#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>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isdate_object"><code>util.isDate()</code></a> API has been 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>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_iserror_object"><code>util.isError()</code></a> API has been deprecated.</p>
<p><a id="DEP0049"></a></p>
<h3>DEP0049: util.isFunction()<span><a class="mark" href="#deprecations_dep0049_util_isfunction" id="deprecations_dep0049_util_isfunction">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isfunction_object"><code>util.isFunction()</code></a> API has been deprecated.</p>
<p><a id="DEP0050"></a></p>
<h3>DEP0050: util.isNull()<span><a class="mark" href="#deprecations_dep0050_util_isnull" id="deprecations_dep0050_util_isnull">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isnull_object"><code>util.isNull()</code></a> API has been deprecated.</p>
<p><a id="DEP0051"></a></p>
<h3>DEP0051: util.isNullOrUndefined()<span><a class="mark" href="#deprecations_dep0051_util_isnullorundefined" id="deprecations_dep0051_util_isnullorundefined">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isnullorundefined_object"><code>util.isNullOrUndefined()</code></a> API has been deprecated.</p>
<p><a id="DEP0052"></a></p>
<h3>DEP0052: util.isNumber()<span><a class="mark" href="#deprecations_dep0052_util_isnumber" id="deprecations_dep0052_util_isnumber">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isnumber_object"><code>util.isNumber()</code></a> API has been 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>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isobject_object"><code>util.isObject()</code></a> API has been deprecated.</p>
<p><a id="DEP0054"></a></p>
<h3>DEP0054: util.isPrimitive()<span><a class="mark" href="#deprecations_dep0054_util_isprimitive" id="deprecations_dep0054_util_isprimitive">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isprimitive_object"><code>util.isPrimitive()</code></a> API has been 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>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isregexp_object"><code>util.isRegExp()</code></a> API has been deprecated.</p>
<p><a id="DEP0056"></a></p>
<h3>DEP0056: util.isString()<span><a class="mark" href="#deprecations_dep0056_util_isstring" id="deprecations_dep0056_util_isstring">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isstring_object"><code>util.isString()</code></a> API has been deprecated.</p>
<p><a id="DEP0057"></a></p>
<h3>DEP0057: util.isSymbol()<span><a class="mark" href="#deprecations_dep0057_util_issymbol" id="deprecations_dep0057_util_issymbol">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_issymbol_object"><code>util.isSymbol()</code></a> API has been deprecated.</p>
<p><a id="DEP0058"></a></p>
<h3>DEP0058: util.isUndefined()<span><a class="mark" href="#deprecations_dep0058_util_isundefined" id="deprecations_dep0058_util_isundefined">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_isundefined_object"><code>util.isUndefined()</code></a> API has been deprecated.</p>
<p><a id="DEP0059"></a></p>
<h3>DEP0059: util.log()<span><a class="mark" href="#deprecations_dep0059_util_log" id="deprecations_dep0059_util_log">#</a></span></h3>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_log_string"><code>util.log()</code></a> API has been 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>
<p>Type: Documentation-only</p>
<p>The <a href="util.html#util_util_extend_target_source"><code>util._extend()</code></a> API has been 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>
<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>
<p>Type: Runtime</p>
<p><code>--debug</code> activates the legacy V8 debugger interface, which has been 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>
<p>Type: Documentation-only</p>
<p>The <code>http</code> module <code>ServerResponse.prototype.writeHeader()</code> API has been
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>
<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>
<p>Type: Documentation-only</p>
<p>The <code>repl</code> module's <code>REPL_MODE_MAGIC</code> constant, used for <code>replMode</code> option, has
been deprecated. Its behavior has been functionally identical to that of
<code>REPL_MODE_SLOPPY</code> since Node.js v6.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 default value, <code>magic</code>, is
similarly deprecated in favor of <code>sloppy</code>.</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>
<p>Type: Documentation-only</p>
<p>The <code>http</code> module <code>outgoingMessage._headers</code> and <code>outgoingMessage._headerNames</code>
properties have been deprecated. Please instead 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>
<p>Type: Documentation-only</p>
<p>The <code>http</code> module <code>OutgoingMessage.prototype._renderHeaders()</code> API has been
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>
<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>
<p>Type: Runtime</p>
<p>The DebugContext will be removed in V8 soon and will not be available in Node
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>
<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>
<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>
<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>
<p>Type: Runtime</p>
<p>Accessing several internal, undocumented properties of <code>net.Server</code> instances
with inappropriate names has been 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>
<p>Type: Runtime</p>
<p>The <code>REPLServer.bufferedCommand</code> property was deprecated in favor of
<a href="repl.html#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>
<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>
<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="lang-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="lang-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>
<p>Type: Runtime</p>
<p><code>Module._debug()</code> has been 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>
<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>
<p>Type: Documentation-only</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.html#util_util_inspect_custom"><code>util.inspect.custom</code></a>
instead. For backwards 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>
<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 has been 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<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>
<p>Type: Runtime</p>
<p><code>fs.truncate()</code> <code>fs.truncateSync()</code> usage with a file descriptor has been
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>
<p>Type: Runtime</p>
<p><code>REPLServer.prototype.memory()</code> is a function only necessary for the
internal mechanics of the <code>REPLServer</code> itself, and is therefore not
necessary in user space.</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>
<p>Type: Runtime</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 is
deprecated in preparation for migrating to OpenSSL 1.1.0 and consistency with
the client. Use the <code>ciphers</code> parameter instead.</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>
<p>Type: Runtime</p>
<p>The AsyncHooks Sensitive API was never documented and had various of 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>
<p>Type: Runtime</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>
<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="DEP0098"></a></p>
<h3>DEP0098: AsyncHooks Embedder AsyncResource.emit<span class="type"><Before,After></span> APIs<span><a class="mark" href="#deprecations_dep0098_asynchooks_embedder_asyncresource_emit_span_class_type_lt_before_after_gt_span_apis" id="deprecations_dep0098_asynchooks_embedder_asyncresource_emit_span_class_type_lt_before_after_gt_span_apis">#</a></span></h3>
<p>Type: Runtime</p>
<p>The embedded API provided by AsyncHooks exposes emit<span class="type"><Before,After></span> methods
which are very easy to use incorrectly which can lead to unrecoverable errors.</p>
<p>Use <a href="async_hooks.html#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>
<!-- [end-include:deprecations.md] -->
<!-- [start-include:dns.md] -->
<h1>DNS<span><a class="mark" href="#dns_dns" id="dns_dns">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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.html#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.html#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="lang-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.html#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.html#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="lang-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 dns.Resolver<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 resolver:</p>
<pre><code class="lang-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_setservers_servers"><code>resolver.setServers()</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>
</ul>
<h3>resolver.cancel()<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>dns.getServers()<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><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="lang-js">[
'4.4.4.4',
'2001:4860:4860::8888',
'4.4.4.4:1053',
'[2001:4860:4860::8888]:1053'
]
</code></pre>
<h2>dns.lookup(hostname[, options], callback)<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>
<tr><th>Version</th><th>Changes</th></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>
</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><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><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#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="lang-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 Promise for an object 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.html#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>dns.lookupService(address, port, callback)<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is the error code.</p>
<pre><code class="lang-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
Promise for an object with <code>hostname</code> and <code>service</code> properties.</p>
<h2>dns.resolve(hostname[, rrtype], callback)<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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>'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>
<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>
</tbody>
</table>
<p>On error, <code>err</code> is an <a href="errors.html#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>dns.resolve4(hostname[, options], callback)<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>
<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>
</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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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>dns.resolve6(hostname[, options], callback)<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>
<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>
</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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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>dns.resolveCname(hostname, callback)<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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>dns.resolveMx(hostname, callback)<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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>dns.resolveNaptr(hostname, callback)<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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="lang-js">{
flags: 's',
service: 'SIP+D2U',
regexp: '',
replacement: '_sip._udp.example.com',
order: 30,
preference: 100
}
</code></pre>
<h2>dns.resolveNs(hostname, callback)<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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>dns.resolvePtr(hostname, callback)<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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>dns.resolveSoa(hostname, callback)<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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="lang-js">{
nsname: 'ns.example.com',
hostmaster: 'root.example.com',
serial: 2013101809,
refresh: 10000,
retry: 2400,
expire: 604800,
minttl: 3600
}
</code></pre>
<h2>dns.resolveSrv(hostname, callback)<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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="lang-js">{
priority: 10,
weight: 5,
port: 21223,
name: 'service.example.com'
}
</code></pre>
<h2>dns.resolveTxt(hostname, callback)<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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></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>dns.resolveAny(hostname, callback)<span><a class="mark" href="#dns_dns_resolveany_hostname_callback" id="dns_dns_resolveany_hostname_callback">#</a></span></h2>
<div class="signature"><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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>
</div><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>, eg. <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="lang-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>
<h2>dns.reverse(ip, callback)<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#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>dns.setServers(servers)<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="lang-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>
<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 iphlpapi.dll.</li>
<li><code>dns.ADDRGETNETWORKPARAMS</code>: Could not find GetNetworkParams 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.html#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.html#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.html#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.html#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">nsswitch.conf(5)</a> and/or <a href="http://man7.org/linux/man-pages/man5/resolv.conf.5.html">resolv.conf(5)</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">getaddrinfo(3)</a> that runs
on libuv's threadpool. This can have surprising negative performance
implications for some applications, see the <a href="cli.html#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 and 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"><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.html#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">getaddrinfo(3)</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.html#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.html#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>
<!-- [end-include:dns.md] -->
<!-- [start-include:domain.md] -->
<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>
<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>
</table>
</details>
</div><!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><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>
<!-- type=misc -->
<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 you 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="lang-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="lang-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}`);
// Note: 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>
<!-- type=misc -->
<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>
<!--type=misc-->
<p>If domains are in use, then all <strong>new</strong> EventEmitter 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 fs.open, 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, Domain 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 Domain objects as children of a parent Domain they must be explicitly
added.</p>
<p>Implicit binding routes thrown errors and <code>'error'</code> events to the
Domain's <code>'error'</code> event, but does not register the EventEmitter on the
Domain.
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>
<!--type=misc-->
<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="lang-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>
<div class="signature"><ul>
<li>Returns: <a href="domain.html#domain_class_domain" class="type"><Domain></a></li>
</ul>
</div><p>Returns a new Domain object.</p>
<h2>Class: Domain<span><a class="mark" href="#domain_class_domain" id="domain_class_domain">#</a></span></h2>
<p>The Domain class encapsulates the functionality of routing errors and
uncaught exceptions to the active Domain object.</p>
<p>Domain is a child class of <a href="events.html"><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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li><code>emitter</code> <a href="events.html#events_class_eventemitter" class="type"><EventEmitter></a> | <a href="timers.html#timers_timers" class="type"><Timer></a> emitter or timer to be added to the domain</li>
</ul>
</div><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.html#timers_setinterval_callback_delay_args"><code>setInterval()</code></a> and
<a href="timers.html#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a>. If their callback function throws, it will be caught by
the domain 'error' handler.</p>
<p>If the Timer or EventEmitter 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>
<div class="signature"><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>
</div><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>
<h4>Example<span><a class="mark" href="#domain_example" id="domain_example">#</a></span></h4>
<pre><code class="lang-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>
<div class="signature"><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>
</div><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.html#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>
<h4>Example<span><a class="mark" href="#domain_example_1" id="domain_example_1">#</a></span></h4>
<pre><code class="lang-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>
<div class="signature"><ul>
<li><code>emitter</code> <a href="events.html#events_class_eventemitter" class="type"><EventEmitter></a> | <a href="timers.html#timers_timers" class="type"><Timer></a> emitter or timer to be removed from the domain</li>
</ul>
</div><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>
<div class="signature"><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> <span class="type"><any></span></li>
</ul>
</div><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>
<p>Example:</p>
<pre><code class="lang-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 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="lang-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="lang-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 Promise
rejections.</p>
<!-- [end-include:domain.md] -->
<!-- [start-include:esm.md] -->
<h1>ECMAScript Modules<span><a class="mark" href="#esm_ecmascript_modules" id="esm_ecmascript_modules">#</a></span></h1>
<!--introduced_in=v8.5.0-->
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><!--name=esm-->
<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>
<!-- type=misc -->
<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="lang-sh">node --experimental-modules my-app.mjs
</code></pre>
<h2>Features<span><a class="mark" href="#esm_features" id="esm_features">#</a></span></h2>
<!-- type=misc -->
<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>
<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 language standard <code>import()</code></td>
</tr>
<tr>
<td><code>import()</code></td>
<td>pending newer V8 release used in Node.js</td>
</tr>
<tr>
<td><code>import.meta</code></td>
<td>pending V8 implementation</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="lang-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="lang-js">import fs from 'fs';
fs.readFile('./foo.txt', (err, body) => {
if (err) {
console.error(err);
} else {
console.log(body);
}
});
</code></pre>
<h2>Loader hooks<span><a class="mark" href="#esm_loader_hooks" id="esm_loader_hooks">#</a></span></h2>
<!-- type=misc -->
<p>To customize the default module resolution, loader hooks can optionally be
provided via a <code>--loader ./loader-name.mjs</code> argument to Node.</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="lang-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 parentURL 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 builtin modules support could
be written:</p>
<pre><code class="lang-js">import url from 'url';
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.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="lang-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="lang-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>
<!-- [end-include:esm.md] -->
<!-- [start-include:errors.md] -->
<h1>Errors<span><a class="mark" href="#errors_errors" id="errors_errors">#</a></span></h1>
<!--introduced_in=v4.0.0-->
<!--type=misc-->
<p>Applications running in Node.js will generally experience four categories of
errors:</p>
<ul>
<li>Standard JavaScript errors such as:<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError" class="type"><EvalError></a> : thrown when a call to <code>eval()</code> fails.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError" class="type"><SyntaxError></a> : thrown in response to improper JavaScript language
syntax.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError" class="type"><RangeError></a> : thrown when a value is not within an expected range</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError" class="type"><ReferenceError></a> : thrown when using undefined variables</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError" class="type"><TypeError></a> : thrown when passing arguments of the wrong type</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError" class="type"><URIError></a> : thrown when a global URI handling function is misused.</li>
</ul>
</li>
<li>System errors triggered by underlying operating system constraints such
as attempting to open a file that does not exist, attempting to send data
over a closed socket, etc;</li>
<li>And User-specified errors triggered by application code.</li>
<li>Assertion Errors are a special class 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.</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>
<!--type=misc-->
<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 Error 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="lang-js">// Throws with a ReferenceError because z is undefined
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.html#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="lang-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.html"><code>EventEmitter</code></a>, errors can be routed to that object's <code>'error'</code> event.</p>
<pre><code class="lang-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.html#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.html"><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
unhandled 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.html#process_event_uncaughtexception"><code>process.on('uncaughtException')</code></a> event.</p>
<pre><code class="lang-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>
<!--type=misc-->
<p>Most asynchronous methods exposed by the Node.js core API follow an idiomatic
pattern referred to as an <em>error-first callback</em> (sometimes referred to as
a <em>Node.js style 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 Error 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="lang-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="lang-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>
<!--type=class-->
<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>
<div class="signature"><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>
</div><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>
<div class="signature"><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>
</div><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="lang-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="lang-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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>The <code>error.code</code> property is a string label that identifies the kind of error.
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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><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="lang-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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><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="lang-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="lang-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. Such errors
commonly indicate inequality of actual and expected value.</p>
<pre><code class="lang-js">assert.strictEqual(1, 2);
// AssertionError [ERR_ASSERTION]: 1 === 2
</code></pre>
<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="lang-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="lang-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="lang-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 TypeError.</p>
<pre><code class="lang-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>
<!--type=misc-->
<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 Error.</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>System errors are generated when exceptions occur within the program's
runtime environment. Typically, these are operational errors that occur
when an application violates an operating system constraint such as attempting
to read a file that does not exist or when the user does not have sufficient
permissions.</p>
<p>System errors are typically generated at the syscall level: an exhaustive list
of error codes and their meanings is available by running <code>man 2 intro</code> or
<code>man 3 errno</code> on most Unices; or <a href="http://man7.org/linux/man-pages/man3/errno.3.html">online</a>.</p>
<p>In Node.js, system errors are represented as augmented <code>Error</code> objects with
added properties.</p>
<h3>Class: System Error<span><a class="mark" href="#errors_class_system_error" id="errors_class_system_error">#</a></span></h3>
<h4>error.code<span><a class="mark" href="#errors_error_code_1" id="errors_error_code_1">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>The <code>error.code</code> property is a string representing the error code, which is
typically <code>E</code> followed by a sequence of capital letters.</p>
<h4>error.errno<span><a class="mark" href="#errors_error_errno" id="errors_error_errno">#</a></span></h4>
<div class="signature"><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>
</div><p>The <code>error.errno</code> property is a number or a string.
The number is a <strong>negative</strong> 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 uv-errno.h 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.syscall<span><a class="mark" href="#errors_error_syscall" id="errors_error_syscall">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>The <code>error.syscall</code> property is a string describing the <a href="http://man7.org/linux/man-pages/man2/syscall.2.html">syscall</a> that failed.</p>
<h4>error.path<span><a class="mark" href="#errors_error_path" id="errors_error_path">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>When present (e.g. in <code>fs</code> or <code>child_process</code>), the <code>error.path</code> property is a
string containing a relevant invalid pathname.</p>
<h4>error.address<span><a class="mark" href="#errors_error_address" id="errors_error_address">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>When present (e.g. in <code>net</code> or <code>dgram</code>), the <code>error.address</code> property is a
string describing the address to which the connection failed.</p>
<h4>error.port<span><a class="mark" href="#errors_error_port" id="errors_error_port">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><p>When present (e.g. in <code>net</code> or <code>dgram</code>), the <code>error.port</code> property is a number
representing the connection's port that is not available.</p>
<h3>Common System Errors<span><a class="mark" href="#errors_common_system_errors" id="errors_common_system_errors">#</a></span></h3>
<p>This list is <strong>not exhaustive</strong>, but enumerates many of the common system
errors encountered when writing a Node.js program. An exhaustive list may be
found <a href="http://man7.org/linux/man-pages/man3/errno.3.html">here</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.html#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.html#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_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_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_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_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_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_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.html#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.html#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.html#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.html#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.html#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_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.html#crypto_crypto_gethashes">crypto digest algorithm</a> was specified.</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.html#crypto_sign_sign_privatekey_outputformat"><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.html#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.html#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.html#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.html#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_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_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_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_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_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_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_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_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_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 something other than a regular file.</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_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_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_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_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.html#child_process_subprocess_send_message_sendhandle_options_callback"><code>subprocess.send()</code></a> and <a href="process.html#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_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>Uint8Array</code> or <code>string</code> was provided as stdio input to a
synchronous 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>
<p>Example:</p>
<pre><code class="lang-js">const { URLSearchParams } = require('url');
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_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.html#url_the_whatwg_url_api">WHATWG</a>
<a href="url.html#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.html#url_the_whatwg_url_api">WHATWG</a>
<a href="url.html#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.html#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_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_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>
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p>An <a href="esm.html">ES6 module</a> could not be resolved.</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>
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><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_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.html#intl_options_for_building_node_js">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>An input argument value was outside an acceptable 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>
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p>An attempt was made to <code>require()</code> an <a href="esm.html">ES6 module</a>.</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.html#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 Server 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_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>
<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>
<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_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.html#stream_class_stream_writable"><code>Writable</code></a> stream.</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.html#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> with a <code>null</code> chunk.</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.html#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_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>
<p>An attempt was made to use a readable stream that did not implement
<a href="stream.html#stream_readable_read_size_1"><code>readable._read()</code></a>.</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.html#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>
<p>Example</p>
<pre><code class="lang-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.html#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> after <code>stream.end()</code> has been
called.</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
subjectAltNames 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_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_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 Transform 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 Transform stream finished with data still in the write buffer.</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.html#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.html"><code>EventEmitter</code></a> but an <code>'error'</code> handler is not registered).</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>
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><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>
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><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.html#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 BreakIterator 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_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>
<p>A given value is out of the accepted range.</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.Module</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_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>
<p>An attempt was made to use a <code>zlib</code> object after it has already been closed.</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>
<!-- [end-include:errors.md] -->
<!-- [start-include:events.md] -->
<h1>Events<span><a class="mark" href="#events_events" id="events_events">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><!--type=module-->
<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")
periodically emit named events that cause Function objects ("listeners") to be
called.</p>
<p>For instance: a <a href="net.html#net_class_net_server"><code>net.Server</code></a> object emits an event each time a peer
connects to it; a <a href="fs.html#fs_class_fs_readstream"><code>fs.ReadStream</code></a> emits an event when the file is opened;
a <a href="stream.html#stream_stream">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="lang-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 by the <code>EventEmitter</code>, the standard <code>this</code>
keyword is intentionally set to reference the <code>EventEmitter</code> to which the
listener is attached.</p>
<pre><code class="lang-js">const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
console.log(a, b, this);
// Prints:
// a b MyEmitter {
// domain: null,
// _events: { event: [Function] },
// _eventsCount: 1,
// _maxListeners: undefined }
});
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="lang-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="lang-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="lang-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="lang-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="lang-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 has been deprecated.)</p>
<p>As a best practice, listeners should always be added for the <code>'error'</code> events.</p>
<pre><code class="lang-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="lang-js">const EventEmitter = require('events');
</code></pre>
<p>All EventEmitters 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="lang-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>
<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>
</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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#events_emitter_listenercount_eventname"><code>emitter.listenerCount()</code></a> instead.</div><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="lang-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="lang-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.html#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.html#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>
<li><code>...args</code> <span class="type"><any></span></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><p>Returns an array listing the events for which the emitter has registered
listeners. The values in the array will be strings or Symbols.</p>
<pre><code class="lang-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><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>
</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>
<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>
</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>
</ul>
<p>Returns a copy of the array of listeners for the event named <code>eventName</code>.</p>
<pre><code class="lang-js">server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
</code></pre>
<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>
</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="lang-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="lang-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>
</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="lang-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="lang-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>
</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="lang-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>
</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="lang-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>
</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>
</ul>
<p>Removes the specified <code>listener</code> from the listener array for the event named
<code>eventName</code>.</p>
<pre><code class="lang-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="lang-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>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>
</ul>
<p>By default EventEmitters 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>
</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="lang-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>
<!-- [end-include:events.md] -->
<!-- [start-include:fs.md] -->
<h1>File System<span><a class="mark" href="#fs_file_system" id="fs_file_system">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><!--name=fs-->
<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="lang-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="lang-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="lang-js">const fs = require('fs');
try {
fs.unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
} catch (err) {
// handle the error
}
</code></pre>
<p>Note that 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="lang-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="lang-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="lang-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.html#buffer_class_buffer"><code>Buffer</code></a>, or a <a href="url.html#url_class_url"><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="lang-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="lang-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.html#buffer_class_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="lang-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><em>Note:</em> 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://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#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.html#url_class_url"><code>URL</code></a> object. Only <a href="url.html#url_class_url"><code>URL</code></a> objects using the <code>file:</code> protocol
are supported.</p>
<pre><code class="lang-js">const fs = require('fs');
const { URL } = require('url');
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.html#url_class_url"><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="lang-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="lang-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="lang-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="lang-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="lang-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>Note that 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.html#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</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.html#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="lang-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: '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.</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.html#stream_class_stream_readable">Readable Streams</a>.</p>
<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: 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 ReadStream.</li>
</ul>
<p>Emitted when the <code>fs.ReadStream</code>'s file descriptor has been opened.</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>Value: <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>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#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>
<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>
<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>
</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_callback"><code>fs.stat()</code></a>, <a href="#fs_fs_lstat_path_callback"><code>fs.lstat()</code></a> and <a href="#fs_fs_fstat_fd_callback"><code>fs.fstat()</code></a> and
their synchronous counterparts are of this type.</p>
<pre><code class="lang-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>
<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_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>
<div class="signature"><ul>
<li>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></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>Value: <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>Value: <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>Value: <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>Value: <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/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">mknod(2)</a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html">utimes(2)</a>, and <a href="http://man7.org/linux/man-pages/man2/read.2.html">read(2)</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">mknod(2)</a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html">utimes(2)</a>, and <a href="http://man7.org/linux/man-pages/man2/write.2.html">write(2)</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">chmod(2)</a>, <a href="http://man7.org/linux/man-pages/man2/chown.2.html">chown(2)</a>,
<a href="http://man7.org/linux/man-pages/man2/link.2.html">link(2)</a>, <a href="http://man7.org/linux/man-pages/man2/mknod.2.html">mknod(2)</a>, <a href="http://man7.org/linux/man-pages/man2/rename.2.html">rename(2)</a>, <a href="http://man7.org/linux/man-pages/man2/unlink.2.html">unlink(2)</a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html">utimes(2)</a>,
<a href="http://man7.org/linux/man-pages/man2/read.2.html">read(2)</a>, and <a href="http://man7.org/linux/man-pages/man2/write.2.html">write(2)</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>). Note that 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">utimes(2)</a> system call.</li>
</ul>
<p>Prior to Node.js v0.12, the <code>ctime</code> held the <code>birthtime</code> on Windows
systems. Note that as of v0.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.html#stream_writable_streams">Writable Stream</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>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 WriteStream.</li>
</ul>
<p>Emitted when the WriteStream's file is opened.</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 <code>fs.createWriteStream()</code>. 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>
<h2>fs.access(path[, mode], callback)<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>
<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 <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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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. The following constants define the 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>
<ul>
<li><code>fs.constants.F_OK</code> - <code>path</code> 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 <code>mode</code> is specified.</li>
<li><code>fs.constants.R_OK</code> - <code>path</code> can be read by the calling process.</li>
<li><code>fs.constants.W_OK</code> - <code>path</code> can be written by the calling process.</li>
<li><code>fs.constants.X_OK</code> - <code>path</code> can be executed by the calling process. This has
no effect on Windows (will behave like <code>fs.constants.F_OK</code>).</li>
</ul>
<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 example checks if the file
<code>/etc/passwd</code> can be read and written by the current process.</p>
<pre><code class="lang-js">fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
console.log(err ? 'no access!' : 'can read/write');
});
</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="lang-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="lang-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="lang-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="lang-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>
<h2>fs.accessSync(path[, mode])<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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. The following constants define the
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>
<ul>
<li><code>fs.constants.F_OK</code> - <code>path</code> 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 <code>mode</code> is specified.</li>
<li><code>fs.constants.R_OK</code> - <code>path</code> can be read by the calling process.</li>
<li><code>fs.constants.W_OK</code> - <code>path</code> can be written by the calling process.</li>
<li><code>fs.constants.X_OK</code> - <code>path</code> can be executed by the calling process. This has
no effect on Windows (will behave like <code>fs.constants.F_OK</code>).</li>
</ul>
<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="lang-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(file, data[, options], callback)<span><a class="mark" href="#fs_fs_appendfile_file_data_options_callback" id="fs_fs_appendfile_file_data_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tr><th>Version</th><th>Changes</th></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.</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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#buffer_class_buffer" class="type"><Buffer></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><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> <strong>Default:</strong> <code>'a'</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><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.html#buffer_class_buffer"><code>Buffer</code></a>.</p>
<p>Example:</p>
<pre><code class="lang-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. Example:</p>
<pre><code class="lang-js">fs.appendFile('message.txt', 'data to append', 'utf8', callback);
</code></pre>
<p>The <code>file</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="lang-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(file, data[, options])<span><a class="mark" href="#fs_fs_appendfilesync_file_data_options" id="fs_fs_appendfilesync_file_data_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#buffer_class_buffer" class="type"><Buffer></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><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> <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.html#buffer_class_buffer"><code>Buffer</code></a>.</p>
<p>Example:</p>
<pre><code class="lang-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. Example:</p>
<pre><code class="lang-js">fs.appendFileSync('message.txt', 'data to append', 'utf8');
</code></pre>
<p>The <code>file</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="lang-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)<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>
<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 <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</p>
</td></tr>
<tr><td>v0.1.30</td>
<td><p><span>Added in: v0.1.30</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">chmod(2)</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>
<h2>fs.chmodSync(path, mode)<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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>Synchronously changes the permissions of a file. Returns <code>undefined</code>.
This is the synchronous version of <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">chmod(2)</a></p>
<h2>fs.chown(path, uid, gid, callback)<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>
<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 <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</p>
</td></tr>
<tr><td>v0.1.97</td>
<td><p><span>Added in: v0.1.97</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">chown(2)</a></p>
<h2>fs.chownSync(path, uid, gid)<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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">chown(2)</a></p>
<h2>fs.close(fd, callback)<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>
<tr><th>Version</th><th>Changes</th></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.</p>
</td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p>
</td></tr>
</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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">close(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.closeSync(fd)<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">close(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.constants<span><a class="mark" href="#fs_fs_constants" id="fs_fs_constants">#</a></span></h2>
<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)<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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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. The only supported flag is <code>fs.constants.COPYFILE_EXCL</code>,
which causes the copy operation to fail if <code>dest</code> already exists.</p>
<p>Example:</p>
<pre><code class="lang-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>, as shown in the
following example.</p>
<pre><code class="lang-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])<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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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. The only supported flag is <code>fs.constants.COPYFILE_EXCL</code>,
which causes the copy operation to fail if <code>dest</code> already exists.</p>
<p>Example:</p>
<pre><code class="lang-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>, as shown in the
following example.</p>
<pre><code class="lang-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])<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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/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><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>
<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>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><code>autoClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></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></li>
<li><code>highWaterMark</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: <span class="type"><ReadStream></span></li>
</ul>
<p>Returns a new <a href="#fs_class_fs_readstream"><code>ReadStream</code></a> object. (See <a href="stream.html#stream_class_stream_readable">Readable Streams</a>).</p>
<p>Be aware that, unlike the default value set for <code>highWaterMark</code> on a
readable stream (16 kb), the stream returned by this method has a
default value of 64 kb for the same parameter.</p>
<p><code>options</code> is an object or string with the following defaults:</p>
<pre><code class="lang-js">const defaults = {
flags: 'r',
encoding: null,
fd: null,
mode: 0o666,
autoClose: true,
highWaterMark: 64 * 1024
};
</code></pre>
<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.html#buffer_class_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. Note that <code>fd</code> should be blocking; non-blocking <code>fd</code>s should be passed
to <a href="net.html#net_class_net_socket"><code>net.Socket</code></a>.</p>
<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="lang-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])<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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/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><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>
<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>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><code>autoClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></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: <span class="type"><WriteStream></span></li>
</ul>
<p>Returns a new <a href="#fs_class_fs_writestream"><code>WriteStream</code></a> object. (See <a href="stream.html#stream_writable_streams">Writable Stream</a>).</p>
<p><code>options</code> is an object or string with the following defaults:</p>
<pre><code class="lang-js">const defaults = {
flags: 'w',
encoding: 'utf8',
fd: null,
mode: 0o666,
autoClose: true
};
</code></pre>
<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.html#buffer_class_buffer"><code>Buffer</code></a>.</p>
<p>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. 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, <code>WriteStream</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. Note that <code>fd</code> should be blocking; non-blocking
<code>fd</code>s should be passed to <a href="net.html#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)<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>
<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>
</table>
</details>
</div><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#fs_fs_stat_path_callback"><code>fs.stat()</code></a> or <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a> instead.</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></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><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. Example:</p>
<pre><code class="lang-js">fs.exists('/etc/passwd', (exists) => {
console.log(exists ? 'it\'s there' : 'no passwd!');
});
</code></pre>
<p><strong>Note that the parameter to this callback is 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="lang-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="lang-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="lang-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="lang-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)<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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>Synchronous version of <a href="fs.html#fs_fs_exists_path_callback"><code>fs.exists()</code></a>.
Returns <code>true</code> if the path exists, <code>false</code> otherwise.</p>
<p>Note that <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)<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>
<tr><th>Version</th><th>Changes</th></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.</p>
</td></tr>
<tr><td>v0.4.7</td>
<td><p><span>Added in: v0.4.7</span></p>
</td></tr>
</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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">fchmod(2)</a>. No arguments other than a possible exception
are given to the completion callback.</p>
<h2>fs.fchmodSync(fd, mode)<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">fchmod(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.fchown(fd, uid, gid, callback)<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>
<tr><th>Version</th><th>Changes</th></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.</p>
</td></tr>
<tr><td>v0.4.7</td>
<td><p><span>Added in: v0.4.7</span></p>
</td></tr>
</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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">fchown(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.fchownSync(fd, uid, gid)<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">fchown(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.fdatasync(fd, callback)<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>
<tr><th>Version</th><th>Changes</th></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.</p>
</td></tr>
<tr><td>v0.1.96</td>
<td><p><span>Added in: v0.1.96</span></p>
</td></tr>
</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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">fdatasync(2)</a>. No arguments other than a possible exception are
given to the completion callback.</p>
<h2>fs.fdatasyncSync(fd)<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">fdatasync(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.fstat(fd, callback)<span><a class="mark" href="#fs_fs_fstat_fd_callback" id="fs_fs_fstat_fd_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tr><th>Version</th><th>Changes</th></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.</p>
</td></tr>
<tr><td>v0.1.95</td>
<td><p><span>Added in: v0.1.95</span></p>
</td></tr>
</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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#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">fstat(2)</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.html#fs_fs_stat_path_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)<span><a class="mark" href="#fs_fs_fstatsync_fd" id="fs_fs_fstatsync_fd">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.95</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>Returns: <a href="fs.html#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">fstat(2)</a>. Returns an instance of <a href="#fs_class_fs_stats"><code>fs.Stats</code></a>.</p>
<h2>fs.fsync(fd, callback)<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>
<tr><th>Version</th><th>Changes</th></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.</p>
</td></tr>
<tr><td>v0.1.96</td>
<td><p><span>Added in: v0.1.96</span></p>
</td></tr>
</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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">fsync(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.fsyncSync(fd)<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">fsync(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.ftruncate(fd[, len], callback)<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>
<tr><th>Version</th><th>Changes</th></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.</p>
</td></tr>
<tr><td>v0.8.6</td>
<td><p><span>Added in: v0.8.6</span></p>
</td></tr>
</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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">ftruncate(2)</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="lang-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 ('\0'). For example,</p>
<pre><code class="lang-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 ('\0'), to compensate the over-truncation.</p>
<h2>fs.ftruncateSync(fd[, len])<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>Synchronous <a href="http://man7.org/linux/man-pages/man2/ftruncate.2.html">ftruncate(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.futimes(fd, atime, mtime, callback)<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>
<tr><th>Version</th><th>Changes</th></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.</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>
</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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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)<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>
<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>
</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>
<tr><th>Version</th><th>Changes</th></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.</p>
</td></tr>
<tr><td>v0.4.7</td>
<td><p><span>Deprecated since: v0.4.7</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">lchmod(2)</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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">lchmod(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.lchown(path, uid, gid, callback)<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>
<tr><th>Version</th><th>Changes</th></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.</p>
</td></tr>
<tr><td>v0.4.7</td>
<td><p><span>Deprecated since: v0.4.7</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">lchown(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.lchownSync(path, uid, gid)<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">
<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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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">lchown(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.link(existingPath, newPath, callback)<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>
<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>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</p>
</td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></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><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">link(2)</a>. No arguments other than a possible exception are given to
the completion callback.</p>
<h2>fs.linkSync(existingPath, newPath)<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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">link(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.lstat(path, callback)<span><a class="mark" href="#fs_fs_lstat_path_callback" id="fs_fs_lstat_path_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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 <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</p>
</td></tr>
<tr><td>v0.1.30</td>
<td><p><span>Added in: v0.1.30</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></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><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.html#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">lstat(2)</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)<span><a class="mark" href="#fs_fs_lstatsync_path" id="fs_fs_lstatsync_path">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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.30</td>
<td><p><span>Added in: v0.1.30</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a></li>
<li>Returns: <a href="fs.html#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">lstat(2)</a>. Returns an instance of <a href="#fs_class_fs_stats"><code>fs.Stats</code></a>.</p>
<h2>fs.mkdir(path[, mode], callback)<span><a class="mark" href="#fs_fs_mkdir_path_mode_callback" id="fs_fs_mkdir_path_mode_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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 <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</p>
</td></tr>
<tr><td>v0.1.8</td>
<td><p><span>Added in: v0.1.8</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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>0o777</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><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. <code>mode</code> defaults to <code>0o777</code>.</p>
<p>See also: <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html">mkdir(2)</a></p>
<h2>fs.mkdirSync(path[, mode])<span><a class="mark" href="#fs_fs_mkdirsync_path_mode" id="fs_fs_mkdirsync_path_mode">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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>0o777</code></li>
</ul>
<p>Synchronously creates a directory. Returns <code>undefined</code>.
This is the synchronous version of <a href="#fs_fs_mkdir_path_mode_callback"><code>fs.mkdir()</code></a>.</p>
<p>See also: <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html">mkdir(2)</a></p>
<h2>fs.mkdtemp(prefix[, options], callback)<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>
<tr><th>Version</th><th>Changes</th></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.</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>
</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><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><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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>
<p>Example:</p>
<pre><code class="lang-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>
<em>must</em> end with a trailing platform-specific path separator
(<code>require('path').sep</code>).</p>
<pre><code class="lang-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`.
// Note that 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])<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><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><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>The synchronous version of <a href="#fs_fs_mkdtemp_prefix_options_callback"><code>fs.mkdtemp()</code></a>. Returns the created
folder path.</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)<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>
<tr><th>Version</th><th>Changes</th></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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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></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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">open(2)</a>. <code>flags</code> can be:</p>
<ul>
<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>Note that this doesn't turn <code>fs.open()</code> into a synchronous blocking call.
If synchronous operation is desired <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 <code>path</code> 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 <code>path</code> exists.</p>
</li>
<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 <code>path</code> 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>'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 <code>path</code> exists.</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>
</ul>
<p><code>mode</code> sets the file mode (permission and sticky bits), but only if the file was
created. It defaults to <code>0o666</code> (readable and writable).</p>
<p>The callback gets two arguments <code>(err, fd)</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">open(2)</a>) ensures that <code>path</code> is newly
created. On POSIX systems, <code>path</code> 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><code>flags</code> can also be a number as documented by <a href="http://man7.org/linux/man-pages/man2/open.2.html">open(2)</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 CreateFileW.</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>The behavior of <code>fs.open()</code> is platform-specific for some flags. 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 will be returned.</p>
<pre><code class="lang-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>Some characters (<code>< > : " / \ | ? *</code>) are reserved under Windows as documented
by <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx">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://msdn.microsoft.com/en-us/library/windows/desktop/bb540537.aspx">this MSDN page</a>.</p>
<p>Functions based on <code>fs.open()</code> exhibit this behavior as well. eg.
<code>fs.writeFile()</code>, <code>fs.readFile()</code>, etc.</p>
<p><em>Note:</em> On Windows, opening an existing hidden file using the <code>w</code> flag (either
through <code>fs.open()</code> or <code>fs.writeFile()</code>) will fail with <code>EPERM</code>. Existing hidden
files can be opened for writing with the <code>r+</code> flag. A call to <code>fs.ftruncate()</code>
can be used to reset the file contents.</p>
<h2>fs.openSync(path, flags[, mode])<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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></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>Synchronous version of <a href="#fs_fs_open_path_flags_mode_callback"><code>fs.open()</code></a>. Returns an integer representing the file
descriptor.</p>
<h2>fs.read(fd, buffer, offset, length, position, callback)<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>
<tr><th>Version</th><th>Changes</th></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>
</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.html#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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#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 Promise for an object with <code>bytesRead</code> and <code>buffer</code> properties.</p>
<h2>fs.readdir(path[, options], callback)<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>
<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 <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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/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><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#buffer_class_buffer" class="type"><Buffer[]></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man3/readdir.3.html">readdir(3)</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>
<h2>fs.readdirSync(path[, options])<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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/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><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/Array" class="type"><Array></a> An array of filenames</li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man3/readdir.3.html">readdir(3)</a>. Returns an array of filenames 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>
<h2>fs.readFile(path[, options], callback)<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>
<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 <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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>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><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> <strong>Default:</strong> <code>'r'</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><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.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>Asynchronously reads the entire contents of a file. Example:</p>
<pre><code class="lang-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. Example:</p>
<pre><code class="lang-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="lang-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>Any specified file descriptor has to support reading.</p>
<p>If a file descriptor is specified as the <code>path</code>, it will not be closed
automatically.</p>
<p>The <code>fs.readFile()</code> function reads the entire file in a single threadpool
request. To minimize threadpool task length variation, prefer the partitioned
APIs <code>fs.read()</code> and <code>fs.createReadStream()</code> when reading files as part of
fulfilling a client request.</p>
<h2>fs.readFileSync(path[, options])<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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>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><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> <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.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
<p>Synchronous version of <a href="#fs_fs_readfile_path_options_callback"><code>fs.readFile()</code></a>. Returns the contents of the <code>path</code>.</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="lang-js">// macOS, Linux, and Windows
fs.readFileSync('<directory>');
// => [Error: EISDIR: illegal operation on a directory, read <directory>]
// FreeBSD
fs.readFileSync('<directory>'); // => null, <data>
</code></pre>
<h2>fs.readlink(path[, options], callback)<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>
<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 <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</p>
</td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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/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><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#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">readlink(2)</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])<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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/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><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.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/readlink.2.html">readlink(2)</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 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.readSync(fd, buffer, offset, length, position)<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>
<tr><th>Version</th><th>Changes</th></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>
</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.html#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/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<p>Synchronous version of <a href="#fs_fs_read_fd_buffer_offset_length_position_callback"><code>fs.read()</code></a>. Returns the number of <code>bytesRead</code>.</p>
<h2>fs.realpath(path[, options], callback)<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>
<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>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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/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><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#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>Note that "canonical" does not mean "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">realpath(3)</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">realpath(3)</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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/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><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#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">realpath(3)</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])<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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/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><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.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
<p>Synchronously computes the canonical pathname by resolving <code>.</code>, <code>..</code> and
symbolic links.</p>
<p>Note that "canonical" does not mean "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">realpath(3)</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">realpath(3)</a> implementation supports.</p>
</li>
</ol>
<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 returned value. 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.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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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/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><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.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man3/realpath.3.html">realpath(3)</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 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.rename(oldPath, newPath, callback)<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>
<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>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</p>
</td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></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><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">rename(2)</a>.</p>
<pre><code class="lang-js">fs.rename('oldFile.txt', 'newFile.txt', (err) => {
if (err) throw err;
console.log('Rename complete!');
});
</code></pre>
<h2>fs.renameSync(oldPath, newPath)<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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">rename(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.rmdir(path, callback)<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>
<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>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</p>
</td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></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><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">rmdir(2)</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)<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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">rmdir(2)</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, callback)<span><a class="mark" href="#fs_fs_stat_path_callback" id="fs_fs_stat_path_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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 <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</p>
</td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></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><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.html#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">stat(2)</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.html#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)<span><a class="mark" href="#fs_fs_statsync_path" id="fs_fs_statsync_path">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a></li>
<li>Returns: <a href="fs.html#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">stat(2)</a>. Returns an instance of <a href="#fs_class_fs_stats"><code>fs.Stats</code></a>.</p>
<h2>fs.symlink(target, path[, type], callback)<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">symlink(2)</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> (default is <code>'file'</code>) and is only available on
Windows (ignored on other platforms). Note that 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="lang-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])<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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>Synchronous <a href="http://man7.org/linux/man-pages/man2/symlink.2.html">symlink(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.truncate(path[, len], callback)<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>
<tr><th>Version</th><th>Changes</th></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.</p>
</td></tr>
<tr><td>v0.8.6</td>
<td><p><span>Added in: v0.8.6</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">truncate(2)</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])<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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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">truncate(2)</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)<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>
<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 <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</p>
</td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></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><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="lang-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">unlink(2)</a></p>
<h2>fs.unlinkSync(path)<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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">unlink(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.unwatchFile(filename[, listener])<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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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)<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>
<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>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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>, a <code>Error</code> will be thrown.</li>
</ul>
<h2>fs.utimesSync(path, atime, mtime)<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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>Synchronous version of <a href="#fs_fs_utimes_path_atime_mtime_callback"><code>fs.utimes()</code></a>. Returns <code>undefined</code>.</p>
<h2>fs.watch(filename[, options][, listener])<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>
<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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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/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><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><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><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.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</li>
</ul>
<p>Watch for changes on <code>filename</code>, where <code>filename</code> is either a file or a
directory. The returned object is a <a href="#fs_class_fs_fswatcher"><code>fs.FSWatcher</code></a>.</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>Note that on most platforms, <code>'rename'</code> is emitted whenever a filename appears
or disappears in the directory.</p>
<p>Also note 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>
<!--type=misc-->
<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>
<!--type=misc-->
<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</code></a></li>
<li>On BSD systems, this uses <a href="https://www.freebsd.org/cgi/man.cgi?kqueue"><code>kqueue</code></a></li>
<li>On macOS, this uses <a href="https://www.freebsd.org/cgi/man.cgi?kqueue"><code>kqueue</code></a> for files and <a href="https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40005289-CH1-SW1"><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://msdn.microsoft.com/en-us/library/windows/desktop/aa365465%28v=vs.85%29.aspx"><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>
<!--type=misc-->
<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>
<!--type=misc-->
<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 null.</p>
<pre><code class="lang-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)<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>
<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>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p>
</td></tr>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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><ul>
<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><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><ul>
<li><code>current</code> <a href="fs.html#fs_class_fs_stats" class="type"><fs.Stats></a></li>
<li><code>previous</code> <a href="fs.html#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. The default is
<code>{ persistent: true, interval: 5007 }</code>.</p>
<p>The <code>listener</code> gets two arguments the current stat object and the previous
stat object:</p>
<pre><code class="lang-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>.</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)<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>
<tr><th>Version</th><th>Changes</th></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.</p>
</td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p>
</td></tr>
</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.html#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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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.html#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>
</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">pwrite(2)</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 Promise for an object with <code>bytesWritten</code> and <code>buffer</code> properties.</p>
<p>Note that it is unsafe to use <code>fs.write</code> multiple times on the same file
without waiting for the callback. For this scenario,
<code>fs.createWriteStream</code> is strongly 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)<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>
<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>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning.</p>
</td></tr>
<tr><td>v0.11.5</td>
<td><p><span>Added in: v0.11.5</span></p>
</td></tr>
</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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a><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">pwrite(2)</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. Note that
bytes written is not the same as string characters. See <a href="buffer.html#buffer_class_method_buffer_bytelength_string_encoding"><code>Buffer.byteLength</code></a>.</p>
<p>Unlike when writing <code>buffer</code>, the entire string must be written. No substring
may be specified. This is because the byte offset of the resulting data may not
be the same as the string offset.</p>
<p>Note that it is unsafe to use <code>fs.write</code> multiple times on the same file
without waiting for the callback. For this scenario,
<code>fs.createWriteStream</code> is strongly 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.writeFile(file, data[, options], callback)<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>
<tr><th>Version</th><th>Changes</th></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.</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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#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>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><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> <strong>Default:</strong> <code>'w'</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><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. It defaults
to <code>'utf8'</code>.</p>
<p>Example:</p>
<pre><code class="lang-js">fs.writeFile('message.txt', 'Hello Node.js', (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. Example:</p>
<pre><code class="lang-js">fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
</code></pre>
<p>Any specified file descriptor has to support writing.</p>
<p>Note that it is unsafe to use <code>fs.writeFile</code> multiple times on the same file
without waiting for the callback. For this scenario,
<code>fs.createWriteStream</code> is strongly recommended.</p>
<p>If a file descriptor is specified as the <code>file</code>, it will not be closed
automatically.</p>
<h2>fs.writeFileSync(file, data[, options])<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>
<tr><th>Version</th><th>Changes</th></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>
</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#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.html#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>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><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> <strong>Default:</strong> <code>'w'</code></li>
</ul>
</li>
</ul>
<p>The synchronous version of <a href="#fs_fs_writefile_file_data_options_callback"><code>fs.writeFile()</code></a>. Returns <code>undefined</code>.</p>
<h2>fs.writeSync(fd, buffer[, offset[, length[, position]]])<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>
<tr><th>Version</th><th>Changes</th></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>
</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.html#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/Data_structures#Number_type" class="type"><number></a></li>
</ul>
<h2>fs.writeSync(fd, string[, position[, encoding]])<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>
<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>
</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></li>
</ul>
<p>Synchronous versions of <a href="#fs_fs_write_fd_buffer_offset_length_position_callback"><code>fs.write()</code></a>. Returns the number of bytes written.</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>
<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.</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.</td>
</tr>
</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>
<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>
</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>
<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>
</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>
<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>
</table>
<!-- [end-include:fs.md] -->
<!-- [start-include:globals.md] -->
<h1>Global Objects<span><a class="mark" href="#globals_global_objects" id="globals_global_objects">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<!-- type=misc -->
<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.html#modules_exports"><code>exports</code></a></li>
<li><a href="modules.html#modules_module"><code>module</code></a></li>
<li><a href="globals.html#globals_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><!-- type=global -->
<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><!--type=global-->
<p><a href="timers.html#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><!--type=global-->
<p><a href="timers.html#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><!--type=global-->
<p><a href="timers.html#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><!-- type=global -->
<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.html#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><!-- type=global -->
<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.html#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><!-- type=global -->
<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.html#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="globals.html#globals_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><!-- type=global -->
<p><a href="timers.html#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><!-- type=global -->
<p><a href="timers.html#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><!-- type=global -->
<p><a href="timers.html#timers_settimeout_callback_delay_args"><code>setTimeout</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<!-- [end-include:globals.md] -->
<!-- [start-include:http.md] -->
<h1>HTTP<span><a class="mark" href="#http_http" id="http_http">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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 — 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="lang-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="lang-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.html#net_socket_unref">socket.unref()</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="lang-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="lang-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(<a href="#zlib_class_options">options</a>)<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><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:<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. Defaults to <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.html#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>. Defaults to <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. Defaults to <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>
</ul>
</li>
</ul>
<p>The default <a href="#http_http_globalagent"><code>http.globalAgent</code></a> that is used by <a href="http.html#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.html#http_class_http_agent"><code>http.Agent</code></a> instance must be created.</p>
<pre><code class="lang-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])<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"><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.html#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"><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)<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.html#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
Agent. Default behavior is to:</p>
<pre><code class="lang-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)<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.html#net_class_net_socket" class="type"><net.Socket></a></li>
<li><code>request</code> <a href="http.html#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="lang-js">socket.ref();
</code></pre>
<p>This method can be overridden by a particular <code>Agent</code> subclass.</p>
<h3>agent.destroy()<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)<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><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<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 Infinity. 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.html#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 implements the <a href="stream.html#stream_writable_streams">Writable Stream</a> interface. This is an
<a href="events.html"><code>EventEmitter</code></a> with the following events:</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.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>socket</code> <a href="net.html#net_class_net_socket" class="type"><net.Socket></a></li>
<li><code>head</code> <a href="buffer.html#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="lang-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,
hostname: '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: '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.html#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.html#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.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>socket</code> <a href="net.html#net_class_net_socket" class="type"><net.Socket></a></li>
<li><code>head</code> <a href="buffer.html#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, 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="lang-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,
hostname: '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.html#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">
<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.html#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>
</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.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#String_type" class="type"><string></a></li>
</ul>
<p>Reads out a header on the request. Note that the name is case insensitive.</p>
<p>Example:</p>
<pre><code class="lang-js">const contentType = request.getHeader('Content-Type');
</code></pre>
<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>
<p>Example:</p>
<pre><code class="lang-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#String_type" class="type"><string></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.</p>
<p>Example:</p>
<pre><code class="lang-js">request.setHeader('Content-Type', 'application/json');
</code></pre>
<p>or</p>
<pre><code class="lang-js">request.setHeader('Set-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.html#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.html#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">
<span>Added in: v0.5.9</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> 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>
</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>
<p>Returns <code>request</code>.</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.html#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>request.connection</code>.</p>
<p>Example:</p>
<pre><code class="lang-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.html#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>
</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.</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>
<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.html#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.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>response</code> <a href="http.html#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="#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>
<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.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>response</code> <a href="http.html#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="#http2_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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The rawPacket is the current buffer that just parsed. Adding this buffer to the error object of clientError 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>
</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.html#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.html#net_class_net_socket"><code>net.Socket</code></a> object that the error originated from.</p>
<pre><code class="lang-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.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Arguments for the HTTP request, as it is in
the <a href="#http2_event_request"><code>'request'</code></a> event</li>
<li><code>socket</code> <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> Network socket between the server and client</li>
<li><code>head</code> <a href="buffer.html#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.html#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.html#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.html#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.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a></li>
<li><code>response</code> <a href="http.html#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">
<span>Added in: v0.1.94</span>
</div><ul>
<li><code>request</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Arguments for the HTTP request, as it is in
the <a href="#http2_event_request"><code>'request'</code></a> event</li>
<li><code>socket</code> <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> Network socket between the server and client</li>
<li><code>head</code> <a href="buffer.html#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. If this event is not
listened for, then clients requesting an upgrade 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>server.close([callback])<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.html#net_server_close_callback"><code>net.Server.close()</code></a>.</p>
<h3>server.listen()<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.html#net_server_listen"><code>server.listen()</code></a> from <a href="net.html#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></li>
</ul>
<p>A Boolean indicating whether or not the server is listening for
connections.</p>
<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> Defaults to 2000.</li>
</ul>
<p>Limits maximum incoming headers count, equal to 2000 by default. If set to 0 -
no limit will be applied.</p>
<h3>server.setTimeout([msecs][, callback])<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> Defaults to 120000 (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>
</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>
<p>Returns <code>server</code>.</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. Defaults to 120000 (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. Defaults to 5000 (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="#http2_event_request"><code>'request'</code></a> event.</p>
<p>The response implements, but does not inherit from, the <a href="stream.html#stream_writable_streams">Writable Stream</a>
interface. This is an <a href="events.html"><code>EventEmitter</code></a> with the following events:</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="#http2_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>
<p>After this event, no more events will be emitted on the response object.</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="lang-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.html#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.html#net_class_net_socket" class="type"><net.Socket></a></li>
</ul>
<p>See <a href="#http2_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">
<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.html#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>
</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.html#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="#http2_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#String_type" class="type"><string></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.</p>
<p>Example:</p>
<pre><code class="lang-js">const contentType = response.getHeader('content-type');
</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/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>Returns an array containing the unique names of the current outgoing headers.
All header names are lowercase.</p>
<p>Example:</p>
<pre><code class="lang-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>
<p>Example:</p>
<pre><code class="lang-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>
<p>Example:</p>
<pre><code class="lang-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>
<p>Example:</p>
<pre><code class="lang-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#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>
<p>Example:</p>
<pre><code class="lang-js">response.setHeader('Content-Type', 'text/html');
</code></pre>
<p>or</p>
<pre><code class="lang-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.html#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="lang-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>
<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>
</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>
<p>Returns <code>response</code>.</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.html#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>
<p>Example:</p>
<pre><code class="lang-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="#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>
<p>Example:</p>
<pre><code class="lang-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="#http2_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>
<p>Example:</p>
<pre><code class="lang-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.html#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>
<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="#http2_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>
<tr><th>Version</th><th>Changes</th></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>
</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>
</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>Example:</p>
<pre><code class="lang-js">const body = 'hello world';
response.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain' });
</code></pre>
<p>This method must only be called once on a message and it must
be called 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="lang-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.html#errors_class_typeerror"><code>TypeError</code></a> being thrown.</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.html#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="#http2_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.html#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 and the network socket has closed.</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.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.
Example:</p>
<pre><code class="lang-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 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.html#http_class_http_server"><code>http.Server</code></a>.</strong></p>
<p>The request method as a string. Read only. Example:
<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/Reference/Global_Objects/Array" class="type"><Array></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="lang-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/Reference/Global_Objects/Array" class="type"><Array></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>
</ul>
<p>Calls <code>message.connection.setTimeout(msecs, callback)</code>.</p>
<p>Returns <code>message</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.html#net_class_net_socket" class="type"><net.Socket></a></li>
</ul>
<p>The <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> object associated with the connection.</p>
<p>With HTTPS support, use <a href="tls.html#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.html#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="lang-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="lang-js">'/status?name=ryan'
</code></pre>
<p>To parse the url into its parts <code>require('url').parse(request.url)</code>
can be used. Example:</p>
<pre><code class="lang-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>.
Example:</p>
<pre><code class="lang-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/Reference/Global_Objects/Array" class="type"><Array></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])<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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.6.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>
</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><ul>
<li><code>IncomingMessage</code> <a href="http.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Specifies the IncomingMessage class
to be used. Useful for extending the original <code>IncomingMessage</code>. Defaults
to: <code>IncomingMessage</code></li>
<li><code>ServerResponse</code> <a href="http.html#http_class_http_serverresponse" class="type"><http.ServerResponse></a> Specifies the ServerResponse class to
be used. Useful for extending the original <code>ServerResponse</code>. Defaults to:
<code>ServerResponse</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.html#http_class_http_server" class="type"><http.Server></a></p>
</li>
</ul>
<p>Returns a new instance of <a href="http.html#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="#http2_event_request"><code>'request'</code></a> event.</p>
<h2>http.get(options[, callback])<span><a class="mark" href="#http_http_get_options_callback" id="http_http_get_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tr><th>Version</th><th>Changes</th></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>
</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a> Accepts the same <code>options</code> as
<a href="http.html#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.html#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.html#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="lang-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.html#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.request(options[, callback])<span><a class="mark" href="#http_http_request_options_callback" id="http_http_request_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tr><th>Version</th><th>Changes</th></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>
</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a><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. Defaults to <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. Defaults to <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> is preferred over <code>host</code>.</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> and
<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>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. Defaults to 80.</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 (use one of host:port or
socketPath).</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. Defaults to
<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. Defaults to <code>'/'</code>. 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.</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><code>agent</code> <a href="http.html#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="#https_class_https_agent"><code>Agent</code></a> behavior. Possible
values:<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.html#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.html#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>options</code> can be an object, a string, or a <a href="url.html#url_class_url"><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.html#url_class_url"><code>URL</code></a>
object, it will be automatically converted to an ordinary <code>options</code> object.</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>
<p>Example:</p>
<pre><code class="lang-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.html#url_class_url"><code>URL</code></a> as <code>options</code>:</p>
<pre><code class="lang-js">const { URL } = require('url');
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><code>response</code><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>close</code></li>
<li><code>error</code> with an error with message <code>Error: socket hang up</code> and code
<code>ECONNRESET</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><code>response</code><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>close</code><ul>
<li><code>aborted</code> on the <code>res</code> object</li>
<li><code>end</code> on the <code>res</code> object</li>
<li><code>close</code> on the <code>res</code> object</li>
</ul>
</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>
<!-- [end-include:http.md] -->
<!-- [start-include:http2.md] -->
<h1>HTTP/2<span><a class="mark" href="#http2_http_2" id="http2_http_2">#</a></span></h1>
<!--introduced_in=v8.4.0-->
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><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="lang-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="lang-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="lang-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="lang-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.html#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>
<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.html#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 the 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.</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><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><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><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>When invoked, the handler function will receive three arguments:</p>
<ul>
<li>An integer identifying the frame type.</li>
<li>An integer identifying the error code.</li>
<li>An integer identifying the stream (or 0 if the frame is not associated with
a stream).</li>
</ul>
<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><p>The <code>'goaway'</code> event is emitted when a GOAWAY frame is received. When invoked,
the handler function will receive three arguments:</p>
<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 GOAWAY 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.html#buffer_class_buffer" class="type"><Buffer></a> If additional opaque data was included in the GOAWAY
frame, a <code>Buffer</code> instance will be passed containing that data.</li>
</ul>
<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><p>The <code>'localSettings'</code> event is emitted when an acknowledgment SETTINGS frame
has been received. When invoked, the handler function will receive a copy of
the local settings.</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="lang-js">session.settings({ enablePush: false });
session.on('localSettings', (settings) => {
/** use the new settings **/
});
</code></pre>
<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><p>The <code>'remoteSettings'</code> event is emitted when a new SETTINGS frame is received
from the connected peer. When invoked, the handler function will receive a copy
of the remote settings.</p>
<pre><code class="lang-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><p>The <code>'stream'</code> event is emitted when a new <code>Http2Stream</code> is created. When
invoked, the handler function will receive a reference to the <code>Http2Stream</code>
object, a <a href="#http2_headers_object">HTTP/2 Headers Object</a>, and numeric flags associated with the
creation of the stream.</p>
<pre><code class="lang-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="lang-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.end('<h1>Hello World</h1>');
});
server.listen(80);
</code></pre>
<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="lang-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>Value: <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>Value: <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.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 after 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>Value: <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>Value: <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.html#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 GOAWAY 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>Value: <a href="http2.html#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>Value: <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 Array of origins for which the <code>Http2Session</code> may be
considered authoritative.</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>Value: <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 SETTINGS 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: v9.2.1</span>
</div><ul>
<li><code>payload</code> <a href="buffer.html#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="lang-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.html#net_socket_ref"><code>ref()</code></a> on this <code>Http2Session</code>
instance's underlying <a href="net.html#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>Value: <a href="http2.html#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>Value: <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> | <a href="tls.html#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li>
</ul>
<p>Returns a Proxy 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">Http2Session 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>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.html#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 SETTINGS acknowledgment is
received and the <code>'localSettings'</code> event is emitted. It is possible to send
multiple SETTINGS 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>Value: <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.html#net_socket_unref"><code>unref()</code></a> on this <code>Http2Session</code>
instance's underlying <a href="net.html#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.html#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 Object 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="lang-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>
<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="lang-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>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><code>headers</code> <a href="http2.html#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> <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>getTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback function invoked to collect trailer
headers.</li>
</ul>
</li>
<li><p>Returns: <a href="http2.html#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="lang-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 set, the <code>options.getTrailers()</code> function is called immediately after
queuing the last chunk of payload data to be sent. The callback is passed a
single object (with a <code>null</code> prototype) that the listener may use to specify
the trailing header fields to send to the peer.</p>
<p>The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header
fields (e.g. <code>':method'</code>, <code>':path'</code>, etc). An <code>'error'</code> event will be emitted
if the <code>getTrailers</code> callback attempts to set such header fields.</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.html#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.html#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.</li>
<li>The <code>http2stream.close()</code> method is called.</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 listener callback is passed a single argument specifying the HTTP/2 error
code specified when closing the stream. If the code is any value other than
<code>NGHTTP2_NO_ERROR</code> (<code>0</code>), an <code>'error'</code> event will also be 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><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>
<pre><code class="lang-js">stream.on('trailers', (headers, flags) => {
console.log(headers);
});
</code></pre>
<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>Value: <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.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 <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>Value: <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>Value: <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.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>Value: <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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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>Value: <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>Value: <a href="http2.html#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>Value: <a href="http2.html#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>Value: <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a></li>
</ul>
<p>An object containing the outbound trailers sent for this 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>Value: <a href="http2.html#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="lang-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>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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 nghttp2.</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>
<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.html#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="lang-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="lang-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 Object containing the received
<a href="#http2_headers_object">HTTP/2 Headers Object</a>, and flags associated with the headers.</p>
<pre><code class="lang-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.html#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.html#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>Value: <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>
<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>Value: <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.html#http2_headers_object" class="type"><HTTP/2 Headers Object></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><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><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.<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.html#http2_class_serverhttp2stream" class="type"><ServerHttp2Stream></a> The returned pushStream object.</li>
<li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></a> Headers object the pushStream 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="lang-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>
<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.html#http2_headers_object" class="type"><HTTP/2 Headers Object></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><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>getTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback function invoked to collect trailer
headers.</li>
</ul>
</li>
</ul>
<pre><code class="lang-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 set, the <code>options.getTrailers()</code> function is called immediately after
queuing the last chunk of payload data to be sent. The callback is passed a
single object (with a <code>null</code> prototype) that the listener may use to specify
the trailing header fields to send to the peer.</p>
<pre><code class="lang-js">const http2 = require('http2');
const server = http2.createServer();
server.on('stream', (stream) => {
stream.respond({ ':status': 200 }, {
getTrailers(trailers) {
trailers.ABC = 'some value to send';
}
});
stream.end('some data');
});
</code></pre>
<p>The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header
fields (e.g. <code>':status'</code>, <code>':path'</code>, etc). An <code>'error'</code> event will be emitted
if the <code>getTrailers</code> callback attempts to set such header fields.</p>
<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">
<span>Added in: v8.4.0</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 readable file descriptor.</li>
<li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></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><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>getTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback function invoked to collect trailer
headers.</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 Duplex interface will be closed
automatically.</p>
<pre><code class="lang-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 set, the <code>options.getTrailers()</code> function is called immediately after
queuing the last chunk of payload data to be sent. The callback is passed a
single object (with a <code>null</code> prototype) that the listener may use to specify
the trailing header fields to send to the peer.</p>
<pre><code class="lang-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, {
getTrailers(trailers) {
trailers.ABC = 'some value to send';
}
});
stream.on('close', () => fs.closeSync(fd));
});
</code></pre>
<p>The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header
fields (e.g. <code>':status'</code>, <code>':path'</code>, etc). An <code>'error'</code> event will be emitted
if the <code>getTrailers</code> callback attempts to set such header fields.</p>
<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">
<span>Added in: v8.4.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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a></li>
<li><code>headers</code> <a href="http2.html#http2_headers_object" class="type"><HTTP/2 Headers Object></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><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>getTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Callback function invoked to collect trailer
headers.</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 Duplex 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="lang-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="lang-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 set, the <code>options.getTrailers()</code> function is called immediately after
queuing the last chunk of payload data to be sent. The callback is passed a
single object (with a <code>null</code> prototype) that the listener may use to specify
the trailing header fields to send to the peer.</p>
<pre><code class="lang-js">const http2 = require('http2');
const server = http2.createServer();
server.on('stream', (stream) => {
function getTrailers(trailers) {
trailers.ABC = 'some value to send';
}
stream.respondWithFile('/some/file',
{ 'content-type': 'text/plain' },
{ getTrailers });
});
</code></pre>
<p>The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header
fields (e.g. <code>':status'</code>, <code>':path'</code>, etc). An <code>'error'</code> event will be emitted
if the <code>getTrailers</code> callback attempts to set such header fields.</p>
<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.html#net_class_net_server" class="type"><net.Server></a></li>
</ul>
<p>In <code>Http2Server</code>, there are no <code>'clientError'</code> events as there are in
HTTP1. However, there are <code>'sessionError'</code>, and <code>'streamError'</code> events for
errors emitted on the socket, or from <code>Http2Session</code> or <code>Http2Stream</code> instances.</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.html#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="http2.html#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.html#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="http2.html#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: 'streamError'<span><a class="mark" href="#http2_event_streamerror" id="http2_event_streamerror">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div><p>If a <code>ServerHttp2Stream</code> emits an <code>'error'</code> event, it will be forwarded here.
The stream will already be destroyed when this event is triggered.</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="lang-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>.</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.html#tls_class_tls_server" class="type"><tls.Server></a></li>
</ul>
<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.html#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="http2.html#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.html#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="http2.html#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="lang-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>.</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. See the <a href="#http2_compatibility_api">Compatibility API</a>.</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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.6.0</td>
<td><p>Added the <code>Http1IncomingMessage</code> and <code>Http1ServerResponse</code> option.</p>
</td></tr>
<tr><td>v9.2.1</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p>
</td></tr>
<tr><td>v9.1.0</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>
</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><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>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>. <strong>Default:</strong>
<code>10</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 PING and SETTINGS frames are all
counted towards the current limit.</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.
<strong>Default:</strong> <code>128</code>. The minimum value is <code>4</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. The default is <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><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 HEADERS and DATA frames. <strong>Default:</strong>
<code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:<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 SETTINGS 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 options.selectPadding</a>.</li>
<li><code>settings</code> <a href="http2.html#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.html#http_class_http_incomingmessage" class="type"><http.IncomingMessage></a> Specifies the IncomingMessage
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.html#http_class_http_serverresponse" class="type"><http.ServerResponse></a> Specifies the ServerResponse
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.html#http2_class_http2_http2serverrequest" class="type"><http2.Http2ServerRequest></a> Specifies the
Http2ServerRequest 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.html#http2_class_http2_http2serverresponse" class="type"><http2.Http2ServerResponse></a> Specifies the
Http2ServerResponse class to use.
Useful for extending the original <code>Http2ServerResponse</code>.
<strong>Default:</strong> <code>Http2ServerResponse</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.html#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="lang-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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.2.1</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p>
</td></tr>
<tr><td>v9.1.0</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>
</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><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>. <strong>Default:</strong>
<code>false</code>. See the <a href="#http2_event_unknownprotocol"><code>'unknownProtocol'</code></a> event. See <a href="#http2_alpn_negotiation">ALPN negotiation</a>.</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>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>. <strong>Default:</strong>
<code>10</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 PING and SETTINGS frames are all
counted towards the current limit.</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.
<strong>Default:</strong> <code>128</code>. The minimum value is <code>4</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. The default is <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><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 HEADERS and DATA frames. <strong>Default:</strong>
<code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:<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 SETTINGS 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 options.selectPadding</a>.</li>
<li><code>settings</code> <a href="http2.html#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>
</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: <span class="type"><Http2SecureServer></span></li>
</ul>
<p>Returns a <code>tls.Server</code> instance that creates and manages <code>Http2Session</code>
instances.</p>
<pre><code class="lang-js">const http2 = require('http2');
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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.2.1</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p>
</td></tr>
<tr><td>v9.1.0</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>
</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.html#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><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>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>. <strong>Default:</strong>
<code>10</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 PING and SETTINGS frames are all
counted towards the current limit.</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.
<strong>Default:</strong> <code>128</code>. The minimum value is <code>1</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. The default is <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><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 HEADERS and DATA frames. <strong>Default:</strong>
<code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:<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 SETTINGS 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 options.selectPadding</a>.</li>
<li><code>settings</code> <a href="http2.html#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.html#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>
</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: <span class="type"><ClientHttp2Session></span></li>
</ul>
<p>Returns a <code>ClientHttp2Session</code> instance.</p>
<pre><code class="lang-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>0x00</td>
<td>No Error</td>
<td><code>http2.constants.NGHTTP2_NO_ERROR</code></td>
</tr>
<tr>
<td>0x01</td>
<td>Protocol Error</td>
<td><code>http2.constants.NGHTTP2_PROTOCOL_ERROR</code></td>
</tr>
<tr>
<td>0x02</td>
<td>Internal Error</td>
<td><code>http2.constants.NGHTTP2_INTERNAL_ERROR</code></td>
</tr>
<tr>
<td>0x03</td>
<td>Flow Control Error</td>
<td><code>http2.constants.NGHTTP2_FLOW_CONTROL_ERROR</code></td>
</tr>
<tr>
<td>0x04</td>
<td>Settings Timeout</td>
<td><code>http2.constants.NGHTTP2_SETTINGS_TIMEOUT</code></td>
</tr>
<tr>
<td>0x05</td>
<td>Stream Closed</td>
<td><code>http2.constants.NGHTTP2_STREAM_CLOSED</code></td>
</tr>
<tr>
<td>0x06</td>
<td>Frame Size Error</td>
<td><code>http2.constants.NGHTTP2_FRAME_SIZE_ERROR</code></td>
</tr>
<tr>
<td>0x07</td>
<td>Refused Stream</td>
<td><code>http2.constants.NGHTTP2_REFUSED_STREAM</code></td>
</tr>
<tr>
<td>0x08</td>
<td>Cancel</td>
<td><code>http2.constants.NGHTTP2_CANCEL</code></td>
</tr>
<tr>
<td>0x09</td>
<td>Compression Error</td>
<td><code>http2.constants.NGHTTP2_COMPRESSION_ERROR</code></td>
</tr>
<tr>
<td>0x0a</td>
<td>Connect Error</td>
<td><code>http2.constants.NGHTTP2_CONNECT_ERROR</code></td>
</tr>
<tr>
<td>0x0b</td>
<td>Enhance Your Calm</td>
<td><code>http2.constants.NGHTTP2_ENHANCE_YOUR_CALM</code></td>
</tr>
<tr>
<td>0x0c</td>
<td>Inadequate Security</td>
<td><code>http2.constants.NGHTTP2_INADEQUATE_SECURITY</code></td>
</tr>
<tr>
<td>0x0d</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.html#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.html#http2_settings_object" class="type"><HTTP/2 Settings Object></a></li>
<li>Returns: <a href="buffer.html#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="lang-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.html#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.html#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 Array of strings (in order
to send more than one value per header field).</p>
<pre><code class="lang-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>
<pre><code class="lang-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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.1.0</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>
</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. <strong>Default:</strong> <code>4,096 octets</code>. The minimum allowed
value is 0. The maximum allowed value is 2<sup>32</sup>-1.</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. <strong>Default:</strong> <code>65,535 bytes</code>. The minimum
allowed value is 0. The maximum allowed value is 2<sup>32</sup>-1.</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.
<strong>Default:</strong> <code>16,384 bytes</code>. The minimum allowed value is 16,384. The maximum
allowed value is 2<sup>24</sup>-1.</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> 65535.</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 HEADERS and DATA 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="lang-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> HEADERS and
DATA 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="lang-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="lang-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="lang-js">const http2 = require('http2');
const { NGHTTP2_REFUSED_STREAM } = http2.constants;
const net = require('net');
const { URL } = require('url');
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="lang-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>
<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="lang-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="lang-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.html#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.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.
Example:</p>
<pre><code class="lang-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="lang-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. Example:
<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/Reference/Global_Objects/Array" class="type"><Array></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="lang-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/Reference/Global_Objects/Array" class="type"><Array></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.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>
</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>
<p>Returns <code>request</code>.</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.html#net_class_net_socket" class="type"><net.Socket></a> | <a href="tls.html#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li>
</ul>
<p>Returns a Proxy 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">Http2Session 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.html#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><span class="type"><http2.Http2Stream></span></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="lang-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="lang-js">'/status?name=ryan'
</code></pre>
<p>To parse the url into its parts <code>require('url').parse(request.url)</code>
can be used. Example:</p>
<pre><code class="lang-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>.
Example:</p>
<pre><code class="lang-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 implements, but does not inherit from, the <a href="stream.html#stream_writable_streams">Writable Stream</a>
interface. This is an <a href="events.html"><code>EventEmitter</code></a> with the following events:</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.html#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.html#net_class_net_socket" class="type"><net.Socket></a> | <a href="tls.html#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">
<span>Added in: v8.4.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.html#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>
</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.html#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>
<p>Example:</p>
<pre><code class="lang-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/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>Returns an array containing the unique names of the current outgoing headers.
All header names are lowercase.</p>
<p>Example:</p>
<pre><code class="lang-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>
<p>Example:</p>
<pre><code class="lang-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>
<p>Example:</p>
<pre><code class="lang-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>Boolean (read-only). True if headers were sent, false otherwise.</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>
<p>Example:</p>
<pre><code class="lang-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>
<p>Example:</p>
<pre><code class="lang-js">response.setHeader('Content-Type', 'text/html');
</code></pre>
<p>or</p>
<pre><code class="lang-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.html#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="lang-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>
</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>
<p>Returns <code>response</code>.</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.html#net_class_net_socket" class="type"><net.Socket></a> | <a href="tls.html#tls_class_tls_tlssocket" class="type"><tls.TLSSocket></a></li>
</ul>
<p>Returns a Proxy 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">Http2Session and Sockets</a> for
more information.</p>
<p>All other interactions will be routed directly to the socket.</p>
<p>Example:</p>
<pre><code class="lang-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>
<p>Example:</p>
<pre><code class="lang-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><span class="type"><http2.Http2Stream></span></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.html#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">
<span>Added in: v8.4.0</span>
</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>
</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>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>
<p>Example:</p>
<pre><code class="lang-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="lang-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.html#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><p>Call <a href="#http2_http2stream_pushstream_headers_options_callback"><code>http2stream.pushStream()</code></a> with the given headers, and wraps the
given newly created <a href="#http2_class_http2stream"><code>Http2Stream</code></a> on <code>Http2ServerRespose</code>.</p>
<p>The callback will be called with an error with code <code>ERR_HTTP2_STREAM_CLOSED</code>
if the stream is closed.</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="lang-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 DATA 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 DATA 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>
<!-- [end-include:http2.md] -->
<!-- [start-include:https.md] -->
<h1>HTTPS<span><a class="mark" href="#https_https" id="https_https">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p>HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.</p>
<h2>Class: https.Agent<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.html#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<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.html#http_class_http_server"><code>http.Server</code></a>. See <a href="http.html#http_class_http_server"><code>http.Server</code></a> for more information.</p>
<h3>server.close([callback])<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>
</ul>
<p>See <a href="http.html#http_server_close_callback"><code>server.close()</code></a> from the HTTP module for details.</p>
<h3>server.listen()<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.html#net_server_listen"><code>server.listen()</code></a> from <a href="net.html#net_class_net_server"><code>net.Server</code></a>.</p>
<h3>server.setTimeout([msecs][, callback])<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> Defaults to 120000 (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>
</ul>
<p>See <a href="http.html#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> Defaults to 120000 (2 minutes).</li>
</ul>
<p>See <a href="http.html#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> Defaults to 5000 (5 seconds).</li>
</ul>
<p>See <a href="http.html#http_server_keepalivetimeout"><code>http.Server#keepAliveTimeout</code></a>.</p>
<h2>https.createServer([options][, requestListener])<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.html#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>
</ul>
<p>Example:</p>
<pre><code class="lang-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="lang-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])<span><a class="mark" href="#https_https_get_options_callback" id="https_https_get_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tr><th>Version</th><th>Changes</th></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>
</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="url.html#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.html#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.html#url_class_url"><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.html#url_class_url"><code>URL</code></a>
object, it will be automatically converted to an ordinary <code>options</code> object.</p>
<p>Example:</p>
<pre><code class="lang-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])<span><a class="mark" href="#https_https_request_options_callback" id="https_https_request_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<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>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>
</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="url.html#url_the_whatwg_url_api" class="type"><URL></a> Accepts all <code>options</code> from
<a href="http.html#http_http_request_options_callback"><code>http.request()</code></a>, with some differences in default values:<ul>
<li><code>protocol</code> Defaults to <code>https:</code></li>
<li><code>port</code> Defaults to <code>443</code>.</li>
<li><code>agent</code> Defaults to <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.html#url_class_url"><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.html#url_class_url"><code>URL</code></a>
object, it will be automatically converted to an ordinary <code>options</code> object.</p>
<p>Example:</p>
<pre><code class="lang-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="lang-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>
<p>Example:</p>
<pre><code class="lang-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.html#url_class_url"><code>URL</code></a> as <code>options</code>:</p>
<pre><code class="lang-js">const { URL } = require('url');
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="lang-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="lang-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>
<!-- [end-include:https.md] -->
<!-- [start-include:inspector.md] -->
<h1>Inspector<span><a class="mark" href="#inspector_inspector" id="inspector_inspector">#</a></span></h1>
<!--introduced_in=v8.0.0-->
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><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="lang-js">const inspector = require('inspector');
</code></pre>
<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>
<div class="signature"><ul>
<li>port <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,
defaults to what was specified on the CLI.</li>
<li>host <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,
defaults to what was specified on the CLI.</li>
<li>wait <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, defaults
to false.</li>
</ul>
</div><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>
<h3>inspector.close()<span><a class="mark" href="#inspector_inspector_close" id="inspector_inspector_close">#</a></span></h3>
<p>Deactivate the inspector. Blocks until there are no active connections.</p>
<h3>inspector.url()<span><a class="mark" href="#inspector_inspector_url" id="inspector_inspector_url">#</a></span></h3>
<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.html"><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="lang-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="lang-js">session.on('Debugger.paused', ({ params }) => {
console.log(params.hitBreakpoints);
});
// [ '/the/file/that/has/the/breakpoint.js:11:0' ]
</code></pre>
<h3>session.connect()<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.post(method[, params][, callback])<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>method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
<li>params <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
<li>callback <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="lang-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 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>
<h3>session.disconnect()<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>
<h2>Example usage<span><a class="mark" href="#inspector_example_usage" id="inspector_example_usage">#</a></span></h2>
<h3>CPU Profiler<span><a class="mark" href="#inspector_cpu_profiler" id="inspector_cpu_profiler">#</a></span></h3>
<p>Apart from the debugger, various V8 Profilers are available through the DevTools
protocol. Here's a simple example showing how to use the <a href="https://chromedevtools.github.io/devtools-protocol/v8/Profiler">CPU profiler</a>:</p>
<pre><code class="lang-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>
<!-- [end-include:inspector.md] -->
<!-- [start-include:intl.md] -->
<h1>Internationalization Support<span><a class="mark" href="#intl_internationalization_support" id="intl_internationalization_support">#</a></span></h1>
<!--introduced_in=v8.2.0-->
<p>Node.js has many features that make it easier to write internationalized
programs. Some of them are:</p>
<ul>
<li>Locale-sensitive or Unicode-aware functions in the <a href="https://tc39.github.io/ecma262/">ECMAScript Language
Specification</a>:<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>All functionality described in the <a href="https://tc39.github.io/ecma402/">ECMAScript Internationalization API
Specification</a> (aka ECMA-402):<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.html#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.html#buffer_buffer_transcode_source_fromenc_toenc"><code>require('buffer').transcode()</code></a></li>
<li>More accurate <a href="repl.html#repl_repl">REPL</a> line editing</li>
<li><a href="util.html#util_class_util_textdecoder"><code>require('util').TextDecoder</code></a></li>
<li><a href="https://github.com/tc39/proposal-regexp-unicode-property-escapes">RegExp Unicode Property Escapes</a></li>
</ul>
<p>Node.js (and its underlying V8 engine) uses <a href="intl.html#intl_options_for_building_node_js">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.html#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.html#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.html#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.html#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">RegExp Unicode Property Escapes</a></td>
<td>none (invalid RegExp 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.html#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.html#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="lang-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.html#cli_node_icu_data_file"><code>NODE_ICU_DATA</code></a> environment variable:</p>
<pre><code class="lang-shell">env NODE_ICU_DATA=/some/directory node
</code></pre>
</li>
<li><p>The <a href="cli.html#cli_icu_data_dir_file"><code>--icu-data-dir</code></a> CLI parameter:</p>
<pre><code class="lang-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>icudt5X[bl].dat</code>, where <code>5X</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="lang-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="lang-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="lang-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>
<!-- [end-include:intl.md] -->
<!-- [start-include:modules.md] -->
<h1>Modules<span><a class="mark" href="#modules_modules" id="modules_modules">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><!--name=module-->
<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="lang-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="lang-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="lang-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="lang-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>
<!-- type=misc -->
<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>
<!-- type=misc -->
<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>
<!-- type=misc -->
<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="lang-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 = []
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>
<!--type=misc-->
<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>Multiple calls to <code>require('foo')</code> may 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>
<!--type=misc-->
<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>
<!--type=misc-->
<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>
<!--type=misc-->
<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="lang-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="lang-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="lang-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="lang-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>
<!--type=misc-->
<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 '/', './', or '../' 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.html#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>
<!--type=misc-->
<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 package.json file might
look like this:</p>
<pre><code class="lang-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 package.json files.</p>
<p>If the file specified by the <code>'main'</code> entry of <code>package.json</code> is missing and
can not be resolved, Node.js will report the entire module as missing with the
default error:</p>
<pre><code class="lang-txt">Error: Cannot find module 'some-library'
</code></pre>
<p>If there is no package.json file present in the directory, 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 package.json 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>
<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>
<!--type=misc-->
<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
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>
<!-- type=misc -->
<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 locations:</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>
<!-- type=misc -->
<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="lang-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>It helps to provide some global-looking variables that are actually specific
to the module, such as:<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><!-- type=var -->
<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.html#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="lang-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><!-- type=var -->
<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 resolved absolute path of the
current module file.</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="lang-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><!-- type=var -->
<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><!-- type=var -->
<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><!-- type=var -->
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>To require modules.</p>
<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</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>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="lang-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="lang-js">console.log(require.main);
</code></pre>
<pre><code class="lang-sh">node entry.js
</code></pre>
<!-- eslint-skip -->
<pre><code class="lang-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>
<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>
</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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>paths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> Paths to resolve module location from. If present, these
paths are used instead of the default resolution paths. 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/Reference/Global_Objects/Array" class="type"><Array></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
null 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><!-- type=var -->
<!-- name=module -->
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>The module objects required 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 Module 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="lang-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="lang-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>x.js:</p>
<pre><code class="lang-js">setTimeout(() => {
module.exports = { a: 'hello' };
}, 0);
</code></pre>
<p>y.js:</p>
<pre><code class="lang-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="lang-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="lang-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="lang-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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Module object</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="lang-js">const builtin = require('module').builtinModules;
</code></pre>
<!-- [end-include:modules.md] -->
<!-- [start-include:net.md] -->
<h1>Net<span><a class="mark" href="#net_net" id="net_net">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<!--lint disable maximum-line-length-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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="lang-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.html#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 path name. 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. It will be visible in the filesystem, and will <em>persist until
unlinked</em>.</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 appearances, the pipe name space is flat. Pipes will <em>not
persist</em>, they are removed when the last reference to them is closed. Do not
forget JavaScript string escaping requires paths to be specified with
double-backslashes, such as:</p>
<pre><code class="lang-js">net.createServer().listen(
path.join('\\\\?\\pipe', process.cwd(), 'myctl'));
</code></pre>
<h2>Class: net.Server<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>
<div class="signature"><ul>
<li>Returns: <a href="net.html#net_class_net_server" class="type"><net.Server></a></li>
</ul>
</div><p>See <a href="#net_net_createserver_options_connectionlistener"><code>net.createServer([options][, connectionListener])</code></a>.</p>
<p><code>net.Server</code> is an <a href="events.html"><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.html#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.html#net_class_net_socket"><code>net.Socket</code></a>, the <a href="#dgram_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.html#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.html#net_server_listen"><code>server.listen()</code></a>.</p>
<h3>server.address()<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><p>Returns the bound address, the address family name, and port 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.
Returns an object with <code>port</code>, <code>family</code>, and <code>address</code> properties:
<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>
<p>Example:</p>
<pre><code class="lang-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])<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>Returns: <a href="net.html#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="#dgram_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 Error as its only argument if the server
was not open when it was closed.</p>
<p>Returns <code>server</code>.</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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="net.html#net_server_getconnections_callback"><code>server.getConnections()</code></a> instead.</div><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.html#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.html#net_server_getconnections_callback"><code>server.getConnections()</code></a> instead.</p>
<h3>server.getConnections(callback)<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>Returns: <a href="net.html#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()<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
a <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.html#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">socket(7)</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="lang-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])<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.html#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.html#net_server_listen"><code>server.listen()</code></a> functions</li>
<li>Returns: <a href="net.html#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])<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><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:<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.html#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>
</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.html#net_server_listen"><code>server.listen()</code></a>
functions.</li>
<li>Returns: <a href="net.html#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][, hostname][, 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="lang-js">server.listen({
host: 'localhost',
port: 80,
exclusive: true
});
</code></pre>
<h4>server.listen(path[, backlog][, callback])<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.html#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.html#net_server_listen"><code>server.listen()</code></a> functions.</li>
<li>Returns: <a href="net.html#net_class_net_server" class="type"><net.Server></a></li>
</ul>
<p>Start a <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])<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.html#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.html#net_server_listen"><code>server.listen()</code></a> functions.</li>
<li>Returns: <a href="net.html#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><p>A Boolean indicating whether or not the server is listening for
connections.</p>
<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.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>.</p>
<h3>server.ref()<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.html#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>d 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>d calling <code>ref</code> again will have no effect.</p>
<h3>server.unref()<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.html#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>d calling
<code>unref</code> again will have no effect.</p>
<h2>Class: net.Socket<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.html#stream_class_stream_duplex">duplex stream</a>, so it can be both readable and
writable, and it is also a <a href="events.html"><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.html#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(<a href="#zlib_class_options">options</a>)<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><p>Creates a new socket object.</p>
<ul>
<li><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:<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="#stream_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.html#net_class_net_socket" class="type"><net.Socket></a></li>
</ul>
<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>had_error</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>had_error</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.html#buffer_class_buffer" class="type"><Buffer></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"><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"><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>
<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>
</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.html#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.html#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: '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()<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><p>Returns the bound address, the address family name and port of the
socket as reported by the operating system. Returns an object with
three properties, e.g.
<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()<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">socket.connect(options[, connectListener])</a></li>
<li><a href="#net_socket_connect_path_connectlistener">socket.connect(path[, connectListener])</a>
for <a href="#net_ipc_support">IPC</a> connections.</li>
<li><a href="#net_socket_connect_port_host_connectlistener">socket.connect(port[, host][, connectListener])</a>
for TCP connections.</li>
<li>Returns: <a href="net.html#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])<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>
<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>
</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.html#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 4 or 6. <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.html#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.html#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>
<p>Returns <code>socket</code>.</p>
<h4>socket.connect(path[, connectListener])<span><a class="mark" href="#net_socket_connect_path_connectlistener" id="net_socket_connect_path_connectlistener">#</a></span></h4>
<div class="signature"><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.html#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
</div><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>
<p>Returns <code>socket</code>.</p>
<h4>socket.connect(port[, host][, connectListener])<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.html#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>
<p>Returns <code>socket</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 haven't yet finished. Will be set to <code>false</code> before emitting
<code>connect</code> event and/or calling
<a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a>'s
callback.</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>Returns: <a href="net.html#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>
<p>A Boolean value that indicates if the connection is destroyed or not. Once a
connection is destroyed no further data can be transferred using it.</p>
<h3>socket.end([data][, encoding])<span><a class="mark" href="#net_socket_end_data_encoding" id="net_socket_end_data_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li>Returns: <a href="net.html#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"><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>
<div class="signature"><ul>
<li>Returns: <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
</div><p>Pauses the reading of data. That is, <a href="#stream_event_data"><code>'data'</code></a> events will not be emitted.
Useful to throttle back an upload.</p>
<h3>socket.ref()<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.html#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>d 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>d 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>
<div class="signature"><ul>
<li>Returns: <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> The socket itself.</li>
</ul>
</div><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>Returns: <a href="net.html#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.html#stream_class_stream_readable">Readable Stream</a>. See
<a href="stream.html#stream_readable_setencoding_encoding"><code>readable.setEncoding()</code></a> for more information.</p>
<h3>socket.setKeepAlive([enable][, initialDelay])<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>Returns: <a href="net.html#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.
<code>enable</code> defaults to <code>false</code>.</p>
<p>Set <code>initialDelay</code> (in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting 0 for
initialDelay will leave the value unchanged from the default
(or previous) setting. Defaults to <code>0</code>.</p>
<h3>socket.setNoDelay([noDelay])<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>Returns: <a href="net.html#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.
<code>noDelay</code> defaults to <code>true</code>.</p>
<h3>socket.setTimeout(timeout[, callback])<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>Returns: <a href="net.html#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"><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="lang-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()<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.html#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>d 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><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="#stream_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>
<h2>net.connect()<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])<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><p>Alias to
<a href="#net_net_createconnection_options_connectlistener"><code>net.createConnection(options[, connectListener])</code></a>.</p>
<h3>net.connect(path[, connectListener])<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><p>Alias to
<a href="#net_net_createconnection_path_connectlistener"><code>net.createConnection(path[, connectListener])</code></a>.</p>
<h3>net.connect(port[, host][, connectListener])<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><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.html#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.html#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="lang-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="lang-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.html#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.html#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.html#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.html#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])<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><p>Creates a new TCP or <a href="#net_ipc_support">IPC</a> server.</p>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.html#net_class_net_server" class="type"><net.Server></a></li>
</ul>
<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"><code>socket.end()</code></a> is explicitly called, until then the connection is
half-closed (non-readable but still writable). See <a href="#stream_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 a <a href="#net_ipc_support">IPC</a> server, depending on what it
<a href="net.html#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="lang-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="lang-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="lang-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="lang-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><p>Tests if input is an IP address. Returns 0 for invalid strings,
returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.</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><p>Returns true if input is a version 4 IP address, otherwise returns false.</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><p>Returns true if input is a version 6 IP address, otherwise returns false.</p>
<!-- [end-include:net.md] -->
<!-- [start-include:os.md] -->
<h1>OS<span><a class="mark" href="#os_os" id="os_os">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p>The <code>os</code> module provides a number of operating system-related utility methods.
It can be accessed using:</p>
<pre><code class="lang-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()<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.html#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()<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/Array" class="type"><Array></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><code>times</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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="lang-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()<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.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()<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/Reference/Global_Objects/Array" class="type"><Array></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()<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="lang-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',
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',
internal: false,
cidr: 'fe80::a00:27ff:fe4e:66a1/64'
}
]
}
</code></pre>
<h2>os.platform()<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.html#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">uname(3)</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.tmpdir()<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>
<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>
</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">uname(3)</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">uname(3)</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">
<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.uptime()</code> method returns the system uptime in number of seconds.</p>
<p>On Windows the returned value includes fractions of a second. Use <code>Math.floor()</code>
to get whole seconds.</p>
<h2>os.userInfo(<a href="#zlib_class_options">options</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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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>
<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>
</table>
</details>
</div><p>The following signal constants are exported by <code>os.constants.signals</code>:</p>
<table>
<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>
</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>
<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.
</tr>
</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>
<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 winsock.dll 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>
</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">dlopen(3)</a> for detailed
information.</p>
<table>
<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 <a href="http://man7.org/linux/man-pages/man3/dlopen.3.html">dlopen(3)</a>
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 RTLD_GLOBAL. 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>
</table>
<h3>libuv Constants<span><a class="mark" href="#os_libuv_constants" id="os_libuv_constants">#</a></span></h3>
<table>
<tr>
<th>Constant</th>
<th>Description</th>
</tr>
<tr>
<td><code>UV_UDP_REUSEADDR</code></td>
<td></td>
</tr>
</table>
<!-- [end-include:os.md] -->
<!-- [start-include:path.md] -->
<h1>Path<span><a class="mark" href="#path_path" id="path_path">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p>The <code>path</code> module provides utilities for working with file and directory paths.
It can be accessed using:</p>
<pre><code class="lang-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>For example, using the <code>path.basename()</code> function with the Windows file path
<code>C:\temp\myfile.html</code>, will yield different results when running on POSIX than
when run on Windows:</p>
<p>On POSIX:</p>
<pre><code class="lang-js">path.basename('C:\\temp\\myfile.html');
// Returns: 'C:\\temp\\myfile.html'
</code></pre>
<p>On Windows:</p>
<pre><code class="lang-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="lang-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="lang-js">path.posix.basename('/tmp/myfile.html');
// Returns: 'myfile.html'
</code></pre>
<p><em>Note:</em> 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://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#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>
<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>
</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="lang-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.html#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="lang-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="lang-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>
<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>
</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="lang-js">path.dirname('/foo/bar/baz/asdf/quux');
// Returns: '/foo/bar/baz/asdf'
</code></pre>
<p>A <a href="errors.html#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>
<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>
</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="lang-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.html#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><code>pathObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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="lang-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="lang-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="lang-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="lang-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.html#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="lang-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.html#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="lang-js">path.normalize('/foo/bar//baz/asdf/quux/..');
// Returns: '/foo/bar/baz/asdf'
</code></pre>
<p>On Windows:</p>
<pre><code class="lang-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="lang-js">path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar');
// Returns: 'C:\\temp\\foo\\bar'
</code></pre>
<p>A <a href="errors.html#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="lang-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="lang-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="lang-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="lang-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.html#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>
<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>
</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="lang-js">path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
// Returns: '../../impl/bbb'
</code></pre>
<p>On Windows:</p>
<pre><code class="lang-js">path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb');
// Returns: '..\\..\\impl\\bbb'
</code></pre>
<p>A <a href="errors.html#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="lang-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.html#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="lang-js">'foo/bar/baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz']
</code></pre>
<p>On Windows:</p>
<pre><code class="lang-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://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#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>
<!-- [end-include:path.md] -->
<!-- [start-include:perf_hooks.md] -->
<h1>Performance Timing API<span><a class="mark" href="#perf_hooks_performance_timing_api" id="perf_hooks_performance_timing_api">#</a></span></h1>
<!--introduced_in=v8.5.0-->
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><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="lang-js">const { performance } = require('perf_hooks');
performance.mark('A');
doSomeLongRunningProcess(() => {
performance.mark('B');
performance.measure('A to B', 'A', 'B');
const measure = performance.getEntriesByName('A to B')[0];
console.log(measure.duration);
// Prints the number of milliseconds between Mark 'A' and Mark '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><p>The <code>Performance</code> provides access to performance metric data. A single
instance of this class is provided via the <code>performance</code> property.</p>
<h3>performance.clearEntries(name)<span><a class="mark" href="#perf_hooks_performance_clearentries_name" id="perf_hooks_performance_clearentries_name">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.5.0</span>
</div><p>Remove all performance entry objects with <code>entryType</code> equal to <code>name</code> from the
Performance Timeline.</p>
<h3>performance.clearFunctions([name])<span><a class="mark" href="#perf_hooks_performance_clearfunctions_name" id="perf_hooks_performance_clearfunctions_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>PerformanceFunction</code> objects from the
Performance Timeline. If <code>name</code> is provided, removes entries with <code>name</code>.</p>
<h3>performance.clearGC()<span><a class="mark" href="#perf_hooks_performance_cleargc" id="perf_hooks_performance_cleargc">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div><p>Remove all performance entry objects with <code>entryType</code> equal to <code>gc</code> from the
Performance Timeline.</p>
<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.clearMeasures([name])<span><a class="mark" href="#perf_hooks_performance_clearmeasures_name" id="perf_hooks_performance_clearmeasures_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>PerformanceMeasure</code> objects from the
Performance Timeline. If <code>name</code> is provided, removes only objects whose
<code>performanceEntry.name</code> matches <code>name</code>.</p>
<h3>performance.getEntries()<span><a class="mark" href="#perf_hooks_performance_getentries" id="perf_hooks_performance_getentries">#</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/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>Returns a list of all <code>PerformanceEntry</code> objects in chronological order
with respect to <code>performanceEntry.startTime</code>.</p>
<h3>performance.getEntriesByName(name[, type])<span><a class="mark" href="#perf_hooks_performance_getentriesbyname_name_type" id="perf_hooks_performance_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>Returns a list of all <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>performance.getEntriesByType(type)<span><a class="mark" href="#perf_hooks_performance_getentriesbytype_type" id="perf_hooks_performance_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>Returns a list of all <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>
<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.maxEntries<span><a class="mark" href="#perf_hooks_performance_maxentries" id="perf_hooks_performance_maxentries">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
</div><p>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></p>
<p>The maximum number of Performance Entry items that should be added to the
Performance Timeline. This limit is not strictly enforced, but a process
warning will be emitted if the number of entries in the timeline exceeds
this limit.</p>
<p>Defaults to 150.</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><span class="type"><PerformanceNodeTiming></span></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="lang-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();
performance.clearFunctions();
});
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. Current it may be one of: <code>'node'</code>, <code>'mark'</code>,
<code>'measure'</code>, <code>'gc'</code>, or <code>'function'</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.clusterSetupEnd<span><a class="mark" href="#perf_hooks_performancenodetiming_clustersetupend" id="perf_hooks_performancenodetiming_clustersetupend">#</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 cluster processing ended. If
cluster processing has not yet ended, the property has the value of -1.</p>
<h3>performanceNodeTiming.clusterSetupStart<span><a class="mark" href="#perf_hooks_performancenodetiming_clustersetupstart" id="perf_hooks_performancenodetiming_clustersetupstart">#</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 cluster processing started.
If cluster processing has not yet started, 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.moduleLoadEnd<span><a class="mark" href="#perf_hooks_performancenodetiming_moduleloadend" id="perf_hooks_performancenodetiming_moduleloadend">#</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 main module load ended.</p>
<h3>performanceNodeTiming.moduleLoadStart<span><a class="mark" href="#perf_hooks_performancenodetiming_moduleloadstart" id="perf_hooks_performancenodetiming_moduleloadstart">#</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 main module load started.</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.preloadModuleLoadEnd<span><a class="mark" href="#perf_hooks_performancenodetiming_preloadmoduleloadend" id="perf_hooks_performancenodetiming_preloadmoduleloadend">#</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 preload module load ended.</p>
<h3>performanceNodeTiming.preloadModuleLoadStart<span><a class="mark" href="#perf_hooks_performancenodetiming_preloadmoduleloadstart" id="perf_hooks_performancenodetiming_preloadmoduleloadstart">#</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 preload module load started.</p>
<h3>performanceNodeTiming.thirdPartyMainEnd<span><a class="mark" href="#perf_hooks_performancenodetiming_thirdpartymainend" id="perf_hooks_performancenodetiming_thirdpartymainend">#</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 third_party_main
processing ended. If third_party_main processing has not yet ended, the
property has the value of -1.</p>
<h3>performanceNodeTiming.thirdPartyMainStart<span><a class="mark" href="#perf_hooks_performancenodetiming_thirdpartymainstart" id="perf_hooks_performancenodetiming_thirdpartymainstart">#</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 third_party_main
processing started. If third_party_main processing has not yet started, the
property has the value of -1.</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(callback)<span><a class="mark" href="#perf_hooks_class_performanceobserver_callback" id="perf_hooks_class_performanceobserver_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v8.5.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> A <code>PerformanceObserverCallback</code> callback function.</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="lang-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>
<h3>Callback: PerformanceObserverCallback(list, observer)<span><a class="mark" href="#perf_hooks_callback_performanceobservercallback_list_observer" id="perf_hooks_callback_performanceobservercallback_list_observer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div><ul>
<li><code>list</code> <a href="perf_hooks.html#perf_hooks_class_performanceobserverentrylist" class="type"><PerformanceObserverEntryList></a></li>
<li><code>observer</code> <a href="perf_hooks.html#perf_hooks_class_performanceobserver_callback" class="type"><PerformanceObserver></a></li>
</ul>
<p>The <code>PerformanceObserverCallback</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>Class: PerformanceObserverEntryList<span><a class="mark" href="#perf_hooks_class_performanceobserverentrylist" id="perf_hooks_class_performanceobserverentrylist">#</a></span></h3>
<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>
<h4>performanceObserverEntryList.getEntries()<span><a class="mark" href="#perf_hooks_performanceobserverentrylist_getentries" id="perf_hooks_performanceobserverentrylist_getentries">#</a></span></h4>
<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/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>Returns a list of <code>PerformanceEntry</code> objects in chronological order
with respect to <code>performanceEntry.startTime</code>.</p>
<h4>performanceObserverEntryList.getEntriesByName(name[, type])<span><a class="mark" href="#perf_hooks_performanceobserverentrylist_getentriesbyname_name_type" id="perf_hooks_performanceobserverentrylist_getentriesbyname_name_type">#</a></span></h4>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></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>
<h4>performanceObserverEntryList.getEntriesByType(type)<span><a class="mark" href="#perf_hooks_performanceobserverentrylist_getentriesbytype_type" id="perf_hooks_performanceobserverentrylist_getentriesbytype_type">#</a></span></h4>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></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>
<h3>performanceObserver.disconnect()<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)<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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>entryTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></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. Defaults to <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="lang-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="lang-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>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="lang-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();
performance.clearMeasures();
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="lang-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();
// Free memory
performance.clearFunctions();
});
obs.observe({ entryTypes: ['function'], buffered: true });
require('some-module');
</code></pre>
<!-- [end-include:perf_hooks.md] -->
<!-- [start-include:process.md] -->
<h1>Process<span><a class="mark" href="#process_process" id="process_process">#</a></span></h1>
<!-- introduced_in=v0.10.0 -->
<!-- type=global -->
<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.html"><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><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, as the only argument.</p>
<pre><code class="lang-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="lang-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><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.html#child_process_subprocess_send_message_sendhandle_options_callback"><code>childprocess.send()</code></a> is received by
the child process.</p>
<p>The listener callback is invoked with the following arguments:</p>
<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> <span class="type"><Handle object></span> a <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> or <a href="net.html#net_class_net_server"><code>net.Server</code></a> object, or
undefined.</li>
</ul>
<p>The message goes through serialization and parsing. The resulting message might
not be the same as what is originally sent.</p>
<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><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 listener callback is invoked with a reference to the rejected <code>Promise</code> as
the only argument.</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="lang-js">const unhandledRejections = new Map();
process.on('unhandledRejection', (reason, p) => {
unhandledRejections.set(p, reason);
});
process.on('rejectionHandled', (p) => {
unhandledRejections.delete(p);
});
</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">
<span>Added in: v0.1.18</span>
</div><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.
Adding a handler for the <code>'uncaughtException'</code> event overrides this default
behavior.</p>
<p>The listener function is called with the <code>Error</code> object passed as the only
argument.</p>
<pre><code class="lang-js">process.on('uncaughtException', (err) => {
fs.writeSync(1, `Caught exception: ${err}\n`);
});
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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>Not handling Promise rejections has been deprecated.</p>
</td></tr>
<tr><td>v6.6.0</td>
<td><p>Unhandled Promise 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>
</table>
</details>
</div><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>
<p>The listener function is called with the following arguments:</p>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a> | <span class="type"><any></span> The object with which the promise was rejected
(typically an <a href="errors.html#errors_class_error"><code>Error</code></a> object).</li>
<li><code>p</code> the <code>Promise</code> that was rejected.</li>
</ul>
<pre><code class="lang-js">process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, '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="lang-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. Alternatively, the <a href="#process_event_rejectionhandled"><code>'rejectionHandled'</code></a> event may be used.</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><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>
<p>The listener function is called with a single <code>warning</code> argument whose value is
an <code>Error</code> object. There are three key properties that describe the warning:</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 (currently <code>Warning</code> by default).</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>
<pre><code class="lang-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="lang-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="lang-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>
<!--type=event-->
<!--name=SIGINT, SIGHUP, etc.-->
<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">signal(7)</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="lang-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">signal(7)</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">kill(2)</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.html#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>
<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="lang-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/Reference/Global_Objects/Array" class="type"><Array></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="lang-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="lang-console">$ node process-args.js one two=three four
</code></pre>
<p>Would generate the output:</p>
<pre><code class="lang-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="lang-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="lang-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>
<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 Object 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="lang-js">{
target_defaults:
{ cflags: [],
default_configuration: 'Release',
defines: [],
include_dirs: [],
libraries: [] },
variables:
{
host_arch: 'x64',
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>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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="lang-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="lang-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="lang-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.html#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>
<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>
</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.html#os_dlopen_constants" class="type"><os.constants.dlopen></a> Defaults to <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.html#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.html#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.html#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="lang-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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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 String, <code>type</code> is the name to use
for the <em>type</em> of warning being emitted. Default: <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 String, <code>ctor</code> is an optional
function used to limit the generated stack trace. Default
<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>process.on('warning')</code></a> event.</p>
<pre><code class="lang-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>process.on('warning')</code></a> event.</p>
<pre><code class="lang-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 String, <code>type</code> is the name to use
for the <em>type</em> of warning being emitted. Default: <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 String, <code>ctor</code> is an optional
function used to limit the generated stack trace. Default
<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>process.on('warning')</code></a> event.</p>
<pre><code class="lang-js">// Emit a warning using a string.
process.emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!
</code></pre>
<pre><code class="lang-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="lang-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>process.on('warning')</code></a> event.</p>
<pre><code class="lang-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>process.on('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="lang-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="lang-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">
<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></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">environ(7)</a>.</p>
<p>An example of this object looks like:</p>
<!-- eslint-skip -->
<pre><code class="lang-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="lang-console">$ node -e 'process.env.foo = "bar"' && echo $foo
</code></pre>
<p>While the following will:</p>
<pre><code class="lang-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.</p>
<p>Example:</p>
<pre><code class="lang-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>
<p>Example:</p>
<pre><code class="lang-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>
<p>Example:</p>
<pre><code class="lang-js">process.env.TEST = 1;
console.log(process.env.test);
// => 1
</code></pre>
<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/Reference/Global_Objects/Array" class="type"><Array></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="lang-console">$ node --harmony script.js --version
</code></pre>
<p>Results in <code>process.execArgv</code>:</p>
<!-- eslint-disable semi -->
<pre><code class="lang-js">['--harmony']
</code></pre>
<p>And <code>process.argv</code>:</p>
<!-- eslint-disable semi -->
<pre><code class="lang-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="lang-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. Defaults to <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="lang-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="lang-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="lang-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>
<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">getegid(2)</a>.)</p>
<pre><code class="lang-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">geteuid(2)</a>.)</p>
<pre><code class="lang-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">getgid(2)</a>.)</p>
<pre><code class="lang-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/Reference/Global_Objects/Array" class="type"><Array></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">getuid(2)</a>.)</p>
<pre><code class="lang-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.html#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/Reference/Global_Objects/Array" class="type"><Array></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/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>The <code>process.hrtime()</code> method returns the current high-resolution real time
in a <code>[seconds, nanoseconds]</code> tuple Array, 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 Array, 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="lang-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.initgroups(user, extra_group)<span><a class="mark" href="#process_process_initgroups_user_extra_group" id="process_process_initgroups_user_extra_group">#</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>extra_group</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. Example:</p>
<pre><code class="lang-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).</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.
Defaults to <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">kill(2)</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="lang-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.html#modules_accessing_the_main_module"><code>require.main</code></a>. The difference is that if the main module changes at
runtime, <a href="modules.html#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.html#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>
<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>
</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><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="lang-js">console.log(process.memoryUsage());
</code></pre>
<p>Will generate:</p>
<!-- eslint-skip -->
<pre><code class="lang-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>
<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>
<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>
</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> <span class="type"><any></span> 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.html#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="lang-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="lang-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="lang-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="lang-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="lang-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
nextTick 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="lang-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="lang-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="lang-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>
<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>
</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 Object 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><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/LTS/">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:<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="lang-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> <span class="type"><Handle object></span></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.html#child_process_event_message"><code>'message'</code></a> event on the parent's <a href="child_process.html#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">setegid(2)</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="lang-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).</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">seteuid(2)</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="lang-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).</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">setgid(2)</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="lang-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).</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/Reference/Global_Objects/Array" class="type"><Array></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).</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><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">setuid(2)</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="lang-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).</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.setUncaughtExceptionCapture</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.html#process_event_uncaughtexception"><code>process.on('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.html#v8_v8_setflagsfromstring_flags"><code>v8.setFlagsFromString()</code></a>, the process will
not abort.</p>
<p>To unset the capture function, <code>process.setUncaughtExceptionCapture(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>
<div class="signature"><ul>
<li><a href="stream.html#stream_stream" class="type"><Stream></a></li>
</ul>
</div><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.html#net_class_net_socket"><code>net.Socket</code></a> (which is a <a href="#stream_class_stream_duplex">Duplex</a>
stream) unless fd <code>2</code> refers to a file, in which case it is
a <a href="#stream_class_stream_writable">Writable</a> stream.</p>
<p><code>process.stderr</code> differs from other Node.js streams in important ways, see
<a href="process.html#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>
<div class="signature"><ul>
<li><a href="stream.html#stream_stream" class="type"><Stream></a></li>
</ul>
</div><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.html#net_class_net_socket"><code>net.Socket</code></a> (which is a <a href="#stream_class_stream_duplex">Duplex</a>
stream) unless fd <code>0</code> refers to a file, in which case it is
a <a href="#stream_class_stream_readable">Readable</a> stream.</p>
<pre><code class="lang-js">process.stdin.setEncoding('utf8');
process.stdin.on('readable', () => {
const chunk = process.stdin.read();
if (chunk !== null) {
process.stdout.write(`data: ${chunk}`);
}
});
process.stdin.on('end', () => {
process.stdout.write('end');
});
</code></pre>
<p>As a <a href="#stream_class_stream_duplex">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.html#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>
<div class="signature"><ul>
<li><a href="stream.html#stream_stream" class="type"><Stream></a></li>
</ul>
</div><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.html#net_class_net_socket"><code>net.Socket</code></a> (which is a <a href="#stream_class_stream_duplex">Duplex</a>
stream) unless fd <code>1</code> refers to a file, in which case it is
a <a href="#stream_class_stream_writable">Writable</a> stream.</p>
<p>For example, to copy process.stdin to process.stdout:</p>
<pre><code class="lang-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.html#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.html#console_console_log_data_args"><code>console.log()</code></a> and <a href="console.html#console_console_error_data_args"><code>console.error()</code></a>,
respectively.</li>
<li>They cannot be closed (<a href="stream.html#stream_writable_end_chunk_encoding_callback"><code>end()</code></a> will throw).</li>
<li>They will never emit the <a href="#stream_event_finish"><code>'finish'</code></a> event.</li>
<li>Writes may be synchronous depending on what the stream is connected to
and whether the system is Windows or POSIX:<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.html">TTY</a> context, check the <code>isTTY</code>
property.</p>
<p>For instance:</p>
<pre><code class="lang-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.html">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="lang-js">const newmask = 0o022;
const oldmask = process.umask(newmask);
console.log(
`Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`
);
</code></pre>
<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="lang-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>
<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>
</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="lang-js">console.log(process.versions);
</code></pre>
<p>Will generate an object similar to:</p>
<!-- eslint-skip -->
<pre><code class="lang-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.html#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 a <a href="process.html#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>
<!-- [end-include:process.md] -->
<!-- [start-include:punycode.md] -->
<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>
<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>
</table>
</details>
</div><!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><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://mths.be/punycode">Punycode.js</a> module instead.</p>
<p>The <code>punycode</code> module is a bundled version of the <a href="https://mths.be/punycode">Punycode.js</a> module. It
can be accessed using:</p>
<pre><code class="lang-js">const punycode = require('punycode');
</code></pre>
<p><a href="https://tools.ietf.org/html/rfc5891#section-4.4">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://mths.be/punycode">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/rfc5891#section-4.4">Punycode</a> string of ASCII-only
characters to the equivalent string of Unicode codepoints.</p>
<pre><code class="lang-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/rfc5891#section-4.4">Punycode</a> string of ASCII-only characters.</p>
<pre><code class="lang-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/rfc5891#section-4.4">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="lang-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/rfc5891#section-4.4">Punycode</a> encoded characters into Unicode. Only the <a href="https://tools.ietf.org/html/rfc5891#section-4.4">Punycode</a>
encoded parts of the domain name are be converted.</p>
<pre><code class="lang-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="lang-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/Reference/Global_Objects/Array" class="type"><Array></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="lang-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><p>Returns a string identifying the current <a href="https://mths.be/punycode">Punycode.js</a> version number.</p>
<!-- [end-include:punycode.md] -->
<!-- [start-include:querystring.md] -->
<h1>Query String<span><a class="mark" href="#querystring_query_string" id="querystring_query_string">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><!--name=querystring-->
<p>The <code>querystring</code> module provides utilities for parsing and formatting URL
query strings. It can be accessed using:</p>
<pre><code class="lang-js">const querystring = require('querystring');
</code></pre>
<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>
<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>
</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. Defaults to <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. Defaults to <code>'='</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><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. Defaults to
<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.
Defaults to <code>1000</code>. Specify <code>0</code> to remove key counting limitations.</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="lang-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 as illustrated
in the following example:</p>
<pre><code class="lang-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. Defaults to <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. Defaults to <code>'='</code>.</li>
<li><code>options</code><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. Defaults to
<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="lang-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 as illustrated in the
following example:</p>
<pre><code class="lang-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>
<!-- [end-include:querystring.md] -->
<!-- [start-include:readline.md] -->
<h1>Readline<span><a class="mark" href="#readline_readline" id="readline_readline">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p>The <code>readline</code> module provides an interface for reading data from a <a href="#stream_class_stream_readable">Readable</a>
stream (such as <a href="process.html#process_process_stdin"><code>process.stdin</code></a>) one line at a time. It can be accessed using:</p>
<pre><code class="lang-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="lang-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_class_stream_readable">Readable</a> stream and a single <code>output</code> <a href="#stream_class_stream_writable">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="lang-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.html#readline_event_sigtstp"><code>SIGTSTP</code></a> and <a href="readline.html#readline_event_sigcont"><code>SIGCONT</code></a>)</li>
</ul>
<p>The listener function is called without passing any arguments.</p>
<pre><code class="lang-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="lang-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">fg(1p)</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="lang-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="lang-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">fg(1p)</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="lang-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>
<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="lang-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><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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="lang-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> Interface's
<code>input</code> <em>as if it were provided by the user</em>.</p>
<h2>readline.clearLine(stream, dir)<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.html#stream_class_stream_writable" class="type"><stream.Writable></a></li>
<li><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a><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)<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.html#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)<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>
<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>
</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><ul>
<li><code>input</code> <a href="stream.html#stream_class_stream_readable" class="type"><stream.Readable></a> The <a href="#stream_class_stream_readable">Readable</a> stream to listen to. This option
is <em>required</em>.</li>
<li><code>output</code> <a href="stream.html#stream_class_stream_writable" class="type"><stream.Writable></a> The <a href="#stream_class_stream_writable">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.
Defaults to 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>
</ul>
</li>
</ul>
<p>The <code>readline.createInterface()</code> method creates a new <code>readline.Interface</code>
instance.</p>
<pre><code class="lang-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="lang-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.html#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 Array with 2 entries:</p>
<ul>
<li>An Array 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="lang-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="lang-js">function completer(linePartial, callback) {
callback(null, [['123'], linePartial]);
}
</code></pre>
<h2>readline.cursorTo(stream, x, y)<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.html#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])<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.html#stream_class_stream_readable" class="type"><stream.Readable></a></li>
<li><code>interface</code> <a href="readline.html#readline_class_interface" class="type"><readline.Interface></a></li>
</ul>
<p>The <code>readline.emitKeypressEvents()</code> method causes the given <a href="#stream_class_stream_readable">Readable</a>
<code>stream</code> 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="lang-js">readline.emitKeypressEvents(process.stdin);
if (process.stdin.isTTY)
process.stdin.setRawMode(true);
</code></pre>
<h2>readline.moveCursor(stream, dx, dy)<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.html#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="lang-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 input from a filesystem
<a href="#stream_class_stream_readable">Readable</a> stream one line at a time, as illustrated in the following
example:</p>
<pre><code class="lang-js">const readline = require('readline');
const fs = require('fs');
const rl = readline.createInterface({
input: fs.createReadStream('sample.txt'),
crlfDelay: Infinity
});
rl.on('line', (line) => {
console.log(`Line from file: ${line}`);
});
</code></pre>
<!-- [end-include:readline.md] -->
<!-- [start-include:repl.md] -->
<h1>REPL<span><a class="mark" href="#repl_repl" id="repl_repl">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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="lang-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 <code>repl.REPLServer</code> class. While running, instances
of <code>repl.REPLServer</code> 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_stream">stream</a>.</p>
<p>Instances of <code>repl.REPLServer</code> 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="lang-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 <code>repl.REPLServer</code> 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 <code>repl.REPLServer</code> 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="lang-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="lang-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="lang-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="lang-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="lang-js">> fs.createReadStream('./some/file');
</code></pre>
<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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.8.0</td>
<td><p>Added <code>_error</code> support.</p>
</td></tr>
</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="lang-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="lang-js">> throw new Error('foo');
Error: foo
> _error.message
'foo'
</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 <code>repl.REPLServer</code> 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="lang-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="lang-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, <code>repl.REPLServer</code> 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 Writable
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 <code>repl.REPLServer</code> 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="lang-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.html#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="lang-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 as illustrated in the following simple example:</p>
<pre><code class="lang-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="lang-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 Function or an object 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="lang-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="lang-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> <span class="type"><any></span> any parameters to the keyword command</li>
</ul>
<div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated.</div><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(<a href="#zlib_class_options">options</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>
<tr><th>Version</th><th>Changes</th></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>
</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a><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. Defaults to <code>></code>
(with a trailing space).</li>
<li><code>input</code> <a href="stream.html#stream_class_stream_readable" class="type"><stream.Readable></a> The Readable stream from which REPL input will be
read. Defaults to <code>process.stdin</code>.</li>
<li><code>output</code> <a href="stream.html#stream_class_stream_writable" class="type"><stream.Writable></a> The Writable stream to which REPL output will be
written. Defaults to <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.
Defaults to 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. Defaults to 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>. Defaults to <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>. Defaults to <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>. Defaults to <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.html#readline_use_of_the_completer_function"><code>readline.InterfaceCompleter</code></a> for an example.</li>
<li><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:<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>
<li><code>repl.REPL_MODE_MAGIC</code> - This value is <strong>deprecated</strong>, since enhanced
spec compliance in V8 has rendered magic mode unnecessary. It is now
equivalent to <code>repl.REPL_MODE_SLOPPY</code> (documented above).</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. Defaults to <code>false</code>.</li>
</ul>
</li>
</ul>
<p>The <code>repl.start()</code> method creates and starts a <code>repl.REPLServer</code> instance.</p>
<p>If <code>options</code> is a string, then it specifies the input prompt:</p>
<pre><code class="lang-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="lang-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> will disable persistent
REPL history. Whitespace will be trimmed from the value.</li>
<li><code>NODE_REPL_HISTORY_SIZE</code> - Defaults to <code>1000</code>. Controls how many lines of
history will be persisted if history is available. Must be a positive number.</li>
<li><code>NODE_REPL_MODE</code> - May be any of <code>sloppy</code>, <code>strict</code>, or <code>magic</code>. Defaults
to <code>sloppy</code>, which will allow non-strict mode code to be run. <code>magic</code> is
<strong>deprecated</strong> and treated as an alias of <code>sloppy</code>.</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>
<h4>NODE_REPL_HISTORY_FILE<span><a class="mark" href="#repl_node_repl_history_file" id="repl_node_repl_history_file">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v2.0.0</span><span>Deprecated since: v3.0.0</span>
</div><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>NODE_REPL_HISTORY</code> instead.</div><p>Previously in Node.js/io.js v2.x, REPL history was controlled by using a
<code>NODE_REPL_HISTORY_FILE</code> environment variable, and the history was saved in JSON
format. This variable has now been deprecated, and the old JSON REPL history
file will be automatically converted to a simplified plain text format. This new
file will be saved to either the user's home directory, or a directory defined
by the <code>NODE_REPL_HISTORY</code> variable, as documented in the
<a href="#repl_environment_variable_options">Environment Variable Options</a>.</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="lang-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="lang-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/2209310">https://gist.github.com/2209310</a></p>
<p>For an example of running a REPL instance over <a href="https://curl.haxx.se/docs/manpage.html">curl(1)</a>,
see: <a href="https://gist.github.com/2053342">https://gist.github.com/2053342</a></p>
<!-- [end-include:repl.md] -->
<!-- [start-include:stream.md] -->
<h1>Stream<span><a class="mark" href="#stream_stream" id="stream_stream">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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.html#http_class_http_incomingmessage">request to an HTTP server</a> and <a href="process.html#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.html"><code>EventEmitter</code></a>.</p>
<p>The <code>stream</code> module can be accessed using:</p>
<pre><code class="lang-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_readable">Readable</a> - streams from which data can be read (for example
<a href="fs.html#fs_fs_createreadstream_path_options"><code>fs.createReadStream()</code></a>).</li>
<li><a href="#stream_class_stream_writable">Writable</a> - streams to which data can be written (for example
<a href="fs.html#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a>).</li>
<li><a href="#stream_class_stream_duplex">Duplex</a> - streams that are both Readable and Writable (for example
<a href="net.html#net_class_net_socket"><code>net.Socket</code></a>).</li>
<li><a href="#stream_class_stream_transform">Transform</a> - Duplex streams that can modify or transform the data as it
is written and read (for example <a href="zlib.html#zlib_zlib_createdeflate_options"><code>zlib.createDeflate()</code></a>).</li>
</ul>
<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>
<!--type=misc-->
<p>Both <a href="#stream_class_stream_writable">Writable</a> and <a href="#stream_class_stream_readable">Readable</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 streams 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 Readable 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 Writable 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">Duplex</a> and <a href="#stream_class_stream_transform">Transform</a> streams are both Readable and Writable,
each maintain <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.html#net_class_net_socket"><code>net.Socket</code></a> instances
are <a href="#stream_class_stream_duplex">Duplex</a> streams whose Readable side allows consumption of data received
<em>from</em> the socket and whose Writable 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>
<!--type=misc-->
<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="lang-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">Writable</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">Readable</a> streams use the <a href="events.html"><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">Writable</a> and <a href="#stream_class_stream_readable">Readable</a> streams use the <a href="events.html"><code>EventEmitter</code></a> API in
various ways to communicate the current state of the stream.</p>
<p><a href="#stream_class_stream_duplex">Duplex</a> and <a href="#stream_class_stream_transform">Transform</a> streams are both <a href="#stream_class_stream_writable">Writable</a> and <a href="#stream_class_stream_readable">Readable</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">Writable</a> streams include:</p>
<ul>
<li><a href="http.html#http_class_http_clientrequest">HTTP requests, on the client</a></li>
<li><a href="http.html#http_class_http_serverresponse">HTTP responses, on the server</a></li>
<li><a href="fs.html#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.html#net_class_net_socket">TCP sockets</a></li>
<li><a href="child_process.html#child_process_subprocess_stdin">child process stdin</a></li>
<li><a href="process.html#process_process_stdout"><code>process.stdout</code></a>, <a href="process.html#process_process_stderr"><code>process.stderr</code></a></li>
</ul>
<p>Some of these examples are actually <a href="#stream_class_stream_duplex">Duplex</a> streams that implement the
<a href="#stream_class_stream_writable">Writable</a> interface.</p>
<p>All <a href="#stream_class_stream_writable">Writable</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">Writable</a> streams may differ in various ways,
all Writable streams follow the same fundamental usage pattern as illustrated
in the example below:</p>
<pre><code class="lang-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><!--type=class-->
<h5>Event: 'close'<span><a class="mark" href="#stream_event_close" id="stream_event_close">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</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>Not all Writable streams will emit the <code>'close'</code> event.</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="lang-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="lang-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.error('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.html#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="lang-js">const writer = getWritableStreamSomehow();
const reader = getReadableStreamSomehow();
writer.on('pipe', (src) => {
console.error('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.html#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">Readable</a> stream, removing this <a href="#stream_class_stream_writable">Writable</a> from its set of
destinations.</p>
<p>This is also emitted in case this <a href="#stream_class_stream_writable">Writable</a> stream emits an error when a
<a href="#stream_class_stream_readable">Readable</a> stream pipes into it.</p>
<pre><code class="lang-js">const writer = getWritableStreamSomehow();
const reader = getReadableStreamSomehow();
writer.on('unpipe', (src) => {
console.error('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.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>
<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.4</td>
<td><p><span>Added in: v0.9.4</span></p>
</td></tr>
</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.html#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> | <span class="type"><any></span> 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>
</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">Writable</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="lang-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>
<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>
</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">Writable</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="lang-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="lang-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.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><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>
<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>
</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.html#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> | <span class="type"><any></span> 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 write() 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">Transform</a>, because the <code>Transform</code> streams are paused
by default until they are piped or an <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">Readable</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="lang-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 Writable stream in object mode will always ignore the <code>encoding</code> argument.</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>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 error. After this call, the
writable stream has ended. Implementors should not override this method,
but instead implement <a href="#stream_writable_destroy_err_callback"><code>writable._destroy</code></a>.</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 Readable streams include:</p>
<ul>
<li><a href="http.html#http_class_http_incomingmessage">HTTP responses, on the client</a></li>
<li><a href="http.html#http_class_http_incomingmessage">HTTP requests, on the server</a></li>
<li><a href="fs.html#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.html#net_class_net_socket">TCP sockets</a></li>
<li><a href="child_process.html#child_process_subprocess_stdout">child process stdout and stderr</a></li>
<li><a href="process.html#process_process_stdin"><code>process.stdin</code></a></li>
</ul>
<p>All <a href="#stream_class_stream_readable">Readable</a> streams implement the interface defined by the
<code>stream.Readable</code> class.</p>
<h4>Two Modes<span><a class="mark" href="#stream_two_modes" id="stream_two_modes">#</a></span></h4>
<p>Readable streams effectively operate in one of two modes: flowing and paused.</p>
<p>When 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.html"><code>EventEmitter</code></a> interface.</p>
<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>
<p>All <a href="#stream_class_stream_readable">Readable</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">Writable</a>.</li>
</ul>
<p>The Readable 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 Readable 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 Readable will <em>attempt</em>
to stop generating the data.</p>
<p>For backwards 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">Readable</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>
<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 Readable stream are a simplified abstraction
for the more complicated internal state management that is happening within the
Readable stream implementation.</p>
<p>Specifically, at any given point in time, every Readable 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
streams data is provided so the stream will not generate its 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 Readable to begin
actively emitting events as data is generated.</p>
<p>Calling <code>readable.pause()</code>, <code>readable.unpipe()</code>, or receiving "back pressure"
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
would not cause <code>readable.readableFlowing</code> to switch to <code>true</code>.</p>
<pre><code class="lang-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 'data' being emitted
</code></pre>
<p>While <code>readable.readableFlowing</code> is <code>false</code>, data may be accumulating
within the streams internal buffer.</p>
<h4>Choose One<span><a class="mark" href="#stream_choose_one" id="stream_choose_one">#</a></span></h4>
<p>The Readable 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.</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.html"><code>EventEmitter</code></a> and <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><!--type=class-->
<h5>Event: 'close'<span><a class="mark" href="#stream_event_close_1" id="stream_event_close_1">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</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>Not all <a href="#stream_class_stream_readable">Readable</a> streams will emit the <code>'close'</code> event.</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.html#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> | <span class="type"><any></span> 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="lang-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="lang-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 Readable 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">
<span>Added in: v0.9.4</span>
</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="lang-javascript">const readable = getReadableStreamSomehow();
readable.on('readable', () => {
// there is some data to read now
});
</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="lang-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="lang-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>
<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
Readable. 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="lang-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="lang-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>
<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.html#stream_class_stream_writable" class="type"><stream.Writable></a> The destination for writing data</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a> Pipe options<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. Defaults to <code>true</code>.</li>
</ul>
</li>
</ul>
<p>The <code>readable.pipe()</code> method attaches a <a href="#stream_class_stream_writable">Writable</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">Writable</a>. The flow of data will be automatically managed so
that the destination Writable stream is not overwhelmed by a faster Readable
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="lang-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 Writable streams to a single Readable 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="lang-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 Writable
stream when the source Readable 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,
as illustrated in the following example:</p>
<pre><code class="lang-js">reader.pipe(writer, { end: false });
reader.on('end', () => {
writer.end('Goodbye\n');
});
</code></pre>
<p>One important caveat is that if the Readable stream emits an error during
processing, the Writable 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.html#process_process_stderr"><code>process.stderr</code></a> and <a href="process.html#process_process_stdout"><code>process.stdout</code></a> Writable streams are never
closed until the Node.js process exits, regardless of the specified options.</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><p>Return the value of <code>highWaterMark</code> passed when constructing this
<code>Readable</code>.</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>Return <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> | <a href="buffer.html#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></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>readable.read()</code> method should only be called on Readable 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="lang-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>A Readable 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.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><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">
<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.resume()</code> method causes an explicitly paused Readable 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 as illustrated in the
following example:</p>
<pre><code class="lang-js">getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
</code></pre>
<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 Readable 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 Readable 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="lang-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.html#stream_class_stream_writable" class="type"><stream.Writable></a> Optional specific stream to unpipe</li>
</ul>
<p>The <code>readable.unpipe()</code> method detaches a Writable 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="lang-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>
<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>
</table>
</details>
</div><ul>
<li><code>chunk</code> <a href="buffer.html#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> | <span class="type"><any></span> 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">Transform</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="lang-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.html#stream_stream" class="type"><Stream></a> An "old style" readable stream</li>
</ul>
<p>Versions of Node.js prior to v0.10 had streams that 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">Readable</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="lang-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.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><p>Destroy the stream, and emit <code>'error'</code>. After this call, the
readable stream will 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>.</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>
<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>
</table>
</details>
</div><!--type=class-->
<p>Duplex streams are streams that implement both the <a href="#stream_class_stream_readable">Readable</a> and
<a href="#stream_class_stream_writable">Writable</a> interfaces.</p>
<p>Examples of Duplex streams include:</p>
<ul>
<li><a href="net.html#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><!--type=class-->
<p>Transform streams are <a href="#stream_class_stream_duplex">Duplex</a> streams where the output is in some way
related to the input. Like all <a href="#stream_class_stream_duplex">Duplex</a> streams, Transform streams
implement both the <a href="#stream_class_stream_readable">Readable</a> and <a href="#stream_class_stream_writable">Writable</a> interfaces.</p>
<p>Examples of Transform 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><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>
<h2>API for Stream Implementers<span><a class="mark" href="#stream_api_for_stream_implementers" id="stream_api_for_stream_implementers">#</a></span></h2>
<!--type=misc-->
<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>
<pre><code class="lang-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>
<p>Use-case</p>
</th>
<th>
<p>Class</p>
</th>
<th>
<p>Method(s) to implement</p>
</th>
</tr>
</thead>
<tr>
<td>
<p>Reading only</p>
</td>
<td>
<p><a href="#stream_class_stream_readable">Readable</a></p>
</td>
<td>
<p><code><a href="#stream_readable_read_size_1">_read</a></code></p>
</td>
</tr>
<tr>
<td>
<p>Writing only</p>
</td>
<td>
<p><a href="#stream_class_stream_writable">Writable</a></p>
</td>
<td>
<p>
<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>
</p>
</td>
</tr>
<tr>
<td>
<p>Reading and writing</p>
</td>
<td>
<p><a href="#stream_class_stream_duplex">Duplex</a></p>
</td>
<td>
<p>
<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>
</p>
</td>
</tr>
<tr>
<td>
<p>Operate on written data, then read the result</p>
</td>
<td>
<p><a href="#stream_class_stream_transform">Transform</a></p>
</td>
<td>
<p>
<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>
</p>
</td>
</tr>
</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="lang-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">Writable</a> stream.</p>
<p>Custom Writable 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(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#stream_constructor_new_stream_writable_options" id="stream_constructor_new_stream_writable_options">#</a></span></h4>
<div class="signature"><ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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>. Defaults to
<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 or not to decode strings into
Buffers before passing them to <a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write()</code></a>.
Defaults to <code>true</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.
Defaults to <code>false</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>
</ul>
</li>
</ul>
</div><pre><code class="lang-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="lang-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="lang-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>
<div class="signature"><ul>
<li><code>chunk</code> <a href="buffer.html#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> | <span class="type"><any></span> The chunk to be written. Will <strong>always</strong>
be a buffer unless the <code>decodeStrings</code> option was set to <code>false</code>
or the stream is operating in object mode.</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>
</div><p>All Writable 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">Transform</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 Writable 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 set in the constructor options, then
<code>chunk</code> may be a string rather than a Buffer, and <code>encoding</code> will
indicate the character encoding of the string. This is to support
implementations that have an optimized handling for certain string
data encodings. If the <code>decodeStrings</code> property is explicitly set to <code>false</code>,
the <code>encoding</code> argument can be safely ignored, and <code>chunk</code> will remain the same
object that is passed to <code>.write()</code>.</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>
<div class="signature"><ul>
<li><code>chunks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></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>
</div><p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal Writable 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 Writable
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 Writable. Throwing an Error 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 Readable stream pipes into a Writable stream when Writable emits an
error, the Readable stream will be unpiped.</p>
<pre><code class="lang-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
Writable stream implementation. While this specific Writable 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">Writable</a> stream instance:</p>
<pre><code class="lang-js">const { Writable } = require('stream');
class MyWritable extends Writable {
constructor(options) {
super(options);
// ...
}
_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">Writable</a>.</p>
<pre><code class="lang-js">const { Writable } = require('stream');
const { StringDecoder } = require('string_decoder');
class StringWritable extends Writable {
constructor(options) {
super(options);
const state = this._writableState;
this._decoder = new StringDecoder(state.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">Readable</a> stream.</p>
<p>Custom Readable 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(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#stream_new_stream_readable_options" id="stream_new_stream_readable_options">#</a></span></h4>
<div class="signature"><ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.
Defaults to <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. Defaults to <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 Buffer of size n. Defaults to <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>
</ul>
</li>
</ul>
</div><pre><code class="lang-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="lang-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="lang-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="signature"><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>
</div><p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal Readable class methods
only.</p>
<p>All Readable 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.</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>
<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>
</table>
</details>
</div><ul>
<li><code>chunk</code> <a href="buffer.html#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> | <span class="type"><any></span> 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
Buffer 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 continued 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 Readable 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 Readable 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 Readable instance as illustrated in the following example:</p>
<pre><code class="lang-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 Readable
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 Error 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="lang-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>
<!--type=example-->
<p>The following is a basic example of a Readable stream that emits the numerals
from 1 to 1,000,000 in ascending order, and then ends.</p>
<pre><code class="lang-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">Duplex</a> stream is one that implements both <a href="#stream_class_stream_readable">Readable</a> and <a href="#stream_class_stream_writable">Writable</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">Duplex</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 Duplex 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>
<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>
</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> Passed to both Writable and Readable
constructors. Also has the following fields:<ul>
<li><code>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Defaults to <code>true</code>. If set to <code>false</code>, then
the stream will automatically end the writable side when the
readable side ends.</li>
<li><code>readableObjectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a> Defaults to <code>false</code>. Sets <code>objectMode</code>
for readable side of the stream. Has no effect if <code>objectMode</code>
is <code>true</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> Defaults to <code>false</code>. Sets <code>objectMode</code>
for writable side of the stream. Has no effect if <code>objectMode</code>
is <code>true</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>
<pre><code class="lang-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="lang-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="lang-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 Duplex 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 Duplex stream that buffers
incoming written data via the <a href="#stream_class_stream_writable">Writable</a> interface that is read back out
via the <a href="#stream_class_stream_readable">Readable</a> interface.</p>
<pre><code class="lang-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 Duplex stream is that the Readable and Writable
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 Duplex streams, <code>objectMode</code> can be set exclusively for either the Readable
or Writable side using the <code>readableObjectMode</code> and <code>writableObjectMode</code> options
respectively.</p>
<p>In the following example, for instance, a new Transform stream (which is a
type of <a href="#stream_class_stream_duplex">Duplex</a> stream) is created that has an object mode Writable side
that accepts JavaScript numbers that are converted to hexadecimal strings on
the Readable side.</p>
<pre><code class="lang-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">Transform</a> stream is a <a href="#stream_class_stream_duplex">Duplex</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 Hash 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">Transform</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 Transform 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 Transform streams in that data written to the
stream can cause the Writable side of the stream to become paused if the output
on the Readable side is not consumed.</p>
<h4>new stream.Transform(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#stream_new_stream_transform_options" id="stream_new_stream_transform_options">#</a></span></h4>
<div class="signature"><ul>
<li><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 Writable and Readable
constructors. Also has the following fields:<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>
</div><pre><code class="lang-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="lang-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="lang-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>
<div class="signature"><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>
</div><p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal Readable 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">Transform</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">Readable</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>
<div class="signature"><ul>
<li><code>chunk</code> <a href="buffer.html#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> | <span class="type"><any></span> The chunk to be transformed. Will <strong>always</strong>
be a buffer unless the <code>decodeStrings</code> option was set to <code>false</code>
or the stream is operating in object mode.</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>
</div><p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal Readable class methods
only.</p>
<p>All Transform 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="lang-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">Transform</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>
<!--type=misc-->
<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>
<!--type=misc-->
<p>In versions of Node.js prior to v0.10, the Readable stream interface was
simpler, but also less powerful and less useful.</p>
<ul>
<li>Rather than waiting for calls 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 v0.10, the <a href="#stream_class_stream_readable">Readable</a> class was added. For backwards compatibility
with older Node.js programs, Readable 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="lang-js">// WARNING! BROKEN!
net.createServer((socket) => {
// we add an 'end' method, 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>In versions of Node.js prior to v0.10, the incoming message data would be
simply discarded. However, in Node.js v0.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="lang-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 Readable streams switching into flowing mode,
pre-v0.10 style streams can be wrapped in a Readable 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
Readable 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>
<!-- [end-include:stream.md] -->
<!-- [start-include:string_decoder.md] -->
<h1>String Decoder<span><a class="mark" href="#string_decoder_string_decoder" id="string_decoder_string_decoder">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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="lang-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="lang-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="lang-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: new StringDecoder([encoding])<span><a class="mark" href="#string_decoder_class_new_stringdecoder_encoding" id="string_decoder_class_new_stringdecoder_encoding">#</a></span></h2>
<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.
Defaults to <code>'utf8'</code>.</li>
</ul>
<p>Creates a new <code>StringDecoder</code> instance.</p>
<h3>stringDecoder.end(<a href="buffer.html#buffer_buffer">buffer</a>)<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.html#buffer_class_buffer" class="type"><Buffer></a> A <code>Buffer</code> containing the bytes to decode.</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>
<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>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> A <code>Buffer</code> containing the bytes to decode.</li>
</ul>
<p>Returns a decoded string, ensuring that any incomplete multibyte characters at
the end of the <code>Buffer</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>
<!-- [end-include:string_decoder.md] -->
<!-- [start-include:timers.md] -->
<h1>Timers<span><a class="mark" href="#timers_timers" id="timers_timers">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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.html#timers_setimmediate_callback_args"><code>setImmediate()</code></a>. It
can be passed to <a href="timers.html#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.html#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><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'd", making it normally unnecessary
to call <code>immediate.ref()</code> unless <code>immediate.unref()</code> had been called previously.</p>
<p>Returns a reference to the <code>Immediate</code>.</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><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>
<p>Returns a reference to the <code>Immediate</code>.</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.html#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a> and
<a href="timers.html#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>. It can be passed to <a href="timers.html#timers_cleartimeout_timeout"><code>clearTimeout()</code></a> or
<a href="timers.html#timers_clearinterval_timeout"><code>clearInterval()</code></a> (respectively) in order to cancel the scheduled actions.</p>
<p>By default, when a timer is scheduled using either <a href="timers.html#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a> or
<a href="timers.html#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><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'd", making it normally unnecessary
to call <code>timeout.ref()</code> unless <code>timeout.unref()</code> had been called previously.</p>
<p>Returns a reference to the <code>Timeout</code>.</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><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>
<p>Returns a reference to the <code>Timeout</code>.</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> <span class="type"><any></span> Optional arguments to pass when the <code>callback</code> is called.</li>
</ul>
<p>Schedules the "immediate" execution of the <code>callback</code> after I/O events'
callbacks. Returns an <code>Immediate</code> for use with <a href="timers.html#timers_clearimmediate_immediate"><code>clearImmediate()</code></a>.</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.html#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="lang-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> <span class="type"><any></span> Optional arguments to pass when the <code>callback</code> is called.</li>
</ul>
<p>Schedules repeated execution of <code>callback</code> every <code>delay</code> milliseconds.
Returns a <code>Timeout</code> for use with <a href="timers.html#timers_clearinterval_timeout"><code>clearInterval()</code></a>.</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.html#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> <span class="type"><any></span> Optional arguments to pass when the <code>callback</code> is called.</li>
</ul>
<p>Schedules execution of a one-time <code>callback</code> after <code>delay</code> milliseconds.
Returns a <code>Timeout</code> for use with <a href="timers.html#timers_cleartimeout_timeout"><code>clearTimeout()</code></a>.</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.html#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="lang-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.html#timers_setimmediate_callback_args"><code>setImmediate()</code></a>, <a href="timers.html#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>, and <a href="timers.html#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.html#timers_setimmediate_callback_args"><code>setImmediate()</code></a>, <a href="timers.html#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.html#timers_class_immediate" class="type"><Immediate></a> An <code>Immediate</code> object as returned by
<a href="timers.html#timers_setimmediate_callback_args"><code>setImmediate()</code></a>.</li>
</ul>
<p>Cancels an <code>Immediate</code> object created by <a href="timers.html#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.html#timers_class_timeout" class="type"><Timeout></a> A <code>Timeout</code> object as returned by <a href="timers.html#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>.</li>
</ul>
<p>Cancels a <code>Timeout</code> object created by <a href="timers.html#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.html#timers_class_timeout" class="type"><Timeout></a> A <code>Timeout</code> object as returned by <a href="timers.html#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a>.</li>
</ul>
<p>Cancels a <code>Timeout</code> object created by <a href="timers.html#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a>.</p>
<!-- [end-include:timers.md] -->
<!-- [start-include:tls.md] -->
<h1>TLS (SSL)<span><a class="mark" href="#tls_tls_ssl" id="tls_tls_ssl">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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="lang-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="lang-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="lang-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="lang-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="lang-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>
<!-- type=misc -->
<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="lang-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, NPN, and SNI<span><a class="mark" href="#tls_alpn_npn_and_sni" id="tls_alpn_npn_and_sni">#</a></span></h3>
<!-- type=misc -->
<p>ALPN (Application-Layer Protocol Negotiation Extension), NPN (Next
Protocol Negotiation) and, SNI (Server Name Indication) are TLS
handshake extensions:</p>
<ul>
<li>ALPN/NPN - Allows the use of one TLS server for multiple protocols (HTTP,
SPDY, HTTP/2)</li>
<li>SNI - Allows the use of one TLS server for multiple hostnames with different
SSL certificates.</li>
</ul>
<p>Use of ALPN is recommended over NPN. The NPN extension has never been
formally defined or documented and generally not recommended for use.</p>
<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>
<!-- type=misc -->
<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. Defaults to <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. Defaults to <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>
<p>To test the renegotiation limits on a server, connect to it using the OpenSSL
command-line client (<code>openssl s_client -connect address:port</code>) then input
<code>R<CR></code> (i.e., the letter <code>R</code> followed by a carriage return) multiple times.</p>
<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="lang-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 <code>--tls-cipher-list</code> command
line switch. For instance, the following makes
<code>ECDHE-RSA-AES128-GCM-SHA256:!RC4</code> the default TLS cipher suite:</p>
<pre><code class="lang-sh">node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4"
</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.0.2/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.0.2/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: '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 listener callback is passed
three arguments when called:</p>
<ul>
<li><code>sessionId</code> - The TLS session identifier</li>
<li><code>sessionData</code> - 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.html#buffer_class_buffer" class="type"><Buffer></a> The server certificate</li>
<li><code>issuer</code> <a href="buffer.html#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://npmjs.org/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> - The TLS/SSL session identifier</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 to be called when the prior session
has been recovered.</li>
</ul>
<p>When called, the event listener may perform a lookup in external storage using
the given <code>sessionId</code> and invoke <code>callback(null, sessionData)</code> once finished. If
the session cannot be resumed (i.e., doesn't exist in storage) the callback may
be invoked as <code>callback(null, null)</code>. Calling <code>callback(err)</code> will 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="lang-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.html#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.npnProtocol</code> and <code>tlsSocket.alpnProtocol</code> properties are strings
that contain the selected NPN and ALPN protocols, respectively. When both NPN
and ALPN extensions are received, ALPN takes precedence over NPN and the next
protocol is selected by ALPN.</p>
<p>When ALPN has no selected protocol, <code>tlsSocket.alpnProtocol</code> returns <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.html#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 hostname matches the supplied <code>hostname</code> (or wildcard).</p>
<h3>server.address()<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><p>Returns the bound address, the address family name, and port of the
server as reported by the operating system. See <a href="net.html#net_server_address"><code>net.Server.address()</code></a> for
more information.</p>
<h3>server.close([callback])<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> An optional listener callback that will be registered to
listen for the server instance's <code>'close'</code> event.</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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="net.html#net_server_getconnections_callback"><code>server.getConnections()</code></a> instead.</div><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><p>Returns a <code>Buffer</code> instance holding the keys currently used for
encryption/decryption of the <a href="https://www.ietf.org/rfc/rfc5077.txt">TLS Session Tickets</a></p>
<h3>server.listen()<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.html#net_server_listen"><code>server.listen()</code></a> from <a href="net.html#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.html#buffer_class_buffer" class="type"><Buffer></a> The keys used for encryption/decryption of the
<a href="https://www.ietf.org/rfc/rfc5077.txt">TLS Session Tickets</a>.</li>
</ul>
<p>Updates the keys for encryption/decryption of the <a href="https://www.ietf.org/rfc/rfc5077.txt">TLS Session Tickets</a>.</p>
<p>The key's <code>Buffer</code> should be 48 bytes long. See <code>ticketKeys</code> option in
<a href="#tls_tls_createserver_options_secureconnectionlistener">tls.createServer</a> for
more information on how it is used.</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>
<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.html#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.html#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>
<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>
</table>
</details>
</div><ul>
<li><code>socket</code> <a href="net.html#net_class_net_socket" class="type"><net.Socket></a> | <a href="stream.html#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.html#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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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. Defaults to <code>false</code>.</li>
<li><code>server</code> <a href="net.html#net_class_net_server" class="type"><net.Server></a> An optional <a href="net.html#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 optionally set <code>requestCert</code> to true to request a
client certificate.</li>
<li><code>rejectUnauthorized</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>NPNProtocols</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>ALPNProtocols</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>SNICallback</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>session</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> An optional <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>: Optional 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>...: Optional <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: '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.html#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 either ALPN or NPN was used,
the <code>tlsSocket.alpnProtocol</code> or <code>tlsSocket.npnProtocol</code> properties 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><p>Returns the bound address, the address family name, and port of the
underlying socket as reported by the operating system. Returns an
object with three properties, e.g.
<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><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><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.0.2/ssl/SSL_CIPHER_get_name.html">https://www.openssl.org/docs/man1.0.2/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><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 'ECDH'.</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.html#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>
</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 a
<code>issuerCertificate</code> property containing an object representing its issuer's
certificate.</p>
<p>For example:</p>
<pre><code class="lang-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 a .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.html#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><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>Example responses include:</p>
<ul>
<li><code>SSLv3</code></li>
<li><code>TLSv1</code></li>
<li><code>TLSv1.1</code></li>
<li><code>TLSv1.2</code></li>
<li><code>unknown</code></li>
</ul>
<p>See <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html">https://www.openssl.org/docs/man1.0.2/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><p>Returns the ASN.1 encoded TLS session or <code>undefined</code> if no session was
negotiated. Can be used to speed up handshake establishment when reconnecting
to the server.</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><p>Returns the TLS session ticket or <code>undefined</code> if no session was negotiated.</p>
<p>This only works with client TLS sockets. Useful only for debugging, for session
reuse provide <code>session</code> option to <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>.</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><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><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><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><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><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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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. Defaults to
<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. Defaults to <code>16384</code>. The
maximum value is <code>16384</code>.</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(host, cert)<span><a class="mark" href="#tls_tls_checkserveridentity_host_cert" id="tls_tls_checkserveridentity_host_cert">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.8.4</span>
</div><ul>
<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 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>
</ul>
<p>Verifies the certificate <code>cert</code> is issued to host <code>host</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 the reason, host, and cert 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="lang-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>
<tr><th>Version</th><th>Changes</th></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> and <code>NPNProtocols</code> options can be <code>Uint8Array</code>s 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>
</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><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, defaults to 'localhost'.</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.html#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.html#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. Defaults to
<code>true</code>.</li>
<li><code>NPNProtocols</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="buffer.html#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.html#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 supported NPN 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>.</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.html#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.html#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>.</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.</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.html#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.
Defaults to <code>1024</code>.</li>
<li><code>secureContext</code>: Optional 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. Defaults to <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li>
<li>...: Optional <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>
</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 implements a simple "echo server" example:</p>
<pre><code class="lang-js">const tls = require('tls');
const fs = require('fs');
const options = {
// Necessary only if using the client certificate authentication
key: fs.readFileSync('client-key.pem'),
cert: fs.readFileSync('client-cert.pem'),
// Necessary only if the server uses the self-signed certificate
ca: [ fs.readFileSync('server-cert.pem') ]
};
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', () => {
server.close();
});
</code></pre>
<p>Or</p>
<pre><code class="lang-js">const tls = require('tls');
const fs = require('fs');
const options = {
pfx: fs.readFileSync('client.pfx')
};
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', () => {
server.close();
});
</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>
</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> Optional 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>
</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>
<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>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. Array 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>
</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><ul>
<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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="buffer.html#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> Optional 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>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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="buffer.html#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> Optional 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>passphrase</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optional shared passphrase used for a single private
key and/or a PFX.</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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer[]></a> Optional 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>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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="buffer.html#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 Buffer, or an Array of
strings and/or Buffers. Any string or Buffer 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.</li>
<li><code>ciphers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optional 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>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.html#crypto_openssl_options">OpenSSL Options</a> for more information.</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, or <code>false</code> to disable ECDH. Set to <code>auto</code> to select the
curve automatically. Defaults to <a href="#tls_tls_default_ecdh_curve"><code>tls.DEFAULT_ECDH_CURVE</code></a>. Use
<a href="crypto.html#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.</li>
<li><code>clientCertEngine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optional 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.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer[]></a> Optional 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.html#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>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.html#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> Optional SSL method to use, default is
<code>"SSLv23_method"</code>. The possible values are listed as <a href="https://www.openssl.org/docs/man1.0.2/ssl/ssl.html#DEALING-WITH-PROTOCOL-METHODS">SSL_METHODS</a>, use
the function names as strings. For example, <code>"SSLv3_method"</code> to force SSL
version 3.</li>
<li><code>sessionIdContext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optional 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>
<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> and <code>NPNProtocols</code> options can be <code>Uint8Array</code>s 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>
</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><ul>
<li><code>clientCertEngine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a> Optional 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. Defaults to
<code>120000</code> (120 seconds). A <code>'tlsClientError'</code> is emitted on the <code>tls.Server</code>
object whenever a handshake times out.</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. Defaults to
<code>false</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> 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>. Defaults to <code>true</code>.</li>
<li><code>NPNProtocols</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="buffer.html#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.html#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 supported NPN 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>ALPNProtocols</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a> | <a href="buffer.html#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.html#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.)
When the server receives both NPN and ALPN extensions from the client,
ALPN takes precedence over NPN and the server does not send an NPN
extension to the client.</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 SecureContext instance. (<code>tls.createSecureContext(...)</code> can
be used to get a proper SecureContext.) If <code>SNICallback</code> wasn't provided the
default callback with high-level API will be used (see below).</li>
<li><code>sessionTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> An integer specifying the number of seconds after
which the TLS session identifiers and TLS session tickets created by the
server will time out. See <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_timeout.html">SSL_CTX_set_timeout</a> for more details.</li>
<li><code>ticketKeys</code>: A 48-byte <code>Buffer</code> instance consisting of a 16-byte prefix,
a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS
session tickets on multiple instances of the TLS server.</li>
<li>...: Any <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</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>
</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>
</ul>
<p>Creates a new <a href="#tls_class_tls_server">tls.Server</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="lang-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 the client certificate authentication.
requestCert: true,
// This is necessary only if the client uses the 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>Or</p>
<pre><code class="lang-js">const tls = require('tls');
const fs = require('fs');
const options = {
pfx: fs.readFileSync('server.pfx'),
// This is necessary only if using the client certificate authentication.
requestCert: true,
};
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>This server can be tested by connecting to it using <code>openssl s_client</code>:</p>
<pre><code class="lang-sh">openssl s_client -connect 127.0.0.1:8000
</code></pre>
<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><p>Returns an array with the names of the supported SSL ciphers.</p>
<p>For example:</p>
<pre><code class="lang-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">
<span>Added in: v0.11.13</span>
</div><p>The default curve name to use for ECDH key agreement in a tls server. The
default value is <code>'prime256v1'</code> (NIST P-256). Consult <a href="https://www.rfc-editor.org/rfc/rfc4492.txt">RFC 4492</a> and
<a href="http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf">FIPS.186-4</a> for more details.</p>
<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</div><p>The <code>tls.CryptoStream</code> class represents a stream of encrypted data. This class
has been 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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</div><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>
<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>
</table>
</details>
</div><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</div><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><code>options</code><ul>
<li><code>secureContext</code>: An optional 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.
Defaults to <code>false</code>.</li>
<li><code>server</code> <a href="net.html#net_class_net_server" class="type"><net.Server></a> An optional <a href="net.html#net_class_net_server"><code>net.Server</code></a> instance</li>
<li><code>requestCert</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>rejectUnauthorized</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>NPNProtocols</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>ALPNProtocols</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>SNICallback</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>session</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> An optional <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="lang-js">pair = tls.createSecurePair(/* ... */);
pair.encrypted.pipe(socket);
socket.pipe(pair.encrypted);
</code></pre>
<p>can be replaced by:</p>
<pre><code class="lang-js">secure_socket = tls.TLSSocket(socket, options);
</code></pre>
<p>where <code>secure_socket</code> has the same API as <code>pair.cleartext</code>.</p>
<!-- [end-include:tls.md] -->
<!-- [start-include:tracing.md] -->
<h1>Tracing<span><a class="mark" href="#tracing_tracing" id="tracing_tracing">#</a></span></h1>
<!--introduced_in=v7.7.0-->
<p>Trace Event provides a mechanism to centralize tracing information generated by
V8, Node core, and userspace code.</p>
<p>Tracing can be enabled by passing the <code>--trace-events-enabled</code> flag when
starting a Node.js application.</p>
<p>The set of categories for which traces are recorded can be specified using the
<code>--trace-event-categories</code> flag followed by a list of comma separated category
names. By default the <code>node</code>, <code>node.async_hooks</code>, and <code>v8</code> categories are
enabled.</p>
<pre><code class="lang-txt">node --trace-events-enabled --trace-event-categories v8,node,node.async_hooks server.js
</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>. For example:</p>
<pre><code class="lang-txt">node --trace-events-enabled --trace-event-file-pattern '${pid}-${rotation}.log' server.js
</code></pre>
<p>Starting with Node 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>
<!-- [end-include:tracing.md] -->
<!-- [start-include:tty.md] -->
<h1>TTY<span><a class="mark" href="#tty_tty" id="tty_tty">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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="lang-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.html#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.html#process_process_stdout"><code>process.stdout</code></a> and <a href="process.html#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="lang-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<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.html#net_class_net_socket"><code>net.Socket</code></a> that represents the
readable side of a TTY. In normal circumstances <a href="process.html#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><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>
<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>
</ul>
<h2>Class: tty.WriteStream<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 <code>net.Socket</code> that represents the
writable side of a TTY. In normal circumstances, <a href="process.html#process_process_stdout"><code>process.stdout</code></a> and
<a href="process.html#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="lang-js">process.stdout.on('resize', () => {
console.log('screen size has changed!');
console.log(`${process.stdout.columns}x${process.stdout.rows}`);
});
</code></pre>
<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.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.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>
<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> <span class="type"><object></span> A object containing the environment variables to check.
Defaults to <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>1 for 2,</li>
<li>4 for 16,</li>
<li>8 for 256,</li>
<li>24 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>
<h2>tty.isatty(fd)<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>
<!-- [end-include:tty.md] -->
<!-- [start-include:dgram.md] -->
<h1>UDP / Datagram Sockets<span><a class="mark" href="#dgram_udp_datagram_sockets" id="dgram_udp_datagram_sockets">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><!-- name=dgram -->
<p>The <code>dgram</code> module provides an implementation of UDP Datagram sockets.</p>
<pre><code class="lang-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<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 Error 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.html#buffer_class_buffer" class="type"><Buffer></a> The message.</li>
<li><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.<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])<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>
<h3>socket.address()<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><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])<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"><number></a> Integer.</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.html#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="lang-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])<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><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:<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.html#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="lang-js">socket.bind({
address: 'localhost',
port: 8000,
exclusive: true
});
</code></pre>
<h3>socket.close([callback])<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><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])<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()<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()<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()<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])<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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>msg</code> parameter can be an Uint8Array 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>
</table>
</details>
</div><ul>
<li><code>msg</code> <a href="buffer.html#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"><number></a> Integer. 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"><number></a> Integer. 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"><number></a> Integer. 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.html#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="lang-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="lang-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)<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)<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>Note: 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="lang-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="lang-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="lang-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.html#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.html#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.html#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)<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)<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"><number></a> Integer.</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)<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"><number></a> Integer</li>
</ul>
<p>Sets the <code>SO_RCVBUF</code> socket option. Sets the maximum socket receive buffer
in bytes.</p>
<h3>socket.setSendBufferSize(size)<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"><number></a> Integer</li>
</ul>
<p>Sets the <code>SO_SNDBUF</code> socket option. Sets the maximum socket send buffer
in bytes.</p>
<h3>socket.setTTL(ttl)<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"><number></a> Integer.</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()<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 that assumes synchronous behavior, as in the
following example:</p>
<pre><code class="lang-js">const s = dgram.createSocket('udp4');
s.bind(1234);
s.addMembership('224.0.0.114');
</code></pre>
<p>Must 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="lang-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])<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>
<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>
</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> Available options are:<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.
Defaults to <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. Defaults to <a href="dns.html#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.html#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])<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 'udp4' or 'udp6'.</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.html#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>
<!-- [end-include:dgram.md] -->
<!-- [start-include:url.md] -->
<h1>URL<span><a class="mark" href="#url_url" id="url_url">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p>The <code>url</code> module provides utilities for URL resolution and parsing. It can be
accessed using:</p>
<pre><code class="lang-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.host.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="lang-txt">┌─────────────────────────────────────────────────────────────────────────────────────────────â”
│ href │
├──────────┬──┬─────────────────────┬─────────────────────┬───────────────────────────┬───────┤
│ protocol │ │ auth │ host │ path │ hash │
│ │ │ ├──────────────┬──────┼──────────┬────────────────┤ │
│ │ │ │ hostname │ port │ pathname │ search │ │
│ │ │ │ │ │ ├─┬──────────────┤ │
│ │ │ │ │ │ │ │ query │ │
" https: // user : pass @ sub.host.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="lang-js">const { URL } = require('url');
const myURL =
new URL('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash');
</code></pre>
<p><em>Note</em>: In Web Browsers, the WHATWG <code>URL</code> class is a global that is always
available. In Node.js, however, the <code>URL</code> class must be accessed via
<code>require('url').URL</code>.</p>
<p>Parsing the URL string using the Legacy API:</p>
<pre><code class="lang-js">const url = require('url');
const myURL =
url.parse('https://user:pass@sub.host.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>
<div class="api_metadata">
<span>Added in: v7.0.0</span>
</div><h3>Class: URL<span><a class="mark" href="#url_class_url" id="url_class_url">#</a></span></h3>
<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.</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 urlObject</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>
<div class="signature"><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 input URL to parse</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.html#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>
</div><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="lang-js">const { URL } = require('url');
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="lang-js">const { URL } = require('url');
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="lang-js">const { URL } = require('url');
const myURL = new URL('https://ä½ å¥½ä½ å¥½');
// https://xn--6qqa088eba/
</code></pre>
<p>This feature is only available if the <code>node</code> executable was compiled with
<a href="intl.html#intl_options_for_building_node_js">ICU</a> enabled. If not, the domain names are passed through unchanged.</p>
<h4>url.hash<span><a class="mark" href="#url_url_hash" id="url_url_hash">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>Gets and sets the fragment portion of the URL.</p>
<pre><code class="lang-js">const { URL } = require('url');
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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>Gets and sets the host portion of the URL.</p>
<pre><code class="lang-js">const { URL } = require('url');
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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><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="lang-js">const { URL } = require('url');
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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>Gets and sets the serialized URL.</p>
<pre><code class="lang-js">const { URL } = require('url');
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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>Gets the read-only serialization of the URL's origin.</p>
<pre><code class="lang-js">const { URL } = require('url');
const myURL = new URL('https://example.org/foo/bar?baz');
console.log(myURL.origin);
// Prints https://example.org
</code></pre>
<pre><code class="lang-js">const { URL } = require('url');
const idnURL = new URL('https://ä½ å¥½ä½ å¥½');
console.log(idnURL.origin);
// Prints https://xn--6qqa088eba
console.log(idnURL.hostname);
// Prints xn--6qqa088eba
</code></pre>
<h4>url.password<span><a class="mark" href="#url_url_password" id="url_url_password">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>Gets and sets the password portion of the URL.</p>
<pre><code class="lang-js">const { URL } = require('url');
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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>Gets and sets the path portion of the URL.</p>
<pre><code class="lang-js">const { URL } = require('url');
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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>Gets and sets the port portion of the URL.</p>
<pre><code class="lang-js">const { URL } = require('url');
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 are ignored
myURL.port = 1e10;
console.log(myURL.port);
// Prints 1234
</code></pre>
<p>The port value may be set as either a number or as 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>If an invalid string is assigned to the <code>port</code> property, but it begins with a
number, the leading number is assigned to <code>port</code>. Otherwise, or if the number
lies outside the range denoted above, it is ignored.</p>
<h4>url.protocol<span><a class="mark" href="#url_url_protocol" id="url_url_protocol">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>Gets and sets the protocol portion of the URL.</p>
<pre><code class="lang-js">const { URL } = require('url');
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>
<h4>url.search<span><a class="mark" href="#url_url_search" id="url_url_search">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>Gets and sets the serialized query portion of the URL.</p>
<pre><code class="lang-js">const { URL } = require('url');
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>
<div class="signature"><ul>
<li><a href="url.html#url_class_urlsearchparams" class="type"><URLSearchParams></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>Gets and sets the username portion of the URL.</p>
<pre><code class="lang-js">const { URL } = require('url');
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>
<div class="signature"><ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><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="lang-js">const { URL } = require('url');
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">
<span>Added in: v7.5.0</span>
</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.</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="lang-js">const { URL, URLSearchParams } = require('url');
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>
<div class="signature"><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>
</div><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="lang-js">const { URLSearchParams } = require('url');
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</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="lang-js">const { URLSearchParams } = require('url');
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</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 Array 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="lang-js">const { URLSearchParams } = require('url');
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>
<div class="signature"><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>
</div><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>
<div class="signature"><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>
</div><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>
<div class="signature"><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>
</div><p>Returns an ES6 Iterator over each of the name-value pairs in the query.
Each item of the iterator is a JavaScript Array. The first item of the Array
is the <code>name</code>, the second item of the Array is the <code>value</code>.</p>
<p>Alias for <a href="#url_urlsearchparams_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>
<div class="signature"><ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a> Function 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> Object to be used as <code>this</code> value for when <code>fn</code> is called</li>
</ul>
</div><p>Iterates over each name-value pair in the query and invokes the given function.</p>
<pre><code class="lang-js">const { URL } = require('url');
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>
<div class="signature"><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>
</div><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>
<div class="signature"><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/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
</div><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>
<div class="signature"><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>
</div><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>
<div class="signature"><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>
</div><p>Returns an ES6 Iterator over the names of each name-value pair.</p>
<pre><code class="lang-js">const { URLSearchParams } = require('url');
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>
<div class="signature"><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>
</div><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="lang-js">const { URLSearchParams } = require('url');
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</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="lang-js">const { URLSearchParams } = require('url');
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>
<div class="signature"><ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><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>
<div class="signature"><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>
</div><p>Returns an ES6 Iterator over the values of each name-value pair.</p>
<h4>urlSearchParams[@@iterator]()<span><a class="mark" href="#url_urlsearchparams_iterator" id="url_urlsearchparams_iterator">#</a></span></h4>
<div class="signature"><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>
</div><p>Returns an ES6 Iterator over each of the name-value pairs in the query string.
Each item of the iterator is a JavaScript Array. The first item of the Array
is the <code>name</code>, the second item of the Array is the <code>value</code>.</p>
<p>Alias for <a href="#url_urlsearchparams_entries"><code>urlSearchParams.entries()</code></a>.</p>
<pre><code class="lang-js">const { URLSearchParams } = require('url');
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</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="lang-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</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="lang-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.format(URL[, options])<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.html#url_the_whatwg_url_api" class="type"><URL></a> A <a href="#url_the_whatwg_url_api">WHATWG URL</a> object</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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. Defaults to <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. Defaults to <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. Defaults to <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. Defaults to <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Returns a customizable serialization of a URL String 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>
<p>For example:</p>
<pre><code class="lang-js">const { URL } = require('url');
const myURL = new URL('https://a:b@ä½ å¥½ä½ å¥½?abc#foo');
console.log(myURL.href);
// Prints https://a:b@xn--6qqa088eba/?abc#foo
console.log(myURL.toString());
// Prints https://a:b@xn--6qqa088eba/?abc#foo
console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://ä½ å¥½ä½ å¥½/?abc'
</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 urlObject<span><a class="mark" href="#url_legacy_urlobject" id="url_legacy_urlobject">#</a></span></h3>
<p>The legacy urlObject (<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 "userinfo". This string subset follows the <code>protocol</code> and
double slashes (if present) and precedes the <code>host</code> component, delimited by an
ASCII "at sign" (<code>@</code>). The format of the string is <code>{username}[:{password}]</code>,
with the <code>[:{password}]</code> portion being optional.</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 consists of the "fragment" portion of the URL including
the leading ASCII hash (<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.host.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.host.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.host.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)<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>
<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>
</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="lang-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.html#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.html#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>If either of the following conditions is true, then the literal string <code>//</code>
will be appended to <code>result</code>:<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>If the <code>urlObject.host</code> property is <code>undefined</code> then:<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.html#errors_class_error"><code>Error</code></a> is thrown.</li>
<li>If the <code>urlObject.port</code> property value is truthy, and <code>urlObject.hostname</code>
is not <code>undefined</code>:<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>If the <code>urlObject.pathname</code> property is a string that is not an empty string:<ul>
<li>If the <code>urlObject.pathname</code> <em>does not start</em> with an ASCII forward slash
(<code>/</code>), then the literal string '/' 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.html#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>Otherwise, if <code>urlObject.search</code> is a string:<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.html#errors_class_error"><code>Error</code></a> is thrown.</li>
<li>If the <code>urlObject.hash</code> property is a string:<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.html#errors_class_error"><code>Error</code></a> is thrown.</li>
<li><code>result</code> is returned.</li>
</ul>
<h3>url.parse(urlString[, parseQueryString[, slashesDenoteHost]])<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>
<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>
</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. Defaults to <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>.
Defaults to <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)<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>
<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>
</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>
<p>For example:</p>
<pre><code class="lang-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="lang-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. For example:</p>
<pre><code class="lang-js">const { URL } = require('url');
const myURL = new URL('https://%CF%80.com/foo');
console.log(myURL.href);
// Prints https://xn--1xa.com/foo
console.log(myURL.origin);
// Prints https://Ï€.com
</code></pre>
<!-- [end-include:url.md] -->
<!-- [start-include:util.md] -->
<h1>Util<span><a class="mark" href="#util_util" id="util_util">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><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="lang-js">const util = require('util');
</code></pre>
<h2>util.callbackify(original)<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 Promise) and returns a
function following the error-first callback style, i.e. taking
a <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 Promise
resolved), and the second argument will be the resolved value.</p>
<pre><code class="lang-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="lang-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.html#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="lang-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)<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.html#console_console_error_data_args"><code>console.error()</code></a>. If not, then the returned function is a no-op.</p>
<pre><code class="lang-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="lang-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="lang-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="lang-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(function, string)<span><a class="mark" href="#util_util_deprecate_function_string" id="util_util_deprecate_function_string">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.8.0</span>
</div><p>The <code>util.deprecate()</code> method wraps the given <code>function</code> or class in such a way
that it is marked as deprecated.</p>
<!-- eslint-disable prefer-rest-params -->
<pre><code class="lang-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 <code>process.on('warning')</code> event. By default,
this warning will be emitted and printed to <code>stderr</code> exactly once, the first
time it is called. After the warning is emitted, the wrapped <code>function</code>
is called.</p>
<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])<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>
<tr><th>Version</th><th>Changes</th></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>
</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> - String.</li>
<li><code>%d</code> - Number (integer or floating point value).</li>
<li><code>%i</code> - Integer.</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> - Object. A string representation of an object
with generic JavaScript object formatting.
Similar to <code>util.inspect()</code> with options <code>{ showHidden: true, depth: 4,
showProxy: true }</code>. This will show the full object including non-enumerable
symbols and properties.</li>
<li><code>%O</code> - Object. 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 symbols and
properties.</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="lang-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="lang-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="lang-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="lang-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.getSystemErrorName(err)<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.html#errors_common_system_errors">Common System Errors</a> for the names of common errors.</p>
<pre><code class="lang-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)<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>
<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>
</table>
</details>
</div><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>
<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>Inherit the prototype methods from one <a href="https://developer.mozilla.org/en/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="lang-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="lang-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>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tr><th>Version</th><th>Changes</th></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>
</table>
</details>
</div><ul>
<li><code>object</code> <span class="type"><any></span> Any JavaScript primitive or Object.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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. Defaults to <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.
Defaults to <code>2</code>. To make it recurse indefinitely pass <code>null</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. Defaults to <code>false</code>. Colors are customizable, see
<a href="#util_customizing_util_inspect_colors">Customizing <code>util.inspect</code> colors</a>.</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. Defaults to <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. Defaults to <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 array and
<code>TypedArray</code> elements to include when formatting. Defaults to <code>100</code>. Set to
<code>null</code> to show all array elements. Set to <code>0</code> or negative to show no array
elements.</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. Defaults to 60 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. Defaults to <code>true</code>.</li>
</ul>
</li>
</ul>
<p>The <code>util.inspect()</code> method returns a string representation of <code>object</code> that is
primarily useful for debugging. Additional <code>options</code> may be passed that alter
certain aspects of the formatted string.</p>
<p>The following example inspects all properties of the <code>util</code> object:</p>
<pre><code class="lang-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="lang-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>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>
<!-- type=misc -->
<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>
<!-- type=misc -->
<p>Objects may also define their own <code>[util.inspect.custom](depth, opts)</code>
(or the equivalent but deprecated <code>inspect(depth, opts)</code>) function that
<code>util.inspect()</code> will invoke and use the result of when inspecting the object:</p>
<pre><code class="lang-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="lang-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">
<span>Added in: v6.6.0</span>
</div><p>A Symbol that can be used to declare custom inspect functions, see
<a href="#util_custom_inspection_functions_on_objects">Custom inspection functions on Objects</a>.</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="lang-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> <span class="type"><any></span></li>
<li><code>val2</code> <span class="type"><any></span></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.html#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
a <code>(err, value) => ...</code> callback as the last argument, and returns a version
that returns promises.</p>
<pre><code class="lang-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="lang-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="lang-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="lang-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 Symbol 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="lang-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>
</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>
<div class="signature"><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. Defaults to <code>'utf-8'</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><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. Defaults to
<code>false</code>. This option is only supported when ICU is enabled (see
<a href="intl.html">Internationalization</a>).</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>. Defaults to <code>false</code>.</li>
</ul>
</li>
</ul>
</div><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>
<div class="signature"><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
Typed Array instance containing the encoded data.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.
Defaults to <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>
</div><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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><boolean></a></li>
</ul>
</div><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="lang-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>
<div class="signature"><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. Defaults to 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>
</div><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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>The encoding supported by the <code>TextEncoder</code> instance. Always set to <code>'utf-8'</code>.</p>
<h2>Deprecated APIs<span><a class="mark" href="#util_deprecated_apis" id="util_deprecated_apis">#</a></span></h2>
<p>The following APIs have been 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><div class="api_stability api_stability_0"><a href="documentation.html#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>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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="console.html#console_console_error_data_args"><code>console.error()</code></a> instead.</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> 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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="console.html#console_console_error_data_args"><code>console.error()</code></a> instead.</div><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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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>Internal 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="lang-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)<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="buffer.html#buffer_class_method_buffer_isbuffer_obj"><code>Buffer.isBuffer()</code></a> instead.</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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.html#errors_class_error"><code>Error</code></a>. Otherwise, returns
<code>false</code>.</p>
<pre><code class="lang-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="lang-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)<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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)<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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)<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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)<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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)<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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>. Otherwise, returns <code>false</code>.</p>
<pre><code class="lang-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)<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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)<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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)<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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)<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated</div><ul>
<li><code>object</code> <span class="type"><any></span></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="lang-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)<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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use a third party module instead.</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>util.log()</code> method prints the given <code>string</code> to <code>stdout</code> with an included
timestamp.</p>
<pre><code class="lang-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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="console.html#console_console_log_data_args"><code>console.log()</code></a> instead.</div><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><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="console.html#console_console_log_data_args"><code>console.log()</code></a> instead.</div><p>Deprecated predecessor of <code>console.log</code>.</p>
<!-- [end-include:util.md] -->
<!-- [start-include:v8.md] -->
<h1>V8<span><a class="mark" href="#v8_v8" id="v8_v8">#</a></span></h1>
<!--introduced_in=v4.0.0-->
<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="lang-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><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.html#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()<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>
<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>
</table>
</details>
</div><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-8.0/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="lang-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()<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>
<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>
</table>
</details>
</div><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="lang-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)<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="lang-js">// Print GC events to stdout for one minute.
const v8 = require('v8');
v8.setFlagsFromString('--trace_gc');
setTimeout(function() { 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>
<div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><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)<span><a class="mark" href="#v8_v8_serialize_value" id="v8_v8_serialize_value">#</a></span></h3>
<!--
added: v8.0.0
-->
<ul>
<li>Returns: <a href="buffer.html#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)<span><a class="mark" href="#v8_v8_deserialize_buffer" id="v8_v8_deserialize_buffer">#</a></span></h3>
<!--
added: v8.0.0
-->
<ul>
<li><code>buffer</code> <a href="buffer.html#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 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>
<!--
added: v8.0.0
-->
<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>
<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>
<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>
<div class="signature"><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>
</div><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>
<div class="signature"><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>
</div><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>
<div class="signature"><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>
</div><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>
<div class="signature"><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>
</div><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>
<div class="signature"><ul>
<li><code>buffer</code> <a href="buffer.html#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>
</ul>
</div><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>
<div class="signature"><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>
</div><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>
<div class="signature"><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>
</div><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.html#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>
<div class="signature"><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>
</div><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>
<div class="signature"><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>
</div><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>
<p>The default is not to treat those objects as host objects.</p>
<h3>class: v8.Deserializer<span><a class="mark" href="#v8_class_v8_deserializer" id="v8_class_v8_deserializer">#</a></span></h3>
<!--
added: v8.0.0
-->
<h4>new Deserializer(buffer)<span><a class="mark" href="#v8_new_deserializer_buffer" id="v8_new_deserializer_buffer">#</a></span></h4>
<div class="signature"><ul>
<li><code>buffer</code> <a href="buffer.html#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 buffer returned by
<a href="#v8_serializer_releasebuffer"><code>serializer.releaseBuffer()</code></a>.</li>
</ul>
</div><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>
<div class="signature"><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>
</div><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>
<div class="signature"><ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a></li>
</ul>
</div><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)<span><a class="mark" href="#v8_deserializer_readrawbytes_length" id="v8_deserializer_readrawbytes_length">#</a></span></h4>
<div class="signature"><ul>
<li>Returns: <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</div><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>
<!--
added: v8.0.0
-->
<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#buffer_class_buffer"><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>
<!--
added: v8.0.0
-->
<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>
<!-- [end-include:v8.md] -->
<!-- [start-include:vm.md] -->
<h1>VM (Executing JavaScript)<span><a class="mark" href="#vm_vm_executing_javascript" id="vm_vm_executing_javascript">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><!--name=vm-->
<p>The <code>vm</code> module provides APIs for compiling and running code within V8 Virtual
Machine contexts.</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 on the sandbox like a
global variable. Any changes on global variables caused by the sandboxed
code are reflected in the sandbox object.</p>
<pre><code class="lang-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>
<p><strong>The vm module is not a security mechanism. Do not use it to run untrusted
code</strong>.</p>
<h2>Class: vm.Module<span><a class="mark" href="#vm_class_vm_module" id="vm_class_vm_module">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
</div><div class="api_stability api_stability_1"><a href="documentation.html#documentation_stability_index">Stability: 1</a> - Experimental</div><p><em>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</em></p>
<p>The <code>vm.Module</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.Module</code> object is bound to a context from
its creation. Operations on <code>vm.Module</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.Module</code> objects is fairly
straightforward.</p>
<p>Using a <code>vm.Module</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.html#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="lang-js">const vm = require('vm');
const contextifiedSandbox = vm.createContext({ secret: 42 });
(async () => {
// Step 1
//
// Create a Module by constructing a new `vm.Module` 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.Module(`
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.Module(`
// 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.Module(code[, options])<span><a class="mark" href="#vm_constructor_new_vm_module_code_options" id="vm_constructor_new_vm_module_code_options">#</a></span></h3>
<div class="signature"><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><code>options</code><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 Module 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 Module.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><integer></a> Spcifies the column number offset that is displayed
in stack traces produced by this Module.</li>
</ul>
</li>
</ul>
</div><p>Creates a new ES <code>Module</code> object.</p>
<h3>module.dependencySpecifiers<span><a class="mark" href="#vm_module_dependencyspecifiers" id="vm_module_dependencyspecifiers">#</a></span></h3>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string[]></a></li>
</ul>
</div><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 [[RequestedModules]] 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>
<div class="signature"><ul>
<li><span class="type"><any></span></li>
</ul>
</div><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 [[EvaluationError]] 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.linkingStatus<span><a class="mark" href="#vm_module_linkingstatus" id="vm_module_linkingstatus">#</a></span></h3>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><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 Promise
that is rejected, or because the Module 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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
</div><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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><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 [[Status]] field. <code>'errored'</code> corresponds to
<code>'evaluated'</code> in the specification, but with [[EvaluationError]] 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>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><string></a></li>
</ul>
</div><p>The URL of the current module, as set in the constructor.</p>
<h3>module.evaluate(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#vm_module_evaluate_options" id="vm_module_evaluate_options">#</a></span></h3>
<div class="signature"><ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><ul>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><number></a> Specifies the number of milliseconds to evaluate
before terminating execution. If execution is interrupted, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</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.html#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>
</div><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>
<div class="signature"><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>
</div><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><code>specifier</code> The specifier of the requested module:<!-- eslint-skip -->
<pre><code class="lang-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>
<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>
<tr><th>Version</th><th>Changes</th></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>
</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><code>options</code><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.html#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"><number></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</li>
<li><code>cachedData</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> Provides an optional <code>Buffer</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.</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.runInContext(contextifiedSandbox[, options])<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>
<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>
</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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.html#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"><number></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</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.html#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="lang-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]])<span><a class="mark" href="#vm_script_runinnewcontext_sandbox_options" id="vm_script_runinnewcontext_sandbox_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</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> 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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.html#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"><number></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</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.html#url_url_origin"><code>url.origin</code></a> property of a <a href="url.html#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>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="lang-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(<a href="#zlib_class_options">options</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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.html#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"><number></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#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> 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="lang-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.createContext([sandbox[, options]])<span><a class="mark" href="#vm_vm_createcontext_sandbox_options" id="vm_vm_createcontext_sandbox_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.1</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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a><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.html#url_url_origin"><code>url.origin</code></a> property of a <a href="url.html#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>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="lang-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)<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>
</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])<span><a class="mark" href="#vm_vm_runincontext_code_contextifiedsandbox_options" id="vm_vm_runincontext_code_contextifiedsandbox_options">#</a></span></h2>
<div class="signature"><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><code>options</code><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.html#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"><number></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</li>
</ul>
</li>
</ul>
</div><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>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="lang-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.runInDebugContext(code)<span><a class="mark" href="#vm_vm_runindebugcontext_code" id="vm_vm_runindebugcontext_code">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Calling this function now emits a deprecation warning.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p><span>Deprecated since: v8.0.0</span></p>
</td></tr>
<tr><td>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></p>
</td></tr>
</table>
</details>
</div><div class="api_stability api_stability_0"><a href="documentation.html#documentation_stability_index">Stability: 0</a> - Deprecated. An alternative is in development.</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>
</ul>
<p>The <code>vm.runInDebugContext()</code> method compiles and executes <code>code</code> inside the V8
debug context. The primary use case is to gain access to the V8 <code>Debug</code> object:</p>
<pre><code class="lang-js">const vm = require('vm');
const Debug = vm.runInDebugContext('Debug');
console.log(Debug.findScript(process.emit).name); // 'events.js'
console.log(Debug.findScript(process.exit).name); // 'internal/process.js'
</code></pre>
<p><em>Note</em>: The debug context and object are intrinsically tied to V8's debugger
implementation and may change (or even be removed) without prior warning.</p>
<p>The <code>Debug</code> object can also be made available using the V8-specific
<code>--expose_debug_as=</code> <a href="cli.html">command line option</a>.</p>
<h2>vm.runInNewContext(code[, sandbox][, options])<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><code>options</code><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.html#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"><number></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</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.html#url_url_origin"><code>url.origin</code></a> property of a <a href="url.html#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>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="lang-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])<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><code>options</code><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.html#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"><number></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a>
will be thrown.</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>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="lang-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="lang-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>
<!-- [end-include:vm.md] -->
<!-- [start-include:zlib.md] -->
<h1>Zlib<span><a class="mark" href="#zlib_zlib" id="zlib_zlib">#</a></span></h1>
<!--introduced_in=v0.10.0-->
<div class="api_stability api_stability_2"><a href="documentation.html#documentation_stability_index">Stability: 2</a> - Stable</div><p>The <code>zlib</code> module provides compression functionality implemented using Gzip and
Deflate/Inflate. It can be accessed using:</p>
<pre><code class="lang-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="lang-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="lang-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, which can have surprising and negative performance implications for
some applications, see the <a href="cli.html#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a> documentation for more
information.</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> and <code>deflate</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="lang-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': 'gzip,deflate' } });
request.on('response', (response) => {
const output = fs.createWriteStream('example.com_index.html');
switch (response.headers['content-encoding']) {
// or, just use zlib.createUnzip() to handle both 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="lang-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 {
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="lang-js">// This is a truncated version of the buffer from the above examples
const buffer = Buffer.from('eJzT0yMA', 'base64');
zlib.unzip(
buffer,
{ 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>
<!--type=misc-->
<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="lang-js">(1 << (windowBits + 2)) + (1 << (memLevel + 9))
</code></pre>
<p>That is: 128K for windowBits = 15 + 128K for memLevel = 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="lang-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 windowBits = 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>
<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="lang-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><!--type=misc-->
<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>
<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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>dictionary</code> option can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>dictionary</code> option can be an Uint8Array 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>
</table>
</details>
</div><!--type=misc-->
<p>Each 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> (default: <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> (default: <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> (default: 16*1024)</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.html#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: zlib.Deflate<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<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<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>
<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>
</table>
</details>
</div><p>Decompress a gzip stream.</p>
<h2>Class: zlib.Gzip<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<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>
<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>
</table>
</details>
</div><p>Decompress a deflate stream.</p>
<h2>Class: zlib.InflateRaw<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>
<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>
</table>
</details>
</div><p>Decompress a raw deflate stream.</p>
<h2>Class: zlib.Unzip<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.Zlib<span><a class="mark" href="#zlib_class_zlib_zlib" id="zlib_class_zlib_zlib">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</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>
<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>
</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.bytesRead</code> property specifies the number of bytes read by 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><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><p><code>kind</code> defaults to <code>zlib.constants.Z_FULL_FLUSH</code>.</p>
<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><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" id="zlib_zlib_constants">#</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.createDeflate(<a href="#zlib_class_options">options</a>)<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><p>Creates and returns a new <a href="#zlib_class_zlib_deflate">Deflate</a> object with the given <a href="#zlib_class_options">options</a>.</p>
<h2>zlib.createDeflateRaw(<a href="#zlib_class_options">options</a>)<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><p>Creates and returns a new <a href="#zlib_class_zlib_deflateraw">DeflateRaw</a> object with the given <a href="#zlib_class_options">options</a>.</p>
<p>An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when windowBits
is set to 8 for raw deflate streams. zlib would automatically set windowBits
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(<a href="#zlib_class_options">options</a>)<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><p>Creates and returns a new <a href="#zlib_class_zlib_gunzip">Gunzip</a> object with the given <a href="#zlib_class_options">options</a>.</p>
<h2>zlib.createGzip(<a href="#zlib_class_options">options</a>)<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><p>Creates and returns a new <a href="#zlib_class_zlib_gzip">Gzip</a> object with the given <a href="#zlib_class_options">options</a>.</p>
<h2>zlib.createInflate(<a href="#zlib_class_options">options</a>)<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><p>Creates and returns a new <a href="#zlib_class_zlib_inflate">Inflate</a> object with the given <a href="#zlib_class_options">options</a>.</p>
<h2>zlib.createInflateRaw(<a href="#zlib_class_options">options</a>)<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><p>Creates and returns a new <a href="#zlib_class_zlib_inflateraw">InflateRaw</a> object with the given <a href="#zlib_class_options">options</a>.</p>
<h2>zlib.createUnzip(<a href="#zlib_class_options">options</a>)<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><p>Creates and returns a new <a href="#zlib_class_zlib_unzip">Unzip</a> object with the given <a href="#zlib_class_options">options</a>.</p>
<h2>Convenience Methods<span><a class="mark" href="#zlib_convenience_methods" id="zlib_convenience_methods">#</a></span></h2>
<!--type=misc-->
<p>All of these take a <a href="buffer.html#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.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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p>
</td></tr>
</table>
</details>
</div><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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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>
</ul>
<p>Compress a chunk of data with <a href="#zlib_class_zlib_deflate">Deflate</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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p>
</td></tr>
</table>
</details>
</div><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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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>
</ul>
<p>Compress a chunk of data with <a href="#zlib_class_zlib_deflateraw">DeflateRaw</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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p>
</td></tr>
</table>
</details>
</div><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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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>
</ul>
<p>Decompress a chunk of data with <a href="#zlib_class_zlib_gunzip">Gunzip</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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p>
</td></tr>
</table>
</details>
</div><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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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>
</ul>
<p>Compress a chunk of data with <a href="#zlib_class_zlib_gzip">Gzip</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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p>
</td></tr>
</table>
</details>
</div><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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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>
</ul>
<p>Decompress a chunk of data with <a href="#zlib_class_zlib_inflate">Inflate</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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p>
</td></tr>
</table>
</details>
</div><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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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>
</ul>
<p>Decompress a chunk of data with <a href="#zlib_class_zlib_inflateraw">InflateRaw</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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p>
</td></tr>
</table>
</details>
</div><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>
<tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an ArrayBuffer.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any TypedArray or DataView now.</p>
</td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an Uint8Array now.</p>
</td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p>
</td></tr>
</table>
</details>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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>
</ul>
<p>Decompress a chunk of data with <a href="#zlib_class_zlib_unzip">Unzip</a>.</p>
<!-- [end-include:zlib.md] -->
</div>
</div>
</div>
<script src="assets/sh_main.js"></script>
<script src="assets/sh_javascript.min.js"></script>
<script>highlight(undefined, undefined, 'pre');</script>
<!-- __TRACKING__ -->
</body>
</html>