enclose-io/compiler

View on GitHub
lts/doc/api/all.html

Summary

Maintainability
Test Coverage
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Node.js v12.18.3 Documentation</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic&display=fallback">
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/hljs.css">
  <link rel="canonical" href="https://nodejs.org/api/all.html">
</head>
<body class="alt apidoc" id="api-section-all">
  <div id="content" class="clearfix">
    <div id="column2" class="interior">
      <div id="intro" class="interior">
        <a href="/" title="Go back to the home page">
          Node.js
        </a>
      </div>
      <ul>
<li><a href="documentation.html" class="nav-documentation">About these docs</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_hooks.html" class="nav-async_hooks">Async hooks</a></li>
<li><a href="buffer.html" class="nav-buffer">Buffer</a></li>
<li><a href="addons.html" class="nav-addons">C++ addons</a></li>
<li><a href="n-api.html" class="nav-n-api">C/C++ addons with N-API</a></li>
<li><a href="child_process.html" class="nav-child_process">Child processes</a></li>
<li><a href="cluster.html" class="nav-cluster">Cluster</a></li>
<li><a href="cli.html" class="nav-cli">Command line options</a></li>
<li><a href="console.html" class="nav-console">Console</a></li>
<li><a href="crypto.html" class="nav-crypto">Crypto</a></li>
<li><a href="debugger.html" class="nav-debugger">Debugger</a></li>
<li><a href="deprecations.html" class="nav-deprecations">Deprecated APIs</a></li>
<li><a href="dns.html" class="nav-dns">DNS</a></li>
<li><a href="domain.html" class="nav-domain">Domain</a></li>
<li><a href="esm.html" class="nav-esm">ECMAScript modules</a></li>
<li><a href="errors.html" class="nav-errors">Errors</a></li>
<li><a href="events.html" class="nav-events">Events</a></li>
<li><a href="fs.html" class="nav-fs">File system</a></li>
<li><a href="globals.html" class="nav-globals">Globals</a></li>
<li><a href="http.html" class="nav-http">HTTP</a></li>
<li><a href="http2.html" class="nav-http2">HTTP/2</a></li>
<li><a href="https.html" class="nav-https">HTTPS</a></li>
<li><a href="inspector.html" class="nav-inspector">Inspector</a></li>
<li><a href="intl.html" class="nav-intl">Internationalization</a></li>
<li><a href="modules.html" class="nav-modules">Modules</a></li>
<li><a href="net.html" class="nav-net">Net</a></li>
<li><a href="os.html" class="nav-os">OS</a></li>
<li><a href="path.html" class="nav-path">Path</a></li>
<li><a href="perf_hooks.html" class="nav-perf_hooks">Performance hooks</a></li>
<li><a href="policy.html" class="nav-policy">Policies</a></li>
<li><a href="process.html" class="nav-process">Process</a></li>
<li><a href="punycode.html" class="nav-punycode">Punycode</a></li>
<li><a href="querystring.html" class="nav-querystring">Query strings</a></li>
<li><a href="readline.html" class="nav-readline">Readline</a></li>
<li><a href="repl.html" class="nav-repl">REPL</a></li>
<li><a href="report.html" class="nav-report">Report</a></li>
<li><a href="stream.html" class="nav-stream">Stream</a></li>
<li><a href="string_decoder.html" class="nav-string_decoder">String decoder</a></li>
<li><a href="timers.html" class="nav-timers">Timers</a></li>
<li><a href="tls.html" class="nav-tls">TLS/SSL</a></li>
<li><a href="tracing.html" class="nav-tracing">Trace events</a></li>
<li><a href="tty.html" class="nav-tty">TTY</a></li>
<li><a href="dgram.html" class="nav-dgram">UDP/datagram</a></li>
<li><a href="url.html" class="nav-url">URL</a></li>
<li><a href="util.html" class="nav-util">Utilities</a></li>
<li><a href="v8.html" class="nav-v8">V8</a></li>
<li><a href="vm.html" class="nav-vm">VM</a></li>
<li><a href="wasi.html" class="nav-wasi">WASI</a></li>
<li><a href="worker_threads.html" class="nav-worker_threads">Worker threads</a></li>
<li><a href="zlib.html" class="nav-zlib">Zlib</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a href="https://github.com/nodejs/node" class="nav-https-github-com-nodejs-node">Code repository and issue tracker</a></li>
</ul>
    </div>

    <div id="column1" data-id="all" class="interior">
      <header>
        <h1>Node.js v12.18.3 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>&#x25bc;</span></a>
      <ol class="version-picker"><li><a href="https://nodejs.org/docs/latest-v14.x/api/all.html">14.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v13.x/api/all.html">13.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v12.x/api/all.html">12.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v11.x/api/all.html">11.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v10.x/api/all.html">10.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v9.x/api/all.html">9.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v8.x/api/all.html">8.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v7.x/api/all.html">7.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v6.x/api/all.html">6.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v5.x/api/all.html">5.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v4.x/api/all.html">4.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.12.x/api/all.html">0.12.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v0.10.x/api/all.html">0.10.x</a></li></ol>
    </li>
  
            
          </ul>
        </div>
        <hr>
      </header>

      <div id="toc">
        <h2>Table of Contents</h2>
        
      <ul>
<li>
<p><a href="#documentation_about_this_documentation">About this documentation</a></p>
<ul>
<li><a href="#documentation_contributing">Contributing</a></li>
<li><a href="#documentation_stability_index">Stability index</a></li>
<li><a href="#documentation_json_output">JSON output</a></li>
<li><a href="#documentation_system_calls_and_man_pages">System calls and man pages</a></li>
</ul>
</li>
<li>
<p><a href="#synopsis_usage_and_example">Usage and example</a></p>
<ul>
<li><a href="#synopsis_usage">Usage</a></li>
<li><a href="#synopsis_example">Example</a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#assert_assert">Assert</a></span></p>
<ul>
<li><a href="#assert_strict_assertion_mode">Strict assertion mode</a></li>
<li><a href="#assert_legacy_assertion_mode">Legacy assertion mode</a></li>
<li>
<p><a href="#assert_class_assert_assertionerror">Class: assert.AssertionError</a></p>
<ul>
<li><a href="#assert_new_assert_assertionerror_options"><code>new assert.AssertionError(options)</code></a></li>
</ul>
</li>
<li><a href="#assert_assert_value_message"><code>assert(value[, message])</code></a></li>
<li>
<p><a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual(actual, expected[, message])</code></a></p>
<ul>
<li><a href="#assert_comparison_details">Comparison details</a></li>
</ul>
</li>
<li>
<p><a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual(actual, expected[, message])</code></a></p>
<ul>
<li><a href="#assert_comparison_details_1">Comparison details</a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#assert_assert_doesnotmatch_string_regexp_message"><code>assert.doesNotMatch(string, regexp[, message])</code></a></span></li>
<li><a href="#assert_assert_doesnotreject_asyncfn_error_message"><code>assert.doesNotReject(asyncFn[, error][, message])</code></a></li>
<li><a href="#assert_assert_doesnotthrow_fn_error_message"><code>assert.doesNotThrow(fn[, error][, message])</code></a></li>
<li><a href="#assert_assert_equal_actual_expected_message"><code>assert.equal(actual, expected[, message])</code></a></li>
<li><a href="#assert_assert_fail_message"><code>assert.fail([message])</code></a></li>
<li><span class="stability_0"><a href="#assert_assert_fail_actual_expected_message_operator_stackstartfn"><code>assert.fail(actual, expected[, message[, operator[, stackStartFn]]])</code></a></span></li>
<li><a href="#assert_assert_iferror_value"><code>assert.ifError(value)</code></a></li>
<li><span class="stability_1"><a href="#assert_assert_match_string_regexp_message"><code>assert.match(string, regexp[, message])</code></a></span></li>
<li><a href="#assert_assert_notdeepequal_actual_expected_message"><code>assert.notDeepEqual(actual, expected[, message])</code></a></li>
<li><a href="#assert_assert_notdeepstrictequal_actual_expected_message"><code>assert.notDeepStrictEqual(actual, expected[, message])</code></a></li>
<li><a href="#assert_assert_notequal_actual_expected_message"><code>assert.notEqual(actual, expected[, message])</code></a></li>
<li><a href="#assert_assert_notstrictequal_actual_expected_message"><code>assert.notStrictEqual(actual, expected[, message])</code></a></li>
<li><a href="#assert_assert_ok_value_message"><code>assert.ok(value[, message])</code></a></li>
<li><a href="#assert_assert_rejects_asyncfn_error_message"><code>assert.rejects(asyncFn[, error][, message])</code></a></li>
<li><a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual(actual, expected[, message])</code></a></li>
<li><a href="#assert_assert_throws_fn_error_message"><code>assert.throws(fn[, error][, message])</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_1"><a href="#async_hooks_async_hooks">Async hooks</a></span></p>
<ul>
<li><a href="#async_hooks_terminology">Terminology</a></li>
<li>
<p><a href="#async_hooks_public_api">Public API</a></p>
<ul>
<li>
<p><a href="#async_hooks_overview">Overview</a></p>
<ul>
<li>
<p><a href="#async_hooks_async_hooks_createhook_callbacks"><code>async_hooks.createHook(callbacks)</code></a></p>
<ul>
<li><a href="#async_hooks_error_handling">Error handling</a></li>
<li><a href="#async_hooks_printing_in_asynchooks_callbacks">Printing in AsyncHooks callbacks</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#async_hooks_class_asynchook">Class: <code>AsyncHook</code></a></p>
<ul>
<li><a href="#async_hooks_asynchook_enable"><code>asyncHook.enable()</code></a></li>
<li><a href="#async_hooks_asynchook_disable"><code>asyncHook.disable()</code></a></li>
<li>
<p><a href="#async_hooks_hook_callbacks">Hook callbacks</a></p>
<ul>
<li>
<p><a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init(asyncId, type, triggerAsyncId, resource)</code></a></p>
<ul>
<li><a href="#async_hooks_type"><code>type</code></a></li>
<li><a href="#async_hooks_triggerasyncid"><code>triggerAsyncId</code></a></li>
<li><a href="#async_hooks_resource"><code>resource</code></a></li>
<li><a href="#async_hooks_asynchronous_context_example">Asynchronous context example</a></li>
</ul>
</li>
<li><a href="#async_hooks_before_asyncid"><code>before(asyncId)</code></a></li>
<li><a href="#async_hooks_after_asyncid"><code>after(asyncId)</code></a></li>
<li><a href="#async_hooks_destroy_asyncid"><code>destroy(asyncId)</code></a></li>
<li><a href="#async_hooks_promiseresolve_asyncid"><code>promiseResolve(asyncId)</code></a></li>
</ul>
</li>
<li><a href="#async_hooks_async_hooks_executionasyncresource"><code>async_hooks.executionAsyncResource()</code></a></li>
<li><a href="#async_hooks_async_hooks_executionasyncid"><code>async_hooks.executionAsyncId()</code></a></li>
<li><a href="#async_hooks_async_hooks_triggerasyncid"><code>async_hooks.triggerAsyncId()</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#async_hooks_promise_execution_tracking">Promise execution tracking</a></li>
<li>
<p><a href="#async_hooks_javascript_embedder_api">JavaScript embedder API</a></p>
<ul>
<li>
<p><a href="#async_hooks_class_asyncresource">Class: <code>AsyncResource</code></a></p>
<ul>
<li><a href="#async_hooks_new_asyncresource_type_options"><code>new AsyncResource(type[, options])</code></a></li>
<li><a href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args"><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code></a></li>
<li><a href="#async_hooks_asyncresource_emitdestroy"><code>asyncResource.emitDestroy()</code></a></li>
<li><a href="#async_hooks_asyncresource_asyncid"><code>asyncResource.asyncId()</code></a></li>
<li><a href="#async_hooks_asyncresource_triggerasyncid"><code>asyncResource.triggerAsyncId()</code></a></li>
</ul>
</li>
<li><a href="#async_hooks_using_asyncresource_for_a_worker_thread_pool">Using <code>AsyncResource</code> for a <code>Worker</code> thread pool</a></li>
<li><a href="#async_hooks_integrating_asyncresource_with_eventemitter">Integrating <code>AsyncResource</code> with <code>EventEmitter</code></a></li>
</ul>
</li>
<li>
<p><a href="#async_hooks_class_asynclocalstorage">Class: <code>AsyncLocalStorage</code></a></p>
<ul>
<li><a href="#async_hooks_new_asynclocalstorage"><code>new AsyncLocalStorage()</code></a></li>
<li><a href="#async_hooks_asynclocalstorage_disable"><code>asyncLocalStorage.disable()</code></a></li>
<li><a href="#async_hooks_asynclocalstorage_getstore"><code>asyncLocalStorage.getStore()</code></a></li>
<li><a href="#async_hooks_asynclocalstorage_enterwith_store"><code>asyncLocalStorage.enterWith(store)</code></a></li>
<li><a href="#async_hooks_asynclocalstorage_run_store_callback_args"><code>asyncLocalStorage.run(store, callback[, ...args])</code></a></li>
<li><a href="#async_hooks_asynclocalstorage_exit_callback_args"><code>asyncLocalStorage.exit(callback[, ...args])</code></a></li>
<li><a href="#async_hooks_usage_with_async_await">Usage with <code>async/await</code></a></li>
<li><a href="#async_hooks_troubleshooting">Troubleshooting</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#buffer_buffer">Buffer</a></span></p>
<ul>
<li><a href="#buffer_buffers_and_character_encodings">Buffers and character encodings</a></li>
<li><a href="#buffer_buffers_and_typedarrays">Buffers and TypedArrays</a></li>
<li><a href="#buffer_buffers_and_iteration">Buffers and iteration</a></li>
<li>
<p><a href="#buffer_class_buffer">Class: <code>Buffer</code></a></p>
<ul>
<li><a href="#buffer_class_method_buffer_alloc_size_fill_encoding">Class Method: <code>Buffer.alloc(size[, fill[, encoding]])</code></a></li>
<li><a href="#buffer_class_method_buffer_allocunsafe_size">Class Method: <code>Buffer.allocUnsafe(size)</code></a></li>
<li><a href="#buffer_class_method_buffer_allocunsafeslow_size">Class Method: <code>Buffer.allocUnsafeSlow(size)</code></a></li>
<li><a href="#buffer_class_method_buffer_bytelength_string_encoding">Class Method: <code>Buffer.byteLength(string[, encoding])</code></a></li>
<li><a href="#buffer_class_method_buffer_compare_buf1_buf2">Class Method: <code>Buffer.compare(buf1, buf2)</code></a></li>
<li><a href="#buffer_class_method_buffer_concat_list_totallength">Class Method: <code>Buffer.concat(list[, totalLength])</code></a></li>
<li><a href="#buffer_class_method_buffer_from_array">Class Method: <code>Buffer.from(array)</code></a></li>
<li><a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length">Class Method: <code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a></li>
<li><a href="#buffer_class_method_buffer_from_buffer">Class Method: <code>Buffer.from(buffer)</code></a></li>
<li><a href="#buffer_class_method_buffer_from_object_offsetorencoding_length">Class Method: <code>Buffer.from(object[, offsetOrEncoding[, length]])</code></a></li>
<li><a href="#buffer_class_method_buffer_from_string_encoding">Class Method: <code>Buffer.from(string[, encoding])</code></a></li>
<li><a href="#buffer_class_method_buffer_isbuffer_obj">Class Method: <code>Buffer.isBuffer(obj)</code></a></li>
<li><a href="#buffer_class_method_buffer_isencoding_encoding">Class Method: <code>Buffer.isEncoding(encoding)</code></a></li>
<li><a href="#buffer_class_property_buffer_poolsize">Class Property: <code>Buffer.poolSize</code></a></li>
<li><a href="#buffer_buf_index"><code>buf[index]</code></a></li>
<li><a href="#buffer_buf_buffer"><code>buf.buffer</code></a></li>
<li><a href="#buffer_buf_byteoffset"><code>buf.byteOffset</code></a></li>
<li><a href="#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend"><code>buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])</code></a></li>
<li><a href="#buffer_buf_copy_target_targetstart_sourcestart_sourceend"><code>buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])</code></a></li>
<li><a href="#buffer_buf_entries"><code>buf.entries()</code></a></li>
<li><a href="#buffer_buf_equals_otherbuffer"><code>buf.equals(otherBuffer)</code></a></li>
<li><a href="#buffer_buf_fill_value_offset_end_encoding"><code>buf.fill(value[, offset[, end]][, encoding])</code></a></li>
<li><a href="#buffer_buf_includes_value_byteoffset_encoding"><code>buf.includes(value[, byteOffset][, encoding])</code></a></li>
<li><a href="#buffer_buf_indexof_value_byteoffset_encoding"><code>buf.indexOf(value[, byteOffset][, encoding])</code></a></li>
<li><a href="#buffer_buf_keys"><code>buf.keys()</code></a></li>
<li><a href="#buffer_buf_lastindexof_value_byteoffset_encoding"><code>buf.lastIndexOf(value[, byteOffset][, encoding])</code></a></li>
<li><a href="#buffer_buf_length"><code>buf.length</code></a></li>
<li><span class="stability_0"><a href="#buffer_buf_parent"><code>buf.parent</code></a></span></li>
<li><a href="#buffer_buf_readbigint64be_offset"><code>buf.readBigInt64BE([offset])</code></a></li>
<li><a href="#buffer_buf_readbigint64le_offset"><code>buf.readBigInt64LE([offset])</code></a></li>
<li><a href="#buffer_buf_readbiguint64be_offset"><code>buf.readBigUInt64BE([offset])</code></a></li>
<li><a href="#buffer_buf_readbiguint64le_offset"><code>buf.readBigUInt64LE([offset])</code></a></li>
<li><a href="#buffer_buf_readdoublebe_offset"><code>buf.readDoubleBE([offset])</code></a></li>
<li><a href="#buffer_buf_readdoublele_offset"><code>buf.readDoubleLE([offset])</code></a></li>
<li><a href="#buffer_buf_readfloatbe_offset"><code>buf.readFloatBE([offset])</code></a></li>
<li><a href="#buffer_buf_readfloatle_offset"><code>buf.readFloatLE([offset])</code></a></li>
<li><a href="#buffer_buf_readint8_offset"><code>buf.readInt8([offset])</code></a></li>
<li><a href="#buffer_buf_readint16be_offset"><code>buf.readInt16BE([offset])</code></a></li>
<li><a href="#buffer_buf_readint16le_offset"><code>buf.readInt16LE([offset])</code></a></li>
<li><a href="#buffer_buf_readint32be_offset"><code>buf.readInt32BE([offset])</code></a></li>
<li><a href="#buffer_buf_readint32le_offset"><code>buf.readInt32LE([offset])</code></a></li>
<li><a href="#buffer_buf_readintbe_offset_bytelength"><code>buf.readIntBE(offset, byteLength)</code></a></li>
<li><a href="#buffer_buf_readintle_offset_bytelength"><code>buf.readIntLE(offset, byteLength)</code></a></li>
<li><a href="#buffer_buf_readuint8_offset"><code>buf.readUInt8([offset])</code></a></li>
<li><a href="#buffer_buf_readuint16be_offset"><code>buf.readUInt16BE([offset])</code></a></li>
<li><a href="#buffer_buf_readuint16le_offset"><code>buf.readUInt16LE([offset])</code></a></li>
<li><a href="#buffer_buf_readuint32be_offset"><code>buf.readUInt32BE([offset])</code></a></li>
<li><a href="#buffer_buf_readuint32le_offset"><code>buf.readUInt32LE([offset])</code></a></li>
<li><a href="#buffer_buf_readuintbe_offset_bytelength"><code>buf.readUIntBE(offset, byteLength)</code></a></li>
<li><a href="#buffer_buf_readuintle_offset_bytelength"><code>buf.readUIntLE(offset, byteLength)</code></a></li>
<li><a href="#buffer_buf_subarray_start_end"><code>buf.subarray([start[, end]])</code></a></li>
<li><a href="#buffer_buf_slice_start_end"><code>buf.slice([start[, end]])</code></a></li>
<li><a href="#buffer_buf_swap16"><code>buf.swap16()</code></a></li>
<li><a href="#buffer_buf_swap32"><code>buf.swap32()</code></a></li>
<li><a href="#buffer_buf_swap64"><code>buf.swap64()</code></a></li>
<li><a href="#buffer_buf_tojson"><code>buf.toJSON()</code></a></li>
<li><a href="#buffer_buf_tostring_encoding_start_end"><code>buf.toString([encoding[, start[, end]]])</code></a></li>
<li><a href="#buffer_buf_values"><code>buf.values()</code></a></li>
<li><a href="#buffer_buf_write_string_offset_length_encoding"><code>buf.write(string[, offset[, length]][, encoding])</code></a></li>
<li><a href="#buffer_buf_writebigint64be_value_offset"><code>buf.writeBigInt64BE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writebigint64le_value_offset"><code>buf.writeBigInt64LE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writebiguint64be_value_offset"><code>buf.writeBigUInt64BE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writebiguint64le_value_offset"><code>buf.writeBigUInt64LE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writedoublebe_value_offset"><code>buf.writeDoubleBE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writedoublele_value_offset"><code>buf.writeDoubleLE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writefloatbe_value_offset"><code>buf.writeFloatBE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writefloatle_value_offset"><code>buf.writeFloatLE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writeint8_value_offset"><code>buf.writeInt8(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writeint16be_value_offset"><code>buf.writeInt16BE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writeint16le_value_offset"><code>buf.writeInt16LE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writeint32be_value_offset"><code>buf.writeInt32BE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writeint32le_value_offset"><code>buf.writeInt32LE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writeintbe_value_offset_bytelength"><code>buf.writeIntBE(value, offset, byteLength)</code></a></li>
<li><a href="#buffer_buf_writeintle_value_offset_bytelength"><code>buf.writeIntLE(value, offset, byteLength)</code></a></li>
<li><a href="#buffer_buf_writeuint8_value_offset"><code>buf.writeUInt8(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writeuint16be_value_offset"><code>buf.writeUInt16BE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writeuint16le_value_offset"><code>buf.writeUInt16LE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writeuint32be_value_offset"><code>buf.writeUInt32BE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writeuint32le_value_offset"><code>buf.writeUInt32LE(value[, offset])</code></a></li>
<li><a href="#buffer_buf_writeuintbe_value_offset_bytelength"><code>buf.writeUIntBE(value, offset, byteLength)</code></a></li>
<li><a href="#buffer_buf_writeuintle_value_offset_bytelength"><code>buf.writeUIntLE(value, offset, byteLength)</code></a></li>
<li><span class="stability_0"><a href="#buffer_new_buffer_array"><code>new Buffer(array)</code></a></span></li>
<li><span class="stability_0"><a href="#buffer_new_buffer_arraybuffer_byteoffset_length"><code>new Buffer(arrayBuffer[, byteOffset[, length]])</code></a></span></li>
<li><span class="stability_0"><a href="#buffer_new_buffer_buffer"><code>new Buffer(buffer)</code></a></span></li>
<li><span class="stability_0"><a href="#buffer_new_buffer_size"><code>new Buffer(size)</code></a></span></li>
<li><span class="stability_0"><a href="#buffer_new_buffer_string_encoding"><code>new Buffer(string[, encoding])</code></a></span></li>
</ul>
</li>
<li><a href="#buffer_buffer_inspect_max_bytes"><code>buffer.INSPECT_MAX_BYTES</code></a></li>
<li><a href="#buffer_buffer_kmaxlength"><code>buffer.kMaxLength</code></a></li>
<li><a href="#buffer_buffer_transcode_source_fromenc_toenc"><code>buffer.transcode(source, fromEnc, toEnc)</code></a></li>
<li>
<p><span class="stability_0"><a href="#buffer_class_slowbuffer">Class: <code>SlowBuffer</code></a></span></p>
<ul>
<li><span class="stability_0"><a href="#buffer_new_slowbuffer_size"><code>new SlowBuffer(size)</code></a></span></li>
</ul>
</li>
<li>
<p><a href="#buffer_buffer_constants">Buffer constants</a></p>
<ul>
<li><a href="#buffer_buffer_constants_max_length"><code>buffer.constants.MAX_LENGTH</code></a></li>
<li><a href="#buffer_buffer_constants_max_string_length"><code>buffer.constants.MAX_STRING_LENGTH</code></a></li>
</ul>
</li>
<li>
<p><a href="#buffer_buffer_from_buffer_alloc_and_buffer_allocunsafe"><code>Buffer.from()</code>, <code>Buffer.alloc()</code>, and <code>Buffer.allocUnsafe()</code></a></p>
<ul>
<li><a href="#buffer_the_zero_fill_buffers_command_line_option">The <code>--zero-fill-buffers</code> command line option</a></li>
<li><a href="#buffer_what_makes_buffer_allocunsafe_and_buffer_allocunsafeslow_unsafe">What makes <code>Buffer.allocUnsafe()</code> and <code>Buffer.allocUnsafeSlow()</code> "unsafe"?</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#addons_c_addons">C++ addons</a></p>
<ul>
<li>
<p><a href="#addons_hello_world">Hello world</a></p>
<ul>
<li>
<p><a href="#addons_context_aware_addons">Context-aware addons</a></p>
<ul>
<li><a href="#addons_worker_support">Worker support</a></li>
</ul>
</li>
<li><a href="#addons_building">Building</a></li>
<li><a href="#addons_linking_to_libraries_included_with_node_js">Linking to libraries included with Node.js</a></li>
<li><a href="#addons_loading_addons_using_require">Loading addons using <code>require()</code></a></li>
</ul>
</li>
<li><a href="#addons_native_abstractions_for_node_js">Native abstractions for Node.js</a></li>
<li><a href="#addons_n_api">N-API</a></li>
<li>
<p><a href="#addons_addon_examples">Addon examples</a></p>
<ul>
<li><a href="#addons_function_arguments">Function arguments</a></li>
<li><a href="#addons_callbacks">Callbacks</a></li>
<li><a href="#addons_object_factory">Object factory</a></li>
<li><a href="#addons_function_factory">Function factory</a></li>
<li><a href="#addons_wrapping_c_objects">Wrapping C++ objects</a></li>
<li><a href="#addons_factory_of_wrapped_objects">Factory of wrapped objects</a></li>
<li><a href="#addons_passing_wrapped_objects_around">Passing wrapped objects around</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#n_api_n_api">N-API</a></span></p>
<ul>
<li><a href="#n_api_implications_of_abi_stability">Implications of ABI stability</a></li>
<li>
<p><a href="#n_api_building">Building</a></p>
<ul>
<li>
<p><a href="#n_api_build_tools">Build tools</a></p>
<ul>
<li><a href="#n_api_node_gyp">node-gyp</a></li>
<li><a href="#n_api_cmake_js">CMake.js</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_uploading_precompiled_binaries">Uploading precompiled binaries</a></p>
<ul>
<li><a href="#n_api_node_pre_gyp">node-pre-gyp</a></li>
<li><a href="#n_api_prebuild">prebuild</a></li>
<li><a href="#n_api_prebuildify">prebuildify</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#n_api_usage">Usage</a></li>
<li><a href="#n_api_n_api_version_matrix">N-API version matrix</a></li>
<li>
<p><a href="#n_api_environment_life_cycle_apis">Environment life cycle APIs</a></p>
<ul>
<li><a href="#n_api_napi_set_instance_data">napi_set_instance_data</a></li>
<li><a href="#n_api_napi_get_instance_data">napi_get_instance_data</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_basic_n_api_data_types">Basic N-API data types</a></p>
<ul>
<li><a href="#n_api_napi_status">napi_status</a></li>
<li><a href="#n_api_napi_extended_error_info">napi_extended_error_info</a></li>
<li><a href="#n_api_napi_env">napi_env</a></li>
<li><a href="#n_api_napi_value">napi_value</a></li>
<li><a href="#n_api_napi_threadsafe_function">napi_threadsafe_function</a></li>
<li><a href="#n_api_napi_threadsafe_function_release_mode">napi_threadsafe_function_release_mode</a></li>
<li><a href="#n_api_napi_threadsafe_function_call_mode">napi_threadsafe_function_call_mode</a></li>
<li>
<p><a href="#n_api_n_api_memory_management_types">N-API memory management types</a></p>
<ul>
<li><a href="#n_api_napi_handle_scope">napi_handle_scope</a></li>
<li><a href="#n_api_napi_escapable_handle_scope">napi_escapable_handle_scope</a></li>
<li><a href="#n_api_napi_ref">napi_ref</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_n_api_callback_types">N-API callback types</a></p>
<ul>
<li><a href="#n_api_napi_callback_info">napi_callback_info</a></li>
<li><a href="#n_api_napi_callback">napi_callback</a></li>
<li><a href="#n_api_napi_finalize">napi_finalize</a></li>
<li><a href="#n_api_napi_async_execute_callback">napi_async_execute_callback</a></li>
<li><a href="#n_api_napi_async_complete_callback">napi_async_complete_callback</a></li>
<li><a href="#n_api_napi_threadsafe_function_call_js">napi_threadsafe_function_call_js</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#n_api_error_handling">Error handling</a></p>
<ul>
<li>
<p><a href="#n_api_return_values">Return values</a></p>
<ul>
<li><a href="#n_api_napi_get_last_error_info">napi_get_last_error_info</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_exceptions">Exceptions</a></p>
<ul>
<li><a href="#n_api_napi_throw">napi_throw</a></li>
<li><a href="#n_api_napi_throw_error">napi_throw_error</a></li>
<li><a href="#n_api_napi_throw_type_error">napi_throw_type_error</a></li>
<li><a href="#n_api_napi_throw_range_error">napi_throw_range_error</a></li>
<li><a href="#n_api_napi_is_error">napi_is_error</a></li>
<li><a href="#n_api_napi_create_error">napi_create_error</a></li>
<li><a href="#n_api_napi_create_type_error">napi_create_type_error</a></li>
<li><a href="#n_api_napi_create_range_error">napi_create_range_error</a></li>
<li><a href="#n_api_napi_get_and_clear_last_exception">napi_get_and_clear_last_exception</a></li>
<li><a href="#n_api_napi_is_exception_pending">napi_is_exception_pending</a></li>
<li><a href="#n_api_napi_fatal_exception">napi_fatal_exception</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_fatal_errors">Fatal errors</a></p>
<ul>
<li><a href="#n_api_napi_fatal_error">napi_fatal_error</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#n_api_object_lifetime_management">Object lifetime management</a></p>
<ul>
<li>
<p><a href="#n_api_making_handle_lifespan_shorter_than_that_of_the_native_method">Making handle lifespan shorter than that of the native method</a></p>
<ul>
<li><a href="#n_api_napi_open_handle_scope">napi_open_handle_scope</a></li>
<li><a href="#n_api_napi_close_handle_scope">napi_close_handle_scope</a></li>
<li><a href="#n_api_napi_open_escapable_handle_scope">napi_open_escapable_handle_scope</a></li>
<li><a href="#n_api_napi_close_escapable_handle_scope">napi_close_escapable_handle_scope</a></li>
<li><a href="#n_api_napi_escape_handle">napi_escape_handle</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method">References to objects with a lifespan longer than that of the native method</a></p>
<ul>
<li><a href="#n_api_napi_create_reference">napi_create_reference</a></li>
<li><a href="#n_api_napi_delete_reference">napi_delete_reference</a></li>
<li><a href="#n_api_napi_reference_ref">napi_reference_ref</a></li>
<li><a href="#n_api_napi_reference_unref">napi_reference_unref</a></li>
<li><a href="#n_api_napi_get_reference_value">napi_get_reference_value</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_cleanup_on_exit_of_the_current_node_js_instance">Cleanup on exit of the current Node.js instance</a></p>
<ul>
<li><a href="#n_api_napi_add_env_cleanup_hook">napi_add_env_cleanup_hook</a></li>
<li><a href="#n_api_napi_remove_env_cleanup_hook">napi_remove_env_cleanup_hook</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#n_api_module_registration">Module registration</a></li>
<li>
<p><a href="#n_api_working_with_javascript_values">Working with JavaScript values</a></p>
<ul>
<li>
<p><a href="#n_api_enum_types">Enum types</a></p>
<ul>
<li><a href="#n_api_napi_key_collection_mode">napi_key_collection_mode</a></li>
<li><a href="#n_api_napi_key_filter">napi_key_filter</a></li>
<li><a href="#n_api_napi_key_conversion">napi_key_conversion</a></li>
<li><a href="#n_api_napi_valuetype">napi_valuetype</a></li>
<li><a href="#n_api_napi_typedarray_type">napi_typedarray_type</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_object_creation_functions">Object creation functions</a></p>
<ul>
<li><a href="#n_api_napi_create_array">napi_create_array</a></li>
<li><a href="#n_api_napi_create_array_with_length">napi_create_array_with_length</a></li>
<li><a href="#n_api_napi_create_arraybuffer">napi_create_arraybuffer</a></li>
<li><a href="#n_api_napi_create_buffer">napi_create_buffer</a></li>
<li><a href="#n_api_napi_create_buffer_copy">napi_create_buffer_copy</a></li>
<li><a href="#n_api_napi_create_date">napi_create_date</a></li>
<li><a href="#n_api_napi_create_external">napi_create_external</a></li>
<li><a href="#n_api_napi_create_external_arraybuffer">napi_create_external_arraybuffer</a></li>
<li><a href="#n_api_napi_create_external_buffer">napi_create_external_buffer</a></li>
<li><a href="#n_api_napi_create_object">napi_create_object</a></li>
<li><a href="#n_api_napi_create_symbol">napi_create_symbol</a></li>
<li><a href="#n_api_napi_create_typedarray">napi_create_typedarray</a></li>
<li><a href="#n_api_napi_create_dataview">napi_create_dataview</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_functions_to_convert_from_c_types_to_n_api">Functions to convert from C types to N-API</a></p>
<ul>
<li><a href="#n_api_napi_create_int32">napi_create_int32</a></li>
<li><a href="#n_api_napi_create_uint32">napi_create_uint32</a></li>
<li><a href="#n_api_napi_create_int64">napi_create_int64</a></li>
<li><a href="#n_api_napi_create_double">napi_create_double</a></li>
<li><a href="#n_api_napi_create_bigint_int64">napi_create_bigint_int64</a></li>
<li><a href="#n_api_napi_create_bigint_uint64">napi_create_bigint_uint64</a></li>
<li><a href="#n_api_napi_create_bigint_words">napi_create_bigint_words</a></li>
<li><a href="#n_api_napi_create_string_latin1">napi_create_string_latin1</a></li>
<li><a href="#n_api_napi_create_string_utf16">napi_create_string_utf16</a></li>
<li><a href="#n_api_napi_create_string_utf8">napi_create_string_utf8</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_functions_to_convert_from_n_api_to_c_types">Functions to convert from N-API to C types</a></p>
<ul>
<li><a href="#n_api_napi_get_array_length">napi_get_array_length</a></li>
<li><a href="#n_api_napi_get_arraybuffer_info">napi_get_arraybuffer_info</a></li>
<li><a href="#n_api_napi_get_buffer_info">napi_get_buffer_info</a></li>
<li><a href="#n_api_napi_get_prototype">napi_get_prototype</a></li>
<li><a href="#n_api_napi_get_typedarray_info">napi_get_typedarray_info</a></li>
<li><a href="#n_api_napi_get_dataview_info">napi_get_dataview_info</a></li>
<li><a href="#n_api_napi_get_date_value">napi_get_date_value</a></li>
<li><a href="#n_api_napi_get_value_bool">napi_get_value_bool</a></li>
<li><a href="#n_api_napi_get_value_double">napi_get_value_double</a></li>
<li><a href="#n_api_napi_get_value_bigint_int64">napi_get_value_bigint_int64</a></li>
<li><a href="#n_api_napi_get_value_bigint_uint64">napi_get_value_bigint_uint64</a></li>
<li><a href="#n_api_napi_get_value_bigint_words">napi_get_value_bigint_words</a></li>
<li><a href="#n_api_napi_get_value_external">napi_get_value_external</a></li>
<li><a href="#n_api_napi_get_value_int32">napi_get_value_int32</a></li>
<li><a href="#n_api_napi_get_value_int64">napi_get_value_int64</a></li>
<li><a href="#n_api_napi_get_value_string_latin1">napi_get_value_string_latin1</a></li>
<li><a href="#n_api_napi_get_value_string_utf8">napi_get_value_string_utf8</a></li>
<li><a href="#n_api_napi_get_value_string_utf16">napi_get_value_string_utf16</a></li>
<li><a href="#n_api_napi_get_value_uint32">napi_get_value_uint32</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_functions_to_get_global_instances">Functions to get global instances</a></p>
<ul>
<li><a href="#n_api_napi_get_boolean">napi_get_boolean</a></li>
<li><a href="#n_api_napi_get_global">napi_get_global</a></li>
<li><a href="#n_api_napi_get_null">napi_get_null</a></li>
<li><a href="#n_api_napi_get_undefined">napi_get_undefined</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#n_api_working_with_javascript_values_and_abstract_operations">Working with JavaScript values and abstract operations</a></p>
<ul>
<li><a href="#n_api_napi_coerce_to_bool">napi_coerce_to_bool</a></li>
<li><a href="#n_api_napi_coerce_to_number">napi_coerce_to_number</a></li>
<li><a href="#n_api_napi_coerce_to_object">napi_coerce_to_object</a></li>
<li><a href="#n_api_napi_coerce_to_string">napi_coerce_to_string</a></li>
<li><a href="#n_api_napi_typeof">napi_typeof</a></li>
<li><a href="#n_api_napi_instanceof">napi_instanceof</a></li>
<li><a href="#n_api_napi_is_array">napi_is_array</a></li>
<li><a href="#n_api_napi_is_arraybuffer">napi_is_arraybuffer</a></li>
<li><a href="#n_api_napi_is_buffer">napi_is_buffer</a></li>
<li><a href="#n_api_napi_is_date">napi_is_date</a></li>
<li><a href="#n_api_napi_is_error_1">napi_is_error</a></li>
<li><a href="#n_api_napi_is_typedarray">napi_is_typedarray</a></li>
<li><a href="#n_api_napi_is_dataview">napi_is_dataview</a></li>
<li><a href="#n_api_napi_strict_equals">napi_strict_equals</a></li>
<li><span class="stability_1"><a href="#n_api_napi_detach_arraybuffer">napi_detach_arraybuffer</a></span></li>
<li><span class="stability_1"><a href="#n_api_napi_is_detached_arraybuffer">napi_is_detached_arraybuffer</a></span></li>
</ul>
</li>
<li>
<p><a href="#n_api_working_with_javascript_properties">Working with JavaScript properties</a></p>
<ul>
<li>
<p><a href="#n_api_structures">Structures</a></p>
<ul>
<li><a href="#n_api_napi_property_attributes">napi_property_attributes</a></li>
<li><a href="#n_api_napi_property_descriptor">napi_property_descriptor</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_functions">Functions</a></p>
<ul>
<li><a href="#n_api_napi_get_property_names">napi_get_property_names</a></li>
<li><a href="#n_api_napi_get_all_property_names">napi_get_all_property_names</a></li>
<li><a href="#n_api_napi_set_property">napi_set_property</a></li>
<li><a href="#n_api_napi_get_property">napi_get_property</a></li>
<li><a href="#n_api_napi_has_property">napi_has_property</a></li>
<li><a href="#n_api_napi_delete_property">napi_delete_property</a></li>
<li><a href="#n_api_napi_has_own_property">napi_has_own_property</a></li>
<li><a href="#n_api_napi_set_named_property">napi_set_named_property</a></li>
<li><a href="#n_api_napi_get_named_property">napi_get_named_property</a></li>
<li><a href="#n_api_napi_has_named_property">napi_has_named_property</a></li>
<li><a href="#n_api_napi_set_element">napi_set_element</a></li>
<li><a href="#n_api_napi_get_element">napi_get_element</a></li>
<li><a href="#n_api_napi_has_element">napi_has_element</a></li>
<li><a href="#n_api_napi_delete_element">napi_delete_element</a></li>
<li><a href="#n_api_napi_define_properties">napi_define_properties</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#n_api_working_with_javascript_functions">Working with JavaScript functions</a></p>
<ul>
<li><a href="#n_api_napi_call_function">napi_call_function</a></li>
<li><a href="#n_api_napi_create_function">napi_create_function</a></li>
<li><a href="#n_api_napi_get_cb_info">napi_get_cb_info</a></li>
<li><a href="#n_api_napi_get_new_target">napi_get_new_target</a></li>
<li><a href="#n_api_napi_new_instance">napi_new_instance</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_object_wrap">Object wrap</a></p>
<ul>
<li><a href="#n_api_napi_define_class">napi_define_class</a></li>
<li><a href="#n_api_napi_wrap">napi_wrap</a></li>
<li><a href="#n_api_napi_unwrap">napi_unwrap</a></li>
<li><a href="#n_api_napi_remove_wrap">napi_remove_wrap</a></li>
<li><a href="#n_api_napi_add_finalizer">napi_add_finalizer</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_simple_asynchronous_operations">Simple asynchronous operations</a></p>
<ul>
<li><a href="#n_api_napi_create_async_work">napi_create_async_work</a></li>
<li><a href="#n_api_napi_delete_async_work">napi_delete_async_work</a></li>
<li><a href="#n_api_napi_queue_async_work">napi_queue_async_work</a></li>
<li><a href="#n_api_napi_cancel_async_work">napi_cancel_async_work</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_custom_asynchronous_operations">Custom asynchronous operations</a></p>
<ul>
<li><a href="#n_api_napi_async_init">napi_async_init</a></li>
<li><a href="#n_api_napi_async_destroy">napi_async_destroy</a></li>
<li><a href="#n_api_napi_make_callback">napi_make_callback</a></li>
<li><a href="#n_api_napi_open_callback_scope">napi_open_callback_scope</a></li>
<li><a href="#n_api_napi_close_callback_scope">napi_close_callback_scope</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_version_management">Version management</a></p>
<ul>
<li><a href="#n_api_napi_get_node_version">napi_get_node_version</a></li>
<li><a href="#n_api_napi_get_version">napi_get_version</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_memory_management">Memory management</a></p>
<ul>
<li><a href="#n_api_napi_adjust_external_memory">napi_adjust_external_memory</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_promises">Promises</a></p>
<ul>
<li><a href="#n_api_napi_create_promise">napi_create_promise</a></li>
<li><a href="#n_api_napi_resolve_deferred">napi_resolve_deferred</a></li>
<li><a href="#n_api_napi_reject_deferred">napi_reject_deferred</a></li>
<li><a href="#n_api_napi_is_promise">napi_is_promise</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_script_execution">Script execution</a></p>
<ul>
<li><a href="#n_api_napi_run_script">napi_run_script</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_libuv_event_loop">libuv event loop</a></p>
<ul>
<li><a href="#n_api_napi_get_uv_event_loop">napi_get_uv_event_loop</a></li>
</ul>
</li>
<li>
<p><a href="#n_api_asynchronous_thread_safe_function_calls">Asynchronous thread-safe function calls</a></p>
<ul>
<li><a href="#n_api_calling_a_thread_safe_function">Calling a thread-safe function</a></li>
<li><a href="#n_api_reference_counting_of_thread_safe_functions">Reference counting of thread-safe functions</a></li>
<li><a href="#n_api_deciding_whether_to_keep_the_process_running">Deciding whether to keep the process running</a></li>
<li><a href="#n_api_napi_create_threadsafe_function">napi_create_threadsafe_function</a></li>
<li><a href="#n_api_napi_get_threadsafe_function_context">napi_get_threadsafe_function_context</a></li>
<li><a href="#n_api_napi_call_threadsafe_function">napi_call_threadsafe_function</a></li>
<li><a href="#n_api_napi_acquire_threadsafe_function">napi_acquire_threadsafe_function</a></li>
<li><a href="#n_api_napi_release_threadsafe_function">napi_release_threadsafe_function</a></li>
<li><a href="#n_api_napi_ref_threadsafe_function">napi_ref_threadsafe_function</a></li>
<li><a href="#n_api_napi_unref_threadsafe_function">napi_unref_threadsafe_function</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#child_process_child_process">Child process</a></span></p>
<ul>
<li>
<p><a href="#child_process_asynchronous_process_creation">Asynchronous process creation</a></p>
<ul>
<li><a href="#child_process_spawning_bat_and_cmd_files_on_windows">Spawning <code>.bat</code> and <code>.cmd</code> files on Windows</a></li>
<li><a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec(command[, options][, callback])</code></a></li>
<li><a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile(file[, args][, options][, callback])</code></a></li>
<li><a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork(modulePath[, args][, options])</code></a></li>
<li>
<p><a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn(command[, args][, options])</code></a></p>
<ul>
<li><a href="#child_process_options_detached"><code>options.detached</code></a></li>
<li><a href="#child_process_options_stdio"><code>options.stdio</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#child_process_synchronous_process_creation">Synchronous process creation</a></p>
<ul>
<li><a href="#child_process_child_process_execfilesync_file_args_options"><code>child_process.execFileSync(file[, args][, options])</code></a></li>
<li><a href="#child_process_child_process_execsync_command_options"><code>child_process.execSync(command[, options])</code></a></li>
<li><a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync(command[, args][, options])</code></a></li>
</ul>
</li>
<li>
<p><a href="#child_process_class_childprocess">Class: <code>ChildProcess</code></a></p>
<ul>
<li><a href="#child_process_event_close">Event: <code>'close'</code></a></li>
<li><a href="#child_process_event_disconnect">Event: <code>'disconnect'</code></a></li>
<li><a href="#child_process_event_error">Event: <code>'error'</code></a></li>
<li><a href="#child_process_event_exit">Event: <code>'exit'</code></a></li>
<li><a href="#child_process_event_message">Event: <code>'message'</code></a></li>
<li><a href="#child_process_subprocess_channel"><code>subprocess.channel</code></a></li>
<li><a href="#child_process_subprocess_connected"><code>subprocess.connected</code></a></li>
<li><a href="#child_process_subprocess_disconnect"><code>subprocess.disconnect()</code></a></li>
<li><a href="#child_process_subprocess_exitcode"><code>subprocess.exitCode</code></a></li>
<li><a href="#child_process_subprocess_kill_signal"><code>subprocess.kill([signal])</code></a></li>
<li><a href="#child_process_subprocess_killed"><code>subprocess.killed</code></a></li>
<li><a href="#child_process_subprocess_pid"><code>subprocess.pid</code></a></li>
<li><a href="#child_process_subprocess_ref"><code>subprocess.ref()</code></a></li>
<li>
<p><a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>subprocess.send(message[, sendHandle[, options]][, callback])</code></a></p>
<ul>
<li><a href="#child_process_example_sending_a_server_object">Example: sending a server object</a></li>
<li><a href="#child_process_example_sending_a_socket_object">Example: sending a socket object</a></li>
</ul>
</li>
<li><a href="#child_process_subprocess_signalcode"><code>subprocess.signalCode</code></a></li>
<li><a href="#child_process_subprocess_spawnargs"><code>subprocess.spawnargs</code></a></li>
<li><a href="#child_process_subprocess_spawnfile"><code>subprocess.spawnfile</code></a></li>
<li><a href="#child_process_subprocess_stderr"><code>subprocess.stderr</code></a></li>
<li><a href="#child_process_subprocess_stdin"><code>subprocess.stdin</code></a></li>
<li><a href="#child_process_subprocess_stdio"><code>subprocess.stdio</code></a></li>
<li><a href="#child_process_subprocess_stdout"><code>subprocess.stdout</code></a></li>
<li><a href="#child_process_subprocess_unref"><code>subprocess.unref()</code></a></li>
</ul>
</li>
<li><a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a></li>
<li><a href="#child_process_shell_requirements">Shell requirements</a></li>
<li><a href="#child_process_default_windows_shell">Default Windows shell</a></li>
<li><a href="#child_process_advanced_serialization">Advanced serialization</a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#cluster_cluster">Cluster</a></span></p>
<ul>
<li><a href="#cluster_how_it_works">How it works</a></li>
<li>
<p><a href="#cluster_class_worker">Class: <code>Worker</code></a></p>
<ul>
<li><a href="#cluster_event_disconnect">Event: <code>'disconnect'</code></a></li>
<li><a href="#cluster_event_error">Event: <code>'error'</code></a></li>
<li><a href="#cluster_event_exit">Event: <code>'exit'</code></a></li>
<li><a href="#cluster_event_listening">Event: <code>'listening'</code></a></li>
<li><a href="#cluster_event_message">Event: <code>'message'</code></a></li>
<li><a href="#cluster_event_online">Event: <code>'online'</code></a></li>
<li><a href="#cluster_worker_disconnect"><code>worker.disconnect()</code></a></li>
<li><a href="#cluster_worker_exitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a></li>
<li><a href="#cluster_worker_id"><code>worker.id</code></a></li>
<li><a href="#cluster_worker_isconnected"><code>worker.isConnected()</code></a></li>
<li><a href="#cluster_worker_isdead"><code>worker.isDead()</code></a></li>
<li><a href="#cluster_worker_kill_signal"><code>worker.kill([signal])</code></a></li>
<li><a href="#cluster_worker_process"><code>worker.process</code></a></li>
<li><a href="#cluster_worker_send_message_sendhandle_options_callback"><code>worker.send(message[, sendHandle[, options]][, callback])</code></a></li>
</ul>
</li>
<li><a href="#cluster_event_disconnect_1">Event: <code>'disconnect'</code></a></li>
<li><a href="#cluster_event_exit_1">Event: <code>'exit'</code></a></li>
<li><a href="#cluster_event_fork">Event: <code>'fork'</code></a></li>
<li><a href="#cluster_event_listening_1">Event: <code>'listening'</code></a></li>
<li><a href="#cluster_event_message_1">Event: <code>'message'</code></a></li>
<li><a href="#cluster_event_online_1">Event: <code>'online'</code></a></li>
<li><a href="#cluster_event_setup">Event: <code>'setup'</code></a></li>
<li><a href="#cluster_cluster_disconnect_callback"><code>cluster.disconnect([callback])</code></a></li>
<li><a href="#cluster_cluster_fork_env"><code>cluster.fork([env])</code></a></li>
<li><a href="#cluster_cluster_ismaster"><code>cluster.isMaster</code></a></li>
<li><a href="#cluster_cluster_isworker"><code>cluster.isWorker</code></a></li>
<li><a href="#cluster_cluster_schedulingpolicy"><code>cluster.schedulingPolicy</code></a></li>
<li><a href="#cluster_cluster_settings"><code>cluster.settings</code></a></li>
<li><a href="#cluster_cluster_setupmaster_settings"><code>cluster.setupMaster([settings])</code></a></li>
<li><a href="#cluster_cluster_worker"><code>cluster.worker</code></a></li>
<li><a href="#cluster_cluster_workers"><code>cluster.workers</code></a></li>
</ul>
</li>
<li>
<p><a href="#cli_command_line_options">Command line options</a></p>
<ul>
<li><a href="#cli_synopsis">Synopsis</a></li>
<li>
<p><a href="#cli_options">Options</a></p>
<ul>
<li><a href="#cli"><code>-</code></a></li>
<li><a href="#cli_1"><code>--</code></a></li>
<li><a href="#cli_abort_on_uncaught_exception"><code>--abort-on-uncaught-exception</code></a></li>
<li><a href="#cli_completion_bash"><code>--completion-bash</code></a></li>
<li><span class="stability_1"><a href="#cli_cpu_prof"><code>--cpu-prof</code></a></span></li>
<li><span class="stability_1"><a href="#cli_cpu_prof_dir"><code>--cpu-prof-dir</code></a></span></li>
<li><span class="stability_1"><a href="#cli_cpu_prof_interval"><code>--cpu-prof-interval</code></a></span></li>
<li><span class="stability_1"><a href="#cli_cpu_prof_name"><code>--cpu-prof-name</code></a></span></li>
<li><a href="#cli_disable_proto_mode"><code>--disable-proto=mode</code></a></li>
<li><a href="#cli_disallow_code_generation_from_strings"><code>--disallow-code-generation-from-strings</code></a></li>
<li><a href="#cli_enable_fips"><code>--enable-fips</code></a></li>
<li><span class="stability_1"><a href="#cli_enable_source_maps"><code>--enable-source-maps</code></a></span></li>
<li><a href="#cli_experimental_import_meta_resolve"><code>--experimental-import-meta-resolve</code></a></li>
<li><a href="#cli_experimental_json_modules"><code>--experimental-json-modules</code></a></li>
<li><a href="#cli_experimental_loader_module"><code>--experimental-loader=module</code></a></li>
<li><a href="#cli_experimental_modules"><code>--experimental-modules</code></a></li>
<li><a href="#cli_experimental_policy"><code>--experimental-policy</code></a></li>
<li><a href="#cli_experimental_repl_await"><code>--experimental-repl-await</code></a></li>
<li><a href="#cli_experimental_specifier_resolution_mode"><code>--experimental-specifier-resolution=mode</code></a></li>
<li><a href="#cli_experimental_vm_modules"><code>--experimental-vm-modules</code></a></li>
<li><a href="#cli_experimental_wasi_unstable_preview1"><code>--experimental-wasi-unstable-preview1</code></a></li>
<li><a href="#cli_experimental_wasm_modules"><code>--experimental-wasm-modules</code></a></li>
<li><a href="#cli_force_context_aware"><code>--force-context-aware</code></a></li>
<li><a href="#cli_force_fips"><code>--force-fips</code></a></li>
<li><span class="stability_1"><a href="#cli_frozen_intrinsics"><code>--frozen-intrinsics</code></a></span></li>
<li><a href="#cli_heapsnapshot_signal_signal"><code>--heapsnapshot-signal=signal</code></a></li>
<li><span class="stability_1"><a href="#cli_heap_prof"><code>--heap-prof</code></a></span></li>
<li><span class="stability_1"><a href="#cli_heap_prof_dir"><code>--heap-prof-dir</code></a></span></li>
<li><span class="stability_1"><a href="#cli_heap_prof_interval"><code>--heap-prof-interval</code></a></span></li>
<li><span class="stability_1"><a href="#cli_heap_prof_name"><code>--heap-prof-name</code></a></span></li>
<li><a href="#cli_http_parser_library"><code>--http-parser=library</code></a></li>
<li><a href="#cli_http_server_default_timeout_milliseconds"><code>--http-server-default-timeout=milliseconds</code></a></li>
<li><a href="#cli_icu_data_dir_file"><code>--icu-data-dir=file</code></a></li>
<li><a href="#cli_input_type_type"><code>--input-type=type</code></a></li>
<li><a href="#cli_inspect_brk_host_port"><code>--inspect-brk[=[host:]port]</code></a></li>
<li><a href="#cli_inspect_port_host_port"><code>--inspect-port=[host:]port</code></a></li>
<li>
<p><a href="#cli_inspect_host_port"><code>--inspect[=[host:]port]</code></a></p>
<ul>
<li><a href="#cli_warning_binding_inspector_to_a_public_ip_port_combination_is_insecure">Warning: binding inspector to a public IP:port combination is insecure</a></li>
</ul>
</li>
<li><a href="#cli_inspect_publish_uid_stderr_http"><code>--inspect-publish-uid=stderr,http</code></a></li>
<li><a href="#cli_insecure_http_parser"><code>--insecure-http-parser</code></a></li>
<li><a href="#cli_jitless"><code>--jitless</code></a></li>
<li><a href="#cli_max_http_header_size_size"><code>--max-http-header-size=size</code></a></li>
<li><a href="#cli_napi_modules"><code>--napi-modules</code></a></li>
<li><a href="#cli_no_deprecation"><code>--no-deprecation</code></a></li>
<li><a href="#cli_no_force_async_hooks_checks"><code>--no-force-async-hooks-checks</code></a></li>
<li><a href="#cli_no_warnings"><code>--no-warnings</code></a></li>
<li><a href="#cli_openssl_config_file"><code>--openssl-config=file</code></a></li>
<li><a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a></li>
<li><span class="stability_1"><a href="#cli_policy_integrity_sri"><code>--policy-integrity=sri</code></a></span></li>
<li><a href="#cli_preserve_symlinks"><code>--preserve-symlinks</code></a></li>
<li><a href="#cli_preserve_symlinks_main"><code>--preserve-symlinks-main</code></a></li>
<li><a href="#cli_prof"><code>--prof</code></a></li>
<li><a href="#cli_prof_process"><code>--prof-process</code></a></li>
<li><a href="#cli_redirect_warnings_file"><code>--redirect-warnings=file</code></a></li>
<li><a href="#cli_report_compact"><code>--report-compact</code></a></li>
<li><a href="#cli_report_directory_directory"><code>--report-directory=directory</code></a></li>
<li><a href="#cli_report_filename_filename"><code>--report-filename=filename</code></a></li>
<li><a href="#cli_report_on_fatalerror"><code>--report-on-fatalerror</code></a></li>
<li><a href="#cli_report_on_signal"><code>--report-on-signal</code></a></li>
<li><a href="#cli_report_signal_signal"><code>--report-signal=signal</code></a></li>
<li><a href="#cli_report_uncaught_exception"><code>--report-uncaught-exception</code></a></li>
<li><a href="#cli_throw_deprecation"><code>--throw-deprecation</code></a></li>
<li><a href="#cli_title_title"><code>--title=title</code></a></li>
<li><a href="#cli_tls_cipher_list_list"><code>--tls-cipher-list=list</code></a></li>
<li><a href="#cli_tls_keylog_file"><code>--tls-keylog=file</code></a></li>
<li><a href="#cli_tls_max_v1_2"><code>--tls-max-v1.2</code></a></li>
<li><a href="#cli_tls_max_v1_3"><code>--tls-max-v1.3</code></a></li>
<li><a href="#cli_tls_min_v1_0"><code>--tls-min-v1.0</code></a></li>
<li><a href="#cli_tls_min_v1_1"><code>--tls-min-v1.1</code></a></li>
<li><a href="#cli_tls_min_v1_2"><code>--tls-min-v1.2</code></a></li>
<li><a href="#cli_tls_min_v1_3"><code>--tls-min-v1.3</code></a></li>
<li><a href="#cli_trace_deprecation"><code>--trace-deprecation</code></a></li>
<li><a href="#cli_trace_event_categories"><code>--trace-event-categories</code></a></li>
<li><a href="#cli_trace_event_file_pattern"><code>--trace-event-file-pattern</code></a></li>
<li><a href="#cli_trace_events_enabled"><code>--trace-events-enabled</code></a></li>
<li><a href="#cli_trace_exit"><code>--trace-exit</code></a></li>
<li><a href="#cli_trace_sigint"><code>--trace-sigint</code></a></li>
<li><a href="#cli_trace_sync_io"><code>--trace-sync-io</code></a></li>
<li><a href="#cli_trace_tls"><code>--trace-tls</code></a></li>
<li><a href="#cli_trace_uncaught"><code>--trace-uncaught</code></a></li>
<li><a href="#cli_trace_warnings"><code>--trace-warnings</code></a></li>
<li><a href="#cli_track_heap_objects"><code>--track-heap-objects</code></a></li>
<li><a href="#cli_unhandled_rejections_mode"><code>--unhandled-rejections=mode</code></a></li>
<li><a href="#cli_use_bundled_ca_use_openssl_ca"><code>--use-bundled-ca</code>, <code>--use-openssl-ca</code></a></li>
<li><a href="#cli_use_largepages_mode"><code>--use-largepages=mode</code></a></li>
<li><a href="#cli_v8_options"><code>--v8-options</code></a></li>
<li><a href="#cli_v8_pool_size_num"><code>--v8-pool-size=num</code></a></li>
<li><a href="#cli_zero_fill_buffers"><code>--zero-fill-buffers</code></a></li>
<li><a href="#cli_c_check"><code>-c</code>, <code>--check</code></a></li>
<li><a href="#cli_e_eval_script"><code>-e</code>, <code>--eval "script"</code></a></li>
<li><a href="#cli_h_help"><code>-h</code>, <code>--help</code></a></li>
<li><a href="#cli_i_interactive"><code>-i</code>, <code>--interactive</code></a></li>
<li><a href="#cli_p_print_script"><code>-p</code>, <code>--print "script"</code></a></li>
<li><a href="#cli_r_require_module"><code>-r</code>, <code>--require module</code></a></li>
<li><a href="#cli_v_version"><code>-v</code>, <code>--version</code></a></li>
</ul>
</li>
<li>
<p><a href="#cli_environment_variables">Environment variables</a></p>
<ul>
<li><a href="#cli_node_debug_module"><code>NODE_DEBUG=module[,…]</code></a></li>
<li><a href="#cli_node_debug_native_module"><code>NODE_DEBUG_NATIVE=module[,…]</code></a></li>
<li><a href="#cli_node_disable_colors_1"><code>NODE_DISABLE_COLORS=1</code></a></li>
<li><a href="#cli_node_extra_ca_certs_file"><code>NODE_EXTRA_CA_CERTS=file</code></a></li>
<li><a href="#cli_node_icu_data_file"><code>NODE_ICU_DATA=file</code></a></li>
<li><a href="#cli_node_no_warnings_1"><code>NODE_NO_WARNINGS=1</code></a></li>
<li><a href="#cli_node_options_options"><code>NODE_OPTIONS=options...</code></a></li>
<li><a href="#cli_node_path_path"><code>NODE_PATH=path[:…]</code></a></li>
<li><a href="#cli_node_pending_deprecation_1"><code>NODE_PENDING_DEPRECATION=1</code></a></li>
<li><a href="#cli_node_pending_pipe_instances_instances"><code>NODE_PENDING_PIPE_INSTANCES=instances</code></a></li>
<li><a href="#cli_node_preserve_symlinks_1"><code>NODE_PRESERVE_SYMLINKS=1</code></a></li>
<li><a href="#cli_node_redirect_warnings_file"><code>NODE_REDIRECT_WARNINGS=file</code></a></li>
<li><a href="#cli_node_repl_history_file"><code>NODE_REPL_HISTORY=file</code></a></li>
<li><a href="#cli_node_repl_external_module_file"><code>NODE_REPL_EXTERNAL_MODULE=file</code></a></li>
<li><a href="#cli_node_tls_reject_unauthorized_value"><code>NODE_TLS_REJECT_UNAUTHORIZED=value</code></a></li>
<li>
<p><a href="#cli_node_v8_coverage_dir"><code>NODE_V8_COVERAGE=dir</code></a></p>
<ul>
<li><a href="#cli_coverage_output">Coverage output</a></li>
<li><a href="#cli_source_map_cache">Source map cache</a></li>
</ul>
</li>
<li><a href="#cli_openssl_conf_file"><code>OPENSSL_CONF=file</code></a></li>
<li><a href="#cli_ssl_cert_dir_dir"><code>SSL_CERT_DIR=dir</code></a></li>
<li><a href="#cli_ssl_cert_file_file"><code>SSL_CERT_FILE=file</code></a></li>
<li><a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE=size</code></a></li>
</ul>
</li>
<li>
<p><a href="#cli_useful_v8_options">Useful V8 options</a></p>
<ul>
<li><a href="#cli_max_old_space_size_size_in_megabytes"><code>--max-old-space-size=SIZE</code> (in megabytes)</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#console_console">Console</a></span></p>
<ul>
<li>
<p><a href="#console_class_console">Class: <code>Console</code></a></p>
<ul>
<li><a href="#console_new_console_stdout_stderr_ignoreerrors"><code>new Console(stdout[, stderr][, ignoreErrors])</code></a></li>
<li><a href="#console_new_console_options"><code>new Console(options)</code></a></li>
<li><a href="#console_console_assert_value_message"><code>console.assert(value[, ...message])</code></a></li>
<li><a href="#console_console_clear"><code>console.clear()</code></a></li>
<li><a href="#console_console_count_label"><code>console.count([label])</code></a></li>
<li><a href="#console_console_countreset_label"><code>console.countReset([label])</code></a></li>
<li><a href="#console_console_debug_data_args"><code>console.debug(data[, ...args])</code></a></li>
<li><a href="#console_console_dir_obj_options"><code>console.dir(obj[, options])</code></a></li>
<li><a href="#console_console_dirxml_data"><code>console.dirxml(...data)</code></a></li>
<li><a href="#console_console_error_data_args"><code>console.error([data][, ...args])</code></a></li>
<li><a href="#console_console_group_label"><code>console.group([...label])</code></a></li>
<li><a href="#console_console_groupcollapsed"><code>console.groupCollapsed()</code></a></li>
<li><a href="#console_console_groupend"><code>console.groupEnd()</code></a></li>
<li><a href="#console_console_info_data_args"><code>console.info([data][, ...args])</code></a></li>
<li><a href="#console_console_log_data_args"><code>console.log([data][, ...args])</code></a></li>
<li><a href="#console_console_table_tabulardata_properties"><code>console.table(tabularData[, properties])</code></a></li>
<li><a href="#console_console_time_label"><code>console.time([label])</code></a></li>
<li><a href="#console_console_timeend_label"><code>console.timeEnd([label])</code></a></li>
<li><a href="#console_console_timelog_label_data"><code>console.timeLog([label][, ...data])</code></a></li>
<li><a href="#console_console_trace_message_args"><code>console.trace([message][, ...args])</code></a></li>
<li><a href="#console_console_warn_data_args"><code>console.warn([data][, ...args])</code></a></li>
</ul>
</li>
<li>
<p><a href="#console_inspector_only_methods">Inspector only methods</a></p>
<ul>
<li><a href="#console_console_profile_label"><code>console.profile([label])</code></a></li>
<li><a href="#console_console_profileend_label"><code>console.profileEnd([label])</code></a></li>
<li><a href="#console_console_timestamp_label"><code>console.timeStamp([label])</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#crypto_crypto">Crypto</a></span></p>
<ul>
<li><a href="#crypto_determining_if_crypto_support_is_unavailable">Determining if crypto support is unavailable</a></li>
<li>
<p><a href="#crypto_class_certificate">Class: <code>Certificate</code></a></p>
<ul>
<li><a href="#crypto_certificate_exportchallenge_spkac"><code>Certificate.exportChallenge(spkac)</code></a></li>
<li><a href="#crypto_certificate_exportpublickey_spkac_encoding"><code>Certificate.exportPublicKey(spkac[, encoding])</code></a></li>
<li><a href="#crypto_certificate_verifyspkac_spkac"><code>Certificate.verifySpkac(spkac)</code></a></li>
<li>
<p><a href="#crypto_legacy_api">Legacy API</a></p>
<ul>
<li><a href="#crypto_new_crypto_certificate"><code>new crypto.Certificate()</code></a></li>
<li><a href="#crypto_certificate_exportchallenge_spkac_1"><code>certificate.exportChallenge(spkac)</code></a></li>
<li><a href="#crypto_certificate_exportpublickey_spkac"><code>certificate.exportPublicKey(spkac)</code></a></li>
<li><a href="#crypto_certificate_verifyspkac_spkac_1"><code>certificate.verifySpkac(spkac)</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#crypto_class_cipher">Class: <code>Cipher</code></a></p>
<ul>
<li><a href="#crypto_cipher_final_outputencoding"><code>cipher.final([outputEncoding])</code></a></li>
<li><a href="#crypto_cipher_setaad_buffer_options"><code>cipher.setAAD(buffer[, options])</code></a></li>
<li><a href="#crypto_cipher_getauthtag"><code>cipher.getAuthTag()</code></a></li>
<li><a href="#crypto_cipher_setautopadding_autopadding"><code>cipher.setAutoPadding([autoPadding])</code></a></li>
<li><a href="#crypto_cipher_update_data_inputencoding_outputencoding"><code>cipher.update(data[, inputEncoding][, outputEncoding])</code></a></li>
</ul>
</li>
<li>
<p><a href="#crypto_class_decipher">Class: <code>Decipher</code></a></p>
<ul>
<li><a href="#crypto_decipher_final_outputencoding"><code>decipher.final([outputEncoding])</code></a></li>
<li><a href="#crypto_decipher_setaad_buffer_options"><code>decipher.setAAD(buffer[, options])</code></a></li>
<li><a href="#crypto_decipher_setauthtag_buffer"><code>decipher.setAuthTag(buffer)</code></a></li>
<li><a href="#crypto_decipher_setautopadding_autopadding"><code>decipher.setAutoPadding([autoPadding])</code></a></li>
<li><a href="#crypto_decipher_update_data_inputencoding_outputencoding"><code>decipher.update(data[, inputEncoding][, outputEncoding])</code></a></li>
</ul>
</li>
<li>
<p><a href="#crypto_class_diffiehellman">Class: <code>DiffieHellman</code></a></p>
<ul>
<li><a href="#crypto_diffiehellman_computesecret_otherpublickey_inputencoding_outputencoding"><code>diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code></a></li>
<li><a href="#crypto_diffiehellman_generatekeys_encoding"><code>diffieHellman.generateKeys([encoding])</code></a></li>
<li><a href="#crypto_diffiehellman_getgenerator_encoding"><code>diffieHellman.getGenerator([encoding])</code></a></li>
<li><a href="#crypto_diffiehellman_getprime_encoding"><code>diffieHellman.getPrime([encoding])</code></a></li>
<li><a href="#crypto_diffiehellman_getprivatekey_encoding"><code>diffieHellman.getPrivateKey([encoding])</code></a></li>
<li><a href="#crypto_diffiehellman_getpublickey_encoding"><code>diffieHellman.getPublicKey([encoding])</code></a></li>
<li><a href="#crypto_diffiehellman_setprivatekey_privatekey_encoding"><code>diffieHellman.setPrivateKey(privateKey[, encoding])</code></a></li>
<li><a href="#crypto_diffiehellman_setpublickey_publickey_encoding"><code>diffieHellman.setPublicKey(publicKey[, encoding])</code></a></li>
<li><a href="#crypto_diffiehellman_verifyerror"><code>diffieHellman.verifyError</code></a></li>
</ul>
</li>
<li><a href="#crypto_class_diffiehellmangroup">Class: <code>DiffieHellmanGroup</code></a></li>
<li>
<p><a href="#crypto_class_ecdh">Class: <code>ECDH</code></a></p>
<ul>
<li><a href="#crypto_class_method_ecdh_convertkey_key_curve_inputencoding_outputencoding_format">Class Method: <code>ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])</code></a></li>
<li><a href="#crypto_ecdh_computesecret_otherpublickey_inputencoding_outputencoding"><code>ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code></a></li>
<li><a href="#crypto_ecdh_generatekeys_encoding_format"><code>ecdh.generateKeys([encoding[, format]])</code></a></li>
<li><a href="#crypto_ecdh_getprivatekey_encoding"><code>ecdh.getPrivateKey([encoding])</code></a></li>
<li><a href="#crypto_ecdh_getpublickey_encoding_format"><code>ecdh.getPublicKey([encoding][, format])</code></a></li>
<li><a href="#crypto_ecdh_setprivatekey_privatekey_encoding"><code>ecdh.setPrivateKey(privateKey[, encoding])</code></a></li>
<li><span class="stability_0"><a href="#crypto_ecdh_setpublickey_publickey_encoding"><code>ecdh.setPublicKey(publicKey[, encoding])</code></a></span></li>
</ul>
</li>
<li>
<p><a href="#crypto_class_hash">Class: <code>Hash</code></a></p>
<ul>
<li><a href="#crypto_hash_copy_options"><code>hash.copy([options])</code></a></li>
<li><a href="#crypto_hash_digest_encoding"><code>hash.digest([encoding])</code></a></li>
<li><a href="#crypto_hash_update_data_inputencoding"><code>hash.update(data[, inputEncoding])</code></a></li>
</ul>
</li>
<li>
<p><a href="#crypto_class_hmac">Class: <code>Hmac</code></a></p>
<ul>
<li><a href="#crypto_hmac_digest_encoding"><code>hmac.digest([encoding])</code></a></li>
<li><a href="#crypto_hmac_update_data_inputencoding"><code>hmac.update(data[, inputEncoding])</code></a></li>
</ul>
</li>
<li>
<p><a href="#crypto_class_keyobject">Class: <code>KeyObject</code></a></p>
<ul>
<li><a href="#crypto_keyobject_asymmetrickeytype"><code>keyObject.asymmetricKeyType</code></a></li>
<li><a href="#crypto_keyobject_export_options"><code>keyObject.export([options])</code></a></li>
<li><a href="#crypto_keyobject_symmetrickeysize"><code>keyObject.symmetricKeySize</code></a></li>
<li><a href="#crypto_keyobject_type"><code>keyObject.type</code></a></li>
</ul>
</li>
<li>
<p><a href="#crypto_class_sign">Class: <code>Sign</code></a></p>
<ul>
<li><a href="#crypto_sign_sign_privatekey_outputencoding"><code>sign.sign(privateKey[, outputEncoding])</code></a></li>
<li><a href="#crypto_sign_update_data_inputencoding"><code>sign.update(data[, inputEncoding])</code></a></li>
</ul>
</li>
<li>
<p><a href="#crypto_class_verify">Class: <code>Verify</code></a></p>
<ul>
<li><a href="#crypto_verify_update_data_inputencoding"><code>verify.update(data[, inputEncoding])</code></a></li>
<li><a href="#crypto_verify_verify_object_signature_signatureencoding"><code>verify.verify(object, signature[, signatureEncoding])</code></a></li>
</ul>
</li>
<li>
<p><a href="#crypto_crypto_module_methods_and_properties"><code>crypto</code> module methods and properties</a></p>
<ul>
<li><a href="#crypto_crypto_constants"><code>crypto.constants</code></a></li>
<li><span class="stability_0"><a href="#crypto_crypto_default_encoding"><code>crypto.DEFAULT_ENCODING</code></a></span></li>
<li><span class="stability_0"><a href="#crypto_crypto_fips"><code>crypto.fips</code></a></span></li>
<li><span class="stability_0"><a href="#crypto_crypto_createcipher_algorithm_password_options"><code>crypto.createCipher(algorithm, password[, options])</code></a></span></li>
<li><a href="#crypto_crypto_createcipheriv_algorithm_key_iv_options"><code>crypto.createCipheriv(algorithm, key, iv[, options])</code></a></li>
<li><span class="stability_0"><a href="#crypto_crypto_createdecipher_algorithm_password_options"><code>crypto.createDecipher(algorithm, password[, options])</code></a></span></li>
<li><a href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options"><code>crypto.createDecipheriv(algorithm, key, iv[, options])</code></a></li>
<li><a href="#crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding"><code>crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])</code></a></li>
<li><a href="#crypto_crypto_creatediffiehellman_primelength_generator"><code>crypto.createDiffieHellman(primeLength[, generator])</code></a></li>
<li><a href="#crypto_crypto_creatediffiehellmangroup_name"><code>crypto.createDiffieHellmanGroup(name)</code></a></li>
<li><a href="#crypto_crypto_createecdh_curvename"><code>crypto.createECDH(curveName)</code></a></li>
<li><a href="#crypto_crypto_createhash_algorithm_options"><code>crypto.createHash(algorithm[, options])</code></a></li>
<li><a href="#crypto_crypto_createhmac_algorithm_key_options"><code>crypto.createHmac(algorithm, key[, options])</code></a></li>
<li><a href="#crypto_crypto_createprivatekey_key"><code>crypto.createPrivateKey(key)</code></a></li>
<li><a href="#crypto_crypto_createpublickey_key"><code>crypto.createPublicKey(key)</code></a></li>
<li><a href="#crypto_crypto_createsecretkey_key"><code>crypto.createSecretKey(key)</code></a></li>
<li><a href="#crypto_crypto_createsign_algorithm_options"><code>crypto.createSign(algorithm[, options])</code></a></li>
<li><a href="#crypto_crypto_createverify_algorithm_options"><code>crypto.createVerify(algorithm[, options])</code></a></li>
<li><a href="#crypto_crypto_diffiehellman_options"><code>crypto.diffieHellman(options)</code></a></li>
<li><a href="#crypto_crypto_generatekeypair_type_options_callback"><code>crypto.generateKeyPair(type, options, callback)</code></a></li>
<li><a href="#crypto_crypto_generatekeypairsync_type_options"><code>crypto.generateKeyPairSync(type, options)</code></a></li>
<li><a href="#crypto_crypto_getciphers"><code>crypto.getCiphers()</code></a></li>
<li><a href="#crypto_crypto_getcurves"><code>crypto.getCurves()</code></a></li>
<li><a href="#crypto_crypto_getdiffiehellman_groupname"><code>crypto.getDiffieHellman(groupName)</code></a></li>
<li><a href="#crypto_crypto_getfips"><code>crypto.getFips()</code></a></li>
<li><a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a></li>
<li><a href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback"><code>crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)</code></a></li>
<li><a href="#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest"><code>crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)</code></a></li>
<li><a href="#crypto_crypto_privatedecrypt_privatekey_buffer"><code>crypto.privateDecrypt(privateKey, buffer)</code></a></li>
<li><a href="#crypto_crypto_privateencrypt_privatekey_buffer"><code>crypto.privateEncrypt(privateKey, buffer)</code></a></li>
<li><a href="#crypto_crypto_publicdecrypt_key_buffer"><code>crypto.publicDecrypt(key, buffer)</code></a></li>
<li><a href="#crypto_crypto_publicencrypt_key_buffer"><code>crypto.publicEncrypt(key, buffer)</code></a></li>
<li><a href="#crypto_crypto_randombytes_size_callback"><code>crypto.randomBytes(size[, callback])</code></a></li>
<li><a href="#crypto_crypto_randomfillsync_buffer_offset_size"><code>crypto.randomFillSync(buffer[, offset][, size])</code></a></li>
<li><a href="#crypto_crypto_randomfill_buffer_offset_size_callback"><code>crypto.randomFill(buffer[, offset][, size], callback)</code></a></li>
<li><a href="#crypto_crypto_scrypt_password_salt_keylen_options_callback"><code>crypto.scrypt(password, salt, keylen[, options], callback)</code></a></li>
<li><a href="#crypto_crypto_scryptsync_password_salt_keylen_options"><code>crypto.scryptSync(password, salt, keylen[, options])</code></a></li>
<li><a href="#crypto_crypto_setengine_engine_flags"><code>crypto.setEngine(engine[, flags])</code></a></li>
<li><a href="#crypto_crypto_setfips_bool"><code>crypto.setFips(bool)</code></a></li>
<li><a href="#crypto_crypto_sign_algorithm_data_key"><code>crypto.sign(algorithm, data, key)</code></a></li>
<li><a href="#crypto_crypto_timingsafeequal_a_b"><code>crypto.timingSafeEqual(a, b)</code></a></li>
<li><a href="#crypto_crypto_verify_algorithm_data_key_signature"><code>crypto.verify(algorithm, data, key, signature)</code></a></li>
</ul>
</li>
<li>
<p><a href="#crypto_notes">Notes</a></p>
<ul>
<li><a href="#crypto_legacy_streams_api_prior_to_node_js_0_10">Legacy Streams API (prior to Node.js 0.10)</a></li>
<li><a href="#crypto_recent_ecdh_changes">Recent ECDH changes</a></li>
<li><a href="#crypto_support_for_weak_or_compromised_algorithms">Support for weak or compromised algorithms</a></li>
<li><a href="#crypto_ccm_mode">CCM mode</a></li>
</ul>
</li>
<li>
<p><a href="#crypto_crypto_constants_1">Crypto constants</a></p>
<ul>
<li><a href="#crypto_openssl_options">OpenSSL options</a></li>
<li><a href="#crypto_openssl_engine_constants">OpenSSL engine constants</a></li>
<li><a href="#crypto_other_openssl_constants">Other OpenSSL constants</a></li>
<li><a href="#crypto_node_js_crypto_constants">Node.js crypto constants</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#debugger_debugger">Debugger</a></span></p>
<ul>
<li><a href="#debugger_watchers">Watchers</a></li>
<li>
<p><a href="#debugger_command_reference">Command reference</a></p>
<ul>
<li><a href="#debugger_stepping">Stepping</a></li>
<li><a href="#debugger_breakpoints">Breakpoints</a></li>
<li><a href="#debugger_information">Information</a></li>
<li><a href="#debugger_execution_control">Execution control</a></li>
<li><a href="#debugger_various">Various</a></li>
</ul>
</li>
<li>
<p><a href="#debugger_advanced_usage">Advanced usage</a></p>
<ul>
<li><a href="#debugger_v8_inspector_integration_for_node_js">V8 inspector integration for Node.js</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#deprecations_deprecated_apis">Deprecated APIs</a></p>
<ul>
<li><a href="#deprecations_revoking_deprecations">Revoking deprecations</a></li>
<li>
<p><a href="#deprecations_list_of_deprecated_apis">List of deprecated APIs</a></p>
<ul>
<li><a href="#deprecations_dep0001_http_outgoingmessage_prototype_flush">DEP0001: <code>http.OutgoingMessage.prototype.flush</code></a></li>
<li><a href="#deprecations_dep0002_require_linklist">DEP0002: <code>require('_linklist')</code></a></li>
<li><a href="#deprecations_dep0003_writablestate_buffer">DEP0003: <code>_writableState.buffer</code></a></li>
<li><a href="#deprecations_dep0004_cryptostream_prototype_readystate">DEP0004: <code>CryptoStream.prototype.readyState</code></a></li>
<li><a href="#deprecations_dep0005_buffer_constructor">DEP0005: <code>Buffer()</code> constructor</a></li>
<li><a href="#deprecations_dep0006_child_process_options_customfds">DEP0006: <code>child_process</code> <code>options.customFds</code></a></li>
<li><a href="#deprecations_dep0007_replace_cluster_worker_suicide_with_worker_exitedafterdisconnect">DEP0007: Replace <code>cluster</code> <code>worker.suicide</code> with <code>worker.exitedAfterDisconnect</code></a></li>
<li><a href="#deprecations_dep0008_require_constants">DEP0008: <code>require('constants')</code></a></li>
<li><a href="#deprecations_dep0009_crypto_pbkdf2_without_digest">DEP0009: <code>crypto.pbkdf2</code> without digest</a></li>
<li><a href="#deprecations_dep0010_crypto_createcredentials">DEP0010: <code>crypto.createCredentials</code></a></li>
<li><a href="#deprecations_dep0011_crypto_credentials">DEP0011: <code>crypto.Credentials</code></a></li>
<li><a href="#deprecations_dep0012_domain_dispose">DEP0012: <code>Domain.dispose</code></a></li>
<li><a href="#deprecations_dep0013_fs_asynchronous_function_without_callback">DEP0013: <code>fs</code> asynchronous function without callback</a></li>
<li><a href="#deprecations_dep0014_fs_read_legacy_string_interface">DEP0014: <code>fs.read</code> legacy String interface</a></li>
<li><a href="#deprecations_dep0015_fs_readsync_legacy_string_interface">DEP0015: <code>fs.readSync</code> legacy String interface</a></li>
<li><a href="#deprecations_dep0016_global_root">DEP0016: <code>GLOBAL</code>/<code>root</code></a></li>
<li><a href="#deprecations_dep0017_intl_v8breakiterator">DEP0017: <code>Intl.v8BreakIterator</code></a></li>
<li><a href="#deprecations_dep0018_unhandled_promise_rejections">DEP0018: Unhandled promise rejections</a></li>
<li><a href="#deprecations_dep0019_require_resolved_outside_directory">DEP0019: <code>require('.')</code> resolved outside directory</a></li>
<li><a href="#deprecations_dep0020_server_connections">DEP0020: <code>Server.connections</code></a></li>
<li><a href="#deprecations_dep0021_server_listenfd">DEP0021: <code>Server.listenFD</code></a></li>
<li><a href="#deprecations_dep0022_os_tmpdir">DEP0022: <code>os.tmpDir()</code></a></li>
<li><a href="#deprecations_dep0023_os_getnetworkinterfaces">DEP0023: <code>os.getNetworkInterfaces()</code></a></li>
<li><a href="#deprecations_dep0024_replserver_prototype_converttocontext">DEP0024: <code>REPLServer.prototype.convertToContext()</code></a></li>
<li><a href="#deprecations_dep0025_require_sys">DEP0025: <code>require('sys')</code></a></li>
<li><a href="#deprecations_dep0026_util_print">DEP0026: <code>util.print()</code></a></li>
<li><a href="#deprecations_dep0027_util_puts">DEP0027: <code>util.puts()</code></a></li>
<li><a href="#deprecations_dep0028_util_debug">DEP0028: <code>util.debug()</code></a></li>
<li><a href="#deprecations_dep0029_util_error">DEP0029: <code>util.error()</code></a></li>
<li><a href="#deprecations_dep0030_slowbuffer">DEP0030: <code>SlowBuffer</code></a></li>
<li><a href="#deprecations_dep0031_ecdh_setpublickey">DEP0031: <code>ecdh.setPublicKey()</code></a></li>
<li><a href="#deprecations_dep0032_domain_module">DEP0032: <code>domain</code> module</a></li>
<li><a href="#deprecations_dep0033_eventemitter_listenercount">DEP0033: <code>EventEmitter.listenerCount()</code></a></li>
<li><a href="#deprecations_dep0034_fs_exists_path_callback">DEP0034: <code>fs.exists(path, callback)</code></a></li>
<li><a href="#deprecations_dep0035_fs_lchmod_path_mode_callback">DEP0035: <code>fs.lchmod(path, mode, callback)</code></a></li>
<li><a href="#deprecations_dep0036_fs_lchmodsync_path_mode">DEP0036: <code>fs.lchmodSync(path, mode)</code></a></li>
<li><a href="#deprecations_dep0037_fs_lchown_path_uid_gid_callback">DEP0037: <code>fs.lchown(path, uid, gid, callback)</code></a></li>
<li><a href="#deprecations_dep0038_fs_lchownsync_path_uid_gid">DEP0038: <code>fs.lchownSync(path, uid, gid)</code></a></li>
<li><a href="#deprecations_dep0039_require_extensions">DEP0039: <code>require.extensions</code></a></li>
<li><a href="#deprecations_dep0040_punycode_module">DEP0040: <code>punycode</code> module</a></li>
<li><a href="#deprecations_dep0041_node_repl_history_file_environment_variable">DEP0041: <code>NODE_REPL_HISTORY_FILE</code> environment variable</a></li>
<li><a href="#deprecations_dep0042_tls_cryptostream">DEP0042: <code>tls.CryptoStream</code></a></li>
<li><a href="#deprecations_dep0043_tls_securepair">DEP0043: <code>tls.SecurePair</code></a></li>
<li><a href="#deprecations_dep0044_util_isarray">DEP0044: <code>util.isArray()</code></a></li>
<li><a href="#deprecations_dep0045_util_isboolean">DEP0045: <code>util.isBoolean()</code></a></li>
<li><a href="#deprecations_dep0046_util_isbuffer">DEP0046: <code>util.isBuffer()</code></a></li>
<li><a href="#deprecations_dep0047_util_isdate">DEP0047: <code>util.isDate()</code></a></li>
<li><a href="#deprecations_dep0048_util_iserror">DEP0048: <code>util.isError()</code></a></li>
<li><a href="#deprecations_dep0049_util_isfunction">DEP0049: <code>util.isFunction()</code></a></li>
<li><a href="#deprecations_dep0050_util_isnull">DEP0050: <code>util.isNull()</code></a></li>
<li><a href="#deprecations_dep0051_util_isnullorundefined">DEP0051: <code>util.isNullOrUndefined()</code></a></li>
<li><a href="#deprecations_dep0052_util_isnumber">DEP0052: <code>util.isNumber()</code></a></li>
<li><a href="#deprecations_dep0053_util_isobject">DEP0053 <code>util.isObject()</code></a></li>
<li><a href="#deprecations_dep0054_util_isprimitive">DEP0054: <code>util.isPrimitive()</code></a></li>
<li><a href="#deprecations_dep0055_util_isregexp">DEP0055: <code>util.isRegExp()</code></a></li>
<li><a href="#deprecations_dep0056_util_isstring">DEP0056: <code>util.isString()</code></a></li>
<li><a href="#deprecations_dep0057_util_issymbol">DEP0057: <code>util.isSymbol()</code></a></li>
<li><a href="#deprecations_dep0058_util_isundefined">DEP0058: <code>util.isUndefined()</code></a></li>
<li><a href="#deprecations_dep0059_util_log">DEP0059: <code>util.log()</code></a></li>
<li><a href="#deprecations_dep0060_util_extend">DEP0060: <code>util._extend()</code></a></li>
<li><a href="#deprecations_dep0061_fs_syncwritestream">DEP0061: <code>fs.SyncWriteStream</code></a></li>
<li><a href="#deprecations_dep0062_node_debug">DEP0062: <code>node --debug</code></a></li>
<li><a href="#deprecations_dep0063_serverresponse_prototype_writeheader">DEP0063: <code>ServerResponse.prototype.writeHeader()</code></a></li>
<li><a href="#deprecations_dep0064_tls_createsecurepair">DEP0064: <code>tls.createSecurePair()</code></a></li>
<li><a href="#deprecations_dep0065_repl_repl_mode_magic_and_node_repl_mode_magic">DEP0065: <code>repl.REPL_MODE_MAGIC</code> and <code>NODE_REPL_MODE=magic</code></a></li>
<li><a href="#deprecations_dep0066_outgoingmessage_prototype_headers_outgoingmessage_prototype_headernames">DEP0066: <code>OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames</code></a></li>
<li><a href="#deprecations_dep0067_outgoingmessage_prototype_renderheaders">DEP0067: <code>OutgoingMessage.prototype._renderHeaders</code></a></li>
<li><a href="#deprecations_dep0068_node_debug">DEP0068: <code>node debug</code></a></li>
<li><a href="#deprecations_dep0069_vm_runindebugcontext_string">DEP0069: <code>vm.runInDebugContext(string)</code></a></li>
<li><a href="#deprecations_dep0070_async_hooks_currentid">DEP0070: <code>async_hooks.currentId()</code></a></li>
<li><a href="#deprecations_dep0071_async_hooks_triggerid">DEP0071: <code>async_hooks.triggerId()</code></a></li>
<li><a href="#deprecations_dep0072_async_hooks_asyncresource_triggerid">DEP0072: <code>async_hooks.AsyncResource.triggerId()</code></a></li>
<li><a href="#deprecations_dep0073_several_internal_properties_of_net_server">DEP0073: Several internal properties of <code>net.Server</code></a></li>
<li><a href="#deprecations_dep0074_replserver_bufferedcommand">DEP0074: <code>REPLServer.bufferedCommand</code></a></li>
<li><a href="#deprecations_dep0075_replserver_parsereplkeyword">DEP0075: <code>REPLServer.parseREPLKeyword()</code></a></li>
<li><a href="#deprecations_dep0076_tls_parsecertstring">DEP0076: <code>tls.parseCertString()</code></a></li>
<li><a href="#deprecations_dep0077_module_debug">DEP0077: <code>Module._debug()</code></a></li>
<li><a href="#deprecations_dep0078_replserver_turnoffeditormode">DEP0078: <code>REPLServer.turnOffEditorMode()</code></a></li>
<li><a href="#deprecations_dep0079_custom_inspection_function_on_objects_via_inspect">DEP0079: Custom inspection function on objects via <code>.inspect()</code></a></li>
<li><a href="#deprecations_dep0080_path_makelong">DEP0080: <code>path._makeLong()</code></a></li>
<li><a href="#deprecations_dep0081_fs_truncate_using_a_file_descriptor">DEP0081: <code>fs.truncate()</code> using a file descriptor</a></li>
<li><a href="#deprecations_dep0082_replserver_prototype_memory">DEP0082: <code>REPLServer.prototype.memory()</code></a></li>
<li><a href="#deprecations_dep0083_disabling_ecdh_by_setting_ecdhcurve_to_false">DEP0083: Disabling ECDH by setting <code>ecdhCurve</code> to <code>false</code></a></li>
<li><a href="#deprecations_dep0084_requiring_bundled_internal_dependencies">DEP0084: requiring bundled internal dependencies</a></li>
<li><a href="#deprecations_dep0085_asynchooks_sensitive_api">DEP0085: AsyncHooks sensitive API</a></li>
<li><a href="#deprecations_dep0086_remove_runinasyncidscope">DEP0086: Remove <code>runInAsyncIdScope</code></a></li>
<li><a href="#deprecations_dep0089_require_assert">DEP0089: <code>require('assert')</code></a></li>
<li><a href="#deprecations_dep0090_invalid_gcm_authentication_tag_lengths">DEP0090: Invalid GCM authentication tag lengths</a></li>
<li><a href="#deprecations_dep0091_crypto_default_encoding">DEP0091: <code>crypto.DEFAULT_ENCODING</code></a></li>
<li><a href="#deprecations_dep0092_top_level_this_bound_to_module_exports">DEP0092: Top-level <code>this</code> bound to <code>module.exports</code></a></li>
<li><a href="#deprecations_dep0093_crypto_fips_is_deprecated_and_replaced">DEP0093: <code>crypto.fips</code> is deprecated and replaced.</a></li>
<li><a href="#deprecations_dep0094_using_assert_fail_with_more_than_one_argument">DEP0094: Using <code>assert.fail()</code> with more than one argument.</a></li>
<li><a href="#deprecations_dep0095_timers_enroll">DEP0095: <code>timers.enroll()</code></a></li>
<li><a href="#deprecations_dep0096_timers_unenroll">DEP0096: <code>timers.unenroll()</code></a></li>
<li><a href="#deprecations_dep0097_makecallback_with_domain_property">DEP0097: <code>MakeCallback</code> with <code>domain</code> property</a></li>
<li><a href="#deprecations_dep0098_asynchooks_embedder_asyncresource_emitbefore_and_asyncresource_emitafter_apis">DEP0098: AsyncHooks embedder <code>AsyncResource.emitBefore</code> and <code>AsyncResource.emitAfter</code> APIs</a></li>
<li><a href="#deprecations_dep0099_async_context_unaware_node_makecallback_c_apis">DEP0099: Async context-unaware <code>node::MakeCallback</code> C++ APIs</a></li>
<li><a href="#deprecations_dep0100_process_assert">DEP0100: <code>process.assert()</code></a></li>
<li><a href="#deprecations_dep0101_with_lttng">DEP0101: <code>--with-lttng</code></a></li>
<li><a href="#deprecations_dep0102_using_noassert_in_buffer_read_write_operations">DEP0102: Using <code>noAssert</code> in <code>Buffer#(read|write)</code> operations.</a></li>
<li><a href="#deprecations_dep0103_process_binding_util_is_typechecks">DEP0103: <code>process.binding('util').is[...]</code> typechecks</a></li>
<li><a href="#deprecations_dep0104_process_env_string_coercion">DEP0104: <code>process.env</code> string coercion</a></li>
<li><a href="#deprecations_dep0105_decipher_finaltol">DEP0105: <code>decipher.finaltol</code></a></li>
<li><a href="#deprecations_dep0106_crypto_createcipher_and_crypto_createdecipher">DEP0106: <code>crypto.createCipher</code> and <code>crypto.createDecipher</code></a></li>
<li><a href="#deprecations_dep0107_tls_convertnpnprotocols">DEP0107: <code>tls.convertNPNProtocols()</code></a></li>
<li><a href="#deprecations_dep0108_zlib_bytesread">DEP0108: <code>zlib.bytesRead</code></a></li>
<li><a href="#deprecations_dep0109_http_https_and_tls_support_for_invalid_urls">DEP0109: <code>http</code>, <code>https</code>, and <code>tls</code> support for invalid URLs</a></li>
<li><a href="#deprecations_dep0110_vm_script_cached_data">DEP0110: <code>vm.Script</code> cached data</a></li>
<li><a href="#deprecations_dep0111_process_binding">DEP0111: <code>process.binding()</code></a></li>
<li><a href="#deprecations_dep0112_dgram_private_apis">DEP0112: <code>dgram</code> private APIs</a></li>
<li><a href="#deprecations_dep0113_cipher_setauthtag_decipher_getauthtag">DEP0113: <code>Cipher.setAuthTag()</code>, <code>Decipher.getAuthTag()</code></a></li>
<li><a href="#deprecations_dep0114_crypto_tobuf">DEP0114: <code>crypto._toBuf()</code></a></li>
<li><a href="#deprecations_dep0115_crypto_prng_crypto_pseudorandombytes_crypto_rng">DEP0115: <code>crypto.prng()</code>, <code>crypto.pseudoRandomBytes()</code>, <code>crypto.rng()</code></a></li>
<li><a href="#deprecations_dep0116_legacy_url_api">DEP0116: Legacy URL API</a></li>
<li><a href="#deprecations_dep0117_native_crypto_handles">DEP0117: Native crypto handles</a></li>
<li><a href="#deprecations_dep0118_dns_lookup_support_for_a_falsy_host_name">DEP0118: <code>dns.lookup()</code> support for a falsy host name</a></li>
<li><a href="#deprecations_dep0119_process_binding_uv_errname_private_api">DEP0119: <code>process.binding('uv').errname()</code> private API</a></li>
<li><a href="#deprecations_dep0120_windows_performance_counter_support">DEP0120: Windows Performance Counter support</a></li>
<li><a href="#deprecations_dep0121_net_setsimultaneousaccepts">DEP0121: <code>net._setSimultaneousAccepts()</code></a></li>
<li><a href="#deprecations_dep0122_tls_server_prototype_setoptions">DEP0122: <code>tls</code> <code>Server.prototype.setOptions()</code></a></li>
<li><a href="#deprecations_dep0123_setting_the_tls_servername_to_an_ip_address">DEP0123: setting the TLS ServerName to an IP address</a></li>
<li><a href="#deprecations_dep0124_using_replserver_rli">DEP0124: using <code>REPLServer.rli</code></a></li>
<li><a href="#deprecations_dep0125_require_stream_wrap">DEP0125: <code>require('_stream_wrap')</code></a></li>
<li><a href="#deprecations_dep0126_timers_active">DEP0126: <code>timers.active()</code></a></li>
<li><a href="#deprecations_dep0127_timers_unrefactive">DEP0127: <code>timers._unrefActive()</code></a></li>
<li><a href="#deprecations_dep0128_modules_with_an_invalid_main_entry_and_an_index_js_file">DEP0128: modules with an invalid <code>main</code> entry and an <code>index.js</code> file</a></li>
<li><a href="#deprecations_dep0129_childprocess_channel">DEP0129: <code>ChildProcess._channel</code></a></li>
<li><a href="#deprecations_dep0130_module_createrequirefrompath">DEP0130: <code>Module.createRequireFromPath()</code></a></li>
<li><a href="#deprecations_dep0131_legacy_http_parser">DEP0131: Legacy HTTP parser</a></li>
<li><a href="#deprecations_dep0132_worker_terminate_with_callback">DEP0132: <code>worker.terminate()</code> with callback</a></li>
<li><a href="#deprecations_dep0133_http_connection">DEP0133: <code>http</code> <code>connection</code></a></li>
<li><a href="#deprecations_dep0134_process_tickcallback">DEP0134: <code>process._tickCallback</code></a></li>
<li><a href="#deprecations_dep0136_http_finished">DEP0136: <code>http</code> <code>finished</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#dns_dns">DNS</a></span></p>
<ul>
<li>
<p><a href="#dns_class_dns_resolver">Class: <code>dns.Resolver</code></a></p>
<ul>
<li><a href="#dns_resolver_options"><code>Resolver([options])</code></a></li>
<li><a href="#dns_resolver_cancel"><code>resolver.cancel()</code></a></li>
</ul>
</li>
<li><a href="#dns_dns_getservers"><code>dns.getServers()</code></a></li>
<li>
<p><a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup(hostname[, options], callback)</code></a></p>
<ul>
<li><a href="#dns_supported_getaddrinfo_flags">Supported getaddrinfo flags</a></li>
</ul>
</li>
<li><a href="#dns_dns_lookupservice_address_port_callback"><code>dns.lookupService(address, port, callback)</code></a></li>
<li><a href="#dns_dns_resolve_hostname_rrtype_callback"><code>dns.resolve(hostname[, rrtype], callback)</code></a></li>
<li><a href="#dns_dns_resolve4_hostname_options_callback"><code>dns.resolve4(hostname[, options], callback)</code></a></li>
<li><a href="#dns_dns_resolve6_hostname_options_callback"><code>dns.resolve6(hostname[, options], callback)</code></a></li>
<li><a href="#dns_dns_resolveany_hostname_callback"><code>dns.resolveAny(hostname, callback)</code></a></li>
<li><a href="#dns_dns_resolvecname_hostname_callback"><code>dns.resolveCname(hostname, callback)</code></a></li>
<li><a href="#dns_dns_resolvemx_hostname_callback"><code>dns.resolveMx(hostname, callback)</code></a></li>
<li><a href="#dns_dns_resolvenaptr_hostname_callback"><code>dns.resolveNaptr(hostname, callback)</code></a></li>
<li><a href="#dns_dns_resolvens_hostname_callback"><code>dns.resolveNs(hostname, callback)</code></a></li>
<li><a href="#dns_dns_resolveptr_hostname_callback"><code>dns.resolvePtr(hostname, callback)</code></a></li>
<li><a href="#dns_dns_resolvesoa_hostname_callback"><code>dns.resolveSoa(hostname, callback)</code></a></li>
<li><a href="#dns_dns_resolvesrv_hostname_callback"><code>dns.resolveSrv(hostname, callback)</code></a></li>
<li><a href="#dns_dns_resolvetxt_hostname_callback"><code>dns.resolveTxt(hostname, callback)</code></a></li>
<li><a href="#dns_dns_reverse_ip_callback"><code>dns.reverse(ip, callback)</code></a></li>
<li><a href="#dns_dns_setservers_servers"><code>dns.setServers(servers)</code></a></li>
<li>
<p><a href="#dns_dns_promises_api">DNS promises API</a></p>
<ul>
<li><a href="#dns_class_dnspromises_resolver">Class: <code>dnsPromises.Resolver</code></a></li>
<li><a href="#dns_dnspromises_getservers"><code>dnsPromises.getServers()</code></a></li>
<li><a href="#dns_dnspromises_lookup_hostname_options"><code>dnsPromises.lookup(hostname[, options])</code></a></li>
<li><a href="#dns_dnspromises_lookupservice_address_port"><code>dnsPromises.lookupService(address, port)</code></a></li>
<li><a href="#dns_dnspromises_resolve_hostname_rrtype"><code>dnsPromises.resolve(hostname[, rrtype])</code></a></li>
<li><a href="#dns_dnspromises_resolve4_hostname_options"><code>dnsPromises.resolve4(hostname[, options])</code></a></li>
<li><a href="#dns_dnspromises_resolve6_hostname_options"><code>dnsPromises.resolve6(hostname[, options])</code></a></li>
<li><a href="#dns_dnspromises_resolveany_hostname"><code>dnsPromises.resolveAny(hostname)</code></a></li>
<li><a href="#dns_dnspromises_resolvecname_hostname"><code>dnsPromises.resolveCname(hostname)</code></a></li>
<li><a href="#dns_dnspromises_resolvemx_hostname"><code>dnsPromises.resolveMx(hostname)</code></a></li>
<li><a href="#dns_dnspromises_resolvenaptr_hostname"><code>dnsPromises.resolveNaptr(hostname)</code></a></li>
<li><a href="#dns_dnspromises_resolvens_hostname"><code>dnsPromises.resolveNs(hostname)</code></a></li>
<li><a href="#dns_dnspromises_resolveptr_hostname"><code>dnsPromises.resolvePtr(hostname)</code></a></li>
<li><a href="#dns_dnspromises_resolvesoa_hostname"><code>dnsPromises.resolveSoa(hostname)</code></a></li>
<li><a href="#dns_dnspromises_resolvesrv_hostname"><code>dnsPromises.resolveSrv(hostname)</code></a></li>
<li><a href="#dns_dnspromises_resolvetxt_hostname"><code>dnsPromises.resolveTxt(hostname)</code></a></li>
<li><a href="#dns_dnspromises_reverse_ip"><code>dnsPromises.reverse(ip)</code></a></li>
<li><a href="#dns_dnspromises_setservers_servers"><code>dnsPromises.setServers(servers)</code></a></li>
</ul>
</li>
<li><a href="#dns_error_codes">Error codes</a></li>
<li>
<p><a href="#dns_implementation_considerations">Implementation considerations</a></p>
<ul>
<li><a href="#dns_dns_lookup"><code>dns.lookup()</code></a></li>
<li><a href="#dns_dns_resolve_dns_resolve_and_dns_reverse"><code>dns.resolve()</code>, <code>dns.resolve*()</code> and <code>dns.reverse()</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_0"><a href="#domain_domain">Domain</a></span></p>
<ul>
<li><a href="#domain_warning_don_t_ignore_errors">Warning: Don't ignore errors!</a></li>
<li><a href="#domain_additions_to_error_objects">Additions to <code>Error</code> objects</a></li>
<li><a href="#domain_implicit_binding">Implicit binding</a></li>
<li><a href="#domain_explicit_binding">Explicit binding</a></li>
<li><a href="#domain_domain_create"><code>domain.create()</code></a></li>
<li>
<p><a href="#domain_class_domain">Class: <code>Domain</code></a></p>
<ul>
<li><a href="#domain_domain_members"><code>domain.members</code></a></li>
<li><a href="#domain_domain_add_emitter"><code>domain.add(emitter)</code></a></li>
<li><a href="#domain_domain_bind_callback"><code>domain.bind(callback)</code></a></li>
<li><a href="#domain_domain_enter"><code>domain.enter()</code></a></li>
<li><a href="#domain_domain_exit"><code>domain.exit()</code></a></li>
<li><a href="#domain_domain_intercept_callback"><code>domain.intercept(callback)</code></a></li>
<li><a href="#domain_domain_remove_emitter"><code>domain.remove(emitter)</code></a></li>
<li><a href="#domain_domain_run_fn_args"><code>domain.run(fn[, ...args])</code></a></li>
</ul>
</li>
<li><a href="#domain_domains_and_promises">Domains and promises</a></li>
</ul>
</li>
<li>
<p><span class="stability_1"><a href="#esm_ecmascript_modules">ECMAScript modules</a></span></p>
<ul>
<li><a href="#esm_introduction">Introduction</a></li>
<li>
<p><a href="#esm_enabling">Enabling</a></p>
<ul>
<li><a href="#esm_package_json_type_field"><code>package.json</code> <code>"type"</code> field</a></li>
<li><a href="#esm_package_scope_and_file_extensions">Package scope and file extensions</a></li>
<li><a href="#esm_input_type_flag"><code>--input-type</code> flag</a></li>
</ul>
</li>
<li>
<p><a href="#esm_packages">Packages</a></p>
<ul>
<li>
<p><a href="#esm_package_entry_points">Package entry points</a></p>
<ul>
<li><a href="#esm_main_entry_point_export">Main entry point export</a></li>
<li><a href="#esm_subpath_exports">Subpath exports</a></li>
<li><a href="#esm_package_exports_fallbacks">Package exports fallbacks</a></li>
<li><a href="#esm_exports_sugar">Exports sugar</a></li>
<li><a href="#esm_conditional_exports">Conditional exports</a></li>
<li><a href="#esm_nested_conditions">Nested conditions</a></li>
<li><a href="#esm_self_referencing_a_package_using_its_name">Self-referencing a package using its name</a></li>
</ul>
</li>
<li>
<p><a href="#esm_dual_commonjs_es_module_packages">Dual CommonJS/ES module packages</a></p>
<ul>
<li><a href="#esm_dual_package_hazard">Dual package hazard</a></li>
<li>
<p><a href="#esm_writing_dual_packages_while_avoiding_or_minimizing_hazards">Writing dual packages while avoiding or minimizing hazards</a></p>
<ul>
<li><a href="#esm_approach_1_use_an_es_module_wrapper">Approach #1: Use an ES module wrapper</a></li>
<li><a href="#esm_approach_2_isolate_state">Approach #2: Isolate state</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#esm_import_specifiers"><code>import</code> Specifiers</a></p>
<ul>
<li>
<p><a href="#esm_terminology">Terminology</a></p>
<ul>
<li><a href="#esm_data_imports"><code>data:</code> Imports</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#esm_import_meta"><code>import.meta</code></a></li>
<li>
<p><a href="#esm_differences_between_es_modules_and_commonjs">Differences between ES modules and CommonJS</a></p>
<ul>
<li><a href="#esm_mandatory_file_extensions">Mandatory file extensions</a></li>
<li><a href="#esm_no_node_path">No <code>NODE_PATH</code></a></li>
<li><a href="#esm_no_require_exports_module_exports_filename_dirname">No <code>require</code>, <code>exports</code>, <code>module.exports</code>, <code>__filename</code>, <code>__dirname</code></a></li>
<li><a href="#esm_no_require_resolve">No <code>require.resolve</code></a></li>
<li><a href="#esm_no_require_extensions">No <code>require.extensions</code></a></li>
<li><a href="#esm_no_require_cache">No <code>require.cache</code></a></li>
<li><a href="#esm_url_based_paths">URL-based paths</a></li>
</ul>
</li>
<li>
<p><a href="#esm_interoperability_with_commonjs">Interoperability with CommonJS</a></p>
<ul>
<li><a href="#esm_require"><code>require</code></a></li>
<li><a href="#esm_import_statements"><code>import</code> statements</a></li>
<li><a href="#esm_import_expressions"><code>import()</code> expressions</a></li>
</ul>
</li>
<li><a href="#esm_commonjs_json_and_native_modules">CommonJS, JSON, and native modules</a></li>
<li><a href="#esm_builtin_modules">Builtin modules</a></li>
<li><a href="#esm_experimental_json_modules">Experimental JSON modules</a></li>
<li><a href="#esm_experimental_wasm_modules">Experimental Wasm modules</a></li>
<li>
<p><a href="#esm_experimental_loaders">Experimental loaders</a></p>
<ul>
<li>
<p><a href="#esm_hooks">Hooks</a></p>
<ul>
<li><a href="#esm_code_resolve_code_hook"><code>resolve</code> hook</a></li>
<li><a href="#esm_code_getformat_code_hook"><code>getFormat</code> hook</a></li>
<li><a href="#esm_code_getsource_code_hook"><code>getSource</code> hook</a></li>
<li><a href="#esm_code_transformsource_code_hook"><code>transformSource</code> hook</a></li>
<li><a href="#esm_code_getglobalpreloadcode_code_hook"><code>getGlobalPreloadCode</code> hook</a></li>
<li><a href="#esm_code_dynamicinstantiate_code_hook"><code>dynamicInstantiate</code> hook</a></li>
</ul>
</li>
<li>
<p><a href="#esm_examples">Examples</a></p>
<ul>
<li><a href="#esm_https_loader">HTTPS loader</a></li>
<li><a href="#esm_transpiler_loader">Transpiler loader</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#esm_resolution_algorithm">Resolution algorithm</a></p>
<ul>
<li><a href="#esm_features">Features</a></li>
<li><a href="#esm_resolver_algorithm">Resolver algorithm</a></li>
<li><a href="#esm_customizing_esm_specifier_resolution_algorithm">Customizing ESM specifier resolution algorithm</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#errors_errors">Errors</a></p>
<ul>
<li>
<p><a href="#errors_error_propagation_and_interception">Error propagation and interception</a></p>
<ul>
<li><a href="#errors_error_first_callbacks">Error-first callbacks</a></li>
</ul>
</li>
<li>
<p><a href="#errors_class_error">Class: <code>Error</code></a></p>
<ul>
<li><a href="#errors_new_error_message"><code>new Error(message)</code></a></li>
<li><a href="#errors_error_capturestacktrace_targetobject_constructoropt"><code>Error.captureStackTrace(targetObject[, constructorOpt])</code></a></li>
<li><a href="#errors_error_stacktracelimit"><code>Error.stackTraceLimit</code></a></li>
<li><a href="#errors_error_code"><code>error.code</code></a></li>
<li><a href="#errors_error_message"><code>error.message</code></a></li>
<li><a href="#errors_error_stack"><code>error.stack</code></a></li>
</ul>
</li>
<li><a href="#errors_class_assertionerror">Class: <code>AssertionError</code></a></li>
<li><a href="#errors_class_rangeerror">Class: <code>RangeError</code></a></li>
<li><a href="#errors_class_referenceerror">Class: <code>ReferenceError</code></a></li>
<li><a href="#errors_class_syntaxerror">Class: <code>SyntaxError</code></a></li>
<li>
<p><a href="#errors_class_systemerror">Class: <code>SystemError</code></a></p>
<ul>
<li><a href="#errors_error_address"><code>error.address</code></a></li>
<li><a href="#errors_error_code_1"><code>error.code</code></a></li>
<li><a href="#errors_error_dest"><code>error.dest</code></a></li>
<li><a href="#errors_error_errno"><code>error.errno</code></a></li>
<li><a href="#errors_error_info"><code>error.info</code></a></li>
<li><a href="#errors_error_message_1"><code>error.message</code></a></li>
<li><a href="#errors_error_path"><code>error.path</code></a></li>
<li><a href="#errors_error_port"><code>error.port</code></a></li>
<li><a href="#errors_error_syscall"><code>error.syscall</code></a></li>
<li><a href="#errors_common_system_errors">Common system errors</a></li>
</ul>
</li>
<li><a href="#errors_class_typeerror">Class: <code>TypeError</code></a></li>
<li><a href="#errors_exceptions_vs_errors">Exceptions vs. errors</a></li>
<li>
<p><a href="#errors_openssl_errors">OpenSSL errors</a></p>
<ul>
<li><a href="#errors_error_opensslerrorstack"><code>error.opensslErrorStack</code></a></li>
<li><a href="#errors_error_function"><code>error.function</code></a></li>
<li><a href="#errors_error_library"><code>error.library</code></a></li>
<li><a href="#errors_error_reason"><code>error.reason</code></a></li>
</ul>
</li>
<li>
<p><a href="#errors_node_js_error_codes">Node.js error codes</a></p>
<ul>
<li><a href="#errors_err_ambiguous_argument"><code>ERR_AMBIGUOUS_ARGUMENT</code></a></li>
<li><a href="#errors_err_arg_not_iterable"><code>ERR_ARG_NOT_ITERABLE</code></a></li>
<li><a href="#errors_err_assertion"><code>ERR_ASSERTION</code></a></li>
<li><a href="#errors_err_async_callback"><code>ERR_ASYNC_CALLBACK</code></a></li>
<li><a href="#errors_err_async_type"><code>ERR_ASYNC_TYPE</code></a></li>
<li><a href="#errors_err_brotli_compression_failed"><code>ERR_BROTLI_COMPRESSION_FAILED</code></a></li>
<li><a href="#errors_err_brotli_invalid_param"><code>ERR_BROTLI_INVALID_PARAM</code></a></li>
<li><a href="#errors_err_buffer_context_not_available"><code>ERR_BUFFER_CONTEXT_NOT_AVAILABLE</code></a></li>
<li><a href="#errors_err_buffer_out_of_bounds"><code>ERR_BUFFER_OUT_OF_BOUNDS</code></a></li>
<li><a href="#errors_err_buffer_too_large"><code>ERR_BUFFER_TOO_LARGE</code></a></li>
<li><a href="#errors_err_cannot_watch_sigint"><code>ERR_CANNOT_WATCH_SIGINT</code></a></li>
<li><a href="#errors_err_child_closed_before_reply"><code>ERR_CHILD_CLOSED_BEFORE_REPLY</code></a></li>
<li><a href="#errors_err_child_process_ipc_required"><code>ERR_CHILD_PROCESS_IPC_REQUIRED</code></a></li>
<li><a href="#errors_err_child_process_stdio_maxbuffer"><code>ERR_CHILD_PROCESS_STDIO_MAXBUFFER</code></a></li>
<li><a href="#errors_err_console_writable_stream"><code>ERR_CONSOLE_WRITABLE_STREAM</code></a></li>
<li><a href="#errors_err_construct_call_required"><code>ERR_CONSTRUCT_CALL_REQUIRED</code></a></li>
<li><a href="#errors_err_construct_call_invalid"><code>ERR_CONSTRUCT_CALL_INVALID</code></a></li>
<li><a href="#errors_err_cpu_usage"><code>ERR_CPU_USAGE</code></a></li>
<li><a href="#errors_err_crypto_custom_engine_not_supported"><code>ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED</code></a></li>
<li><a href="#errors_err_crypto_ecdh_invalid_format"><code>ERR_CRYPTO_ECDH_INVALID_FORMAT</code></a></li>
<li><a href="#errors_err_crypto_ecdh_invalid_public_key"><code>ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY</code></a></li>
<li><a href="#errors_err_crypto_engine_unknown"><code>ERR_CRYPTO_ENGINE_UNKNOWN</code></a></li>
<li><a href="#errors_err_crypto_fips_forced"><code>ERR_CRYPTO_FIPS_FORCED</code></a></li>
<li><a href="#errors_err_crypto_fips_unavailable"><code>ERR_CRYPTO_FIPS_UNAVAILABLE</code></a></li>
<li><a href="#errors_err_crypto_hash_finalized"><code>ERR_CRYPTO_HASH_FINALIZED</code></a></li>
<li><a href="#errors_err_crypto_hash_update_failed"><code>ERR_CRYPTO_HASH_UPDATE_FAILED</code></a></li>
<li><a href="#errors_err_crypto_incompatible_key"><code>ERR_CRYPTO_INCOMPATIBLE_KEY</code></a></li>
<li><a href="#errors_err_crypto_incompatible_key_options"><code>ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS</code></a></li>
<li><a href="#errors_err_crypto_invalid_digest"><code>ERR_CRYPTO_INVALID_DIGEST</code></a></li>
<li><a href="#errors_err_crypto_invalid_key_object_type"><code>ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE</code></a></li>
<li><a href="#errors_err_crypto_invalid_state"><code>ERR_CRYPTO_INVALID_STATE</code></a></li>
<li><a href="#errors_err_crypto_pbkdf2_error"><code>ERR_CRYPTO_PBKDF2_ERROR</code></a></li>
<li><a href="#errors_err_crypto_scrypt_invalid_parameter"><code>ERR_CRYPTO_SCRYPT_INVALID_PARAMETER</code></a></li>
<li><a href="#errors_err_crypto_scrypt_not_supported"><code>ERR_CRYPTO_SCRYPT_NOT_SUPPORTED</code></a></li>
<li><a href="#errors_err_crypto_sign_key_required"><code>ERR_CRYPTO_SIGN_KEY_REQUIRED</code></a></li>
<li><a href="#errors_err_crypto_timing_safe_equal_length"><code>ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH</code></a></li>
<li><a href="#errors_err_crypto_unknown_cipher"><code>ERR_CRYPTO_UNKNOWN_CIPHER</code></a></li>
<li><a href="#errors_err_crypto_unknown_dh_group"><code>ERR_CRYPTO_UNKNOWN_DH_GROUP</code></a></li>
<li><a href="#errors_err_dir_closed"><code>ERR_DIR_CLOSED</code></a></li>
<li><a href="#errors_err_dir_concurrent_operation"><code>ERR_DIR_CONCURRENT_OPERATION</code></a></li>
<li><a href="#errors_err_dns_set_servers_failed"><code>ERR_DNS_SET_SERVERS_FAILED</code></a></li>
<li><a href="#errors_err_domain_callback_not_available"><code>ERR_DOMAIN_CALLBACK_NOT_AVAILABLE</code></a></li>
<li><a href="#errors_err_domain_cannot_set_uncaught_exception_capture"><code>ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</code></a></li>
<li><a href="#errors_err_encoding_invalid_encoded_data"><code>ERR_ENCODING_INVALID_ENCODED_DATA</code></a></li>
<li><a href="#errors_err_encoding_not_supported"><code>ERR_ENCODING_NOT_SUPPORTED</code></a></li>
<li><a href="#errors_err_execution_environment_not_available"><code>ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE</code></a></li>
<li><a href="#errors_err_falsy_value_rejection"><code>ERR_FALSY_VALUE_REJECTION</code></a></li>
<li><a href="#errors_err_fs_file_too_large"><code>ERR_FS_FILE_TOO_LARGE</code></a></li>
<li><a href="#errors_err_fs_invalid_symlink_type"><code>ERR_FS_INVALID_SYMLINK_TYPE</code></a></li>
<li><a href="#errors_err_http_headers_sent"><code>ERR_HTTP_HEADERS_SENT</code></a></li>
<li><a href="#errors_err_http_invalid_header_value"><code>ERR_HTTP_INVALID_HEADER_VALUE</code></a></li>
<li><a href="#errors_err_http_invalid_status_code"><code>ERR_HTTP_INVALID_STATUS_CODE</code></a></li>
<li><a href="#errors_err_http_trailer_invalid"><code>ERR_HTTP_TRAILER_INVALID</code></a></li>
<li><a href="#errors_err_http2_altsvc_invalid_origin"><code>ERR_HTTP2_ALTSVC_INVALID_ORIGIN</code></a></li>
<li><a href="#errors_err_http2_altsvc_length"><code>ERR_HTTP2_ALTSVC_LENGTH</code></a></li>
<li><a href="#errors_err_http2_connect_authority"><code>ERR_HTTP2_CONNECT_AUTHORITY</code></a></li>
<li><a href="#errors_err_http2_connect_path"><code>ERR_HTTP2_CONNECT_PATH</code></a></li>
<li><a href="#errors_err_http2_connect_scheme"><code>ERR_HTTP2_CONNECT_SCHEME</code></a></li>
<li><a href="#errors_err_http2_error"><code>ERR_HTTP2_ERROR</code></a></li>
<li><a href="#errors_err_http2_goaway_session"><code>ERR_HTTP2_GOAWAY_SESSION</code></a></li>
<li><a href="#errors_err_http2_headers_after_respond"><code>ERR_HTTP2_HEADERS_AFTER_RESPOND</code></a></li>
<li><a href="#errors_err_http2_headers_sent"><code>ERR_HTTP2_HEADERS_SENT</code></a></li>
<li><a href="#errors_err_http2_header_single_value"><code>ERR_HTTP2_HEADER_SINGLE_VALUE</code></a></li>
<li><a href="#errors_err_http2_info_status_not_allowed"><code>ERR_HTTP2_INFO_STATUS_NOT_ALLOWED</code></a></li>
<li><a href="#errors_err_http2_invalid_connection_headers"><code>ERR_HTTP2_INVALID_CONNECTION_HEADERS</code></a></li>
<li><a href="#errors_err_http2_invalid_header_value"><code>ERR_HTTP2_INVALID_HEADER_VALUE</code></a></li>
<li><a href="#errors_err_http2_invalid_info_status"><code>ERR_HTTP2_INVALID_INFO_STATUS</code></a></li>
<li><a href="#errors_err_http2_invalid_origin"><code>ERR_HTTP2_INVALID_ORIGIN</code></a></li>
<li><a href="#errors_err_http2_invalid_packed_settings_length"><code>ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH</code></a></li>
<li><a href="#errors_err_http2_invalid_pseudoheader"><code>ERR_HTTP2_INVALID_PSEUDOHEADER</code></a></li>
<li><a href="#errors_err_http2_invalid_session"><code>ERR_HTTP2_INVALID_SESSION</code></a></li>
<li><a href="#errors_err_http2_invalid_setting_value"><code>ERR_HTTP2_INVALID_SETTING_VALUE</code></a></li>
<li><a href="#errors_err_http2_invalid_stream"><code>ERR_HTTP2_INVALID_STREAM</code></a></li>
<li><a href="#errors_err_http2_max_pending_settings_ack"><code>ERR_HTTP2_MAX_PENDING_SETTINGS_ACK</code></a></li>
<li><a href="#errors_err_http2_nested_push"><code>ERR_HTTP2_NESTED_PUSH</code></a></li>
<li><a href="#errors_err_http2_no_socket_manipulation"><code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code></a></li>
<li><a href="#errors_err_http2_origin_length"><code>ERR_HTTP2_ORIGIN_LENGTH</code></a></li>
<li><a href="#errors_err_http2_out_of_streams"><code>ERR_HTTP2_OUT_OF_STREAMS</code></a></li>
<li><a href="#errors_err_http2_payload_forbidden"><code>ERR_HTTP2_PAYLOAD_FORBIDDEN</code></a></li>
<li><a href="#errors_err_http2_ping_cancel"><code>ERR_HTTP2_PING_CANCEL</code></a></li>
<li><a href="#errors_err_http2_ping_length"><code>ERR_HTTP2_PING_LENGTH</code></a></li>
<li><a href="#errors_err_http2_pseudoheader_not_allowed"><code>ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED</code></a></li>
<li><a href="#errors_err_http2_push_disabled"><code>ERR_HTTP2_PUSH_DISABLED</code></a></li>
<li><a href="#errors_err_http2_send_file"><code>ERR_HTTP2_SEND_FILE</code></a></li>
<li><a href="#errors_err_http2_send_file_noseek"><code>ERR_HTTP2_SEND_FILE_NOSEEK</code></a></li>
<li><a href="#errors_err_http2_session_error"><code>ERR_HTTP2_SESSION_ERROR</code></a></li>
<li><a href="#errors_err_http2_settings_cancel"><code>ERR_HTTP2_SETTINGS_CANCEL</code></a></li>
<li><a href="#errors_err_http2_socket_bound"><code>ERR_HTTP2_SOCKET_BOUND</code></a></li>
<li><a href="#errors_err_http2_socket_unbound"><code>ERR_HTTP2_SOCKET_UNBOUND</code></a></li>
<li><a href="#errors_err_http2_status_101"><code>ERR_HTTP2_STATUS_101</code></a></li>
<li><a href="#errors_err_http2_status_invalid"><code>ERR_HTTP2_STATUS_INVALID</code></a></li>
<li><a href="#errors_err_http2_stream_cancel"><code>ERR_HTTP2_STREAM_CANCEL</code></a></li>
<li><a href="#errors_err_http2_stream_error"><code>ERR_HTTP2_STREAM_ERROR</code></a></li>
<li><a href="#errors_err_http2_stream_self_dependency"><code>ERR_HTTP2_STREAM_SELF_DEPENDENCY</code></a></li>
<li><a href="#errors_err_http2_trailers_already_sent"><code>ERR_HTTP2_TRAILERS_ALREADY_SENT</code></a></li>
<li><a href="#errors_err_http2_trailers_not_ready"><code>ERR_HTTP2_TRAILERS_NOT_READY</code></a></li>
<li><a href="#errors_err_http2_unsupported_protocol"><code>ERR_HTTP2_UNSUPPORTED_PROTOCOL</code></a></li>
<li><a href="#errors_err_internal_assertion"><code>ERR_INTERNAL_ASSERTION</code></a></li>
<li><a href="#errors_err_incompatible_option_pair"><code>ERR_INCOMPATIBLE_OPTION_PAIR</code></a></li>
<li><a href="#errors_err_input_type_not_allowed"><code>ERR_INPUT_TYPE_NOT_ALLOWED</code></a></li>
<li><a href="#errors_err_inspector_already_activated"><code>ERR_INSPECTOR_ALREADY_ACTIVATED</code></a></li>
<li><a href="#errors_err_inspector_already_connected"><code>ERR_INSPECTOR_ALREADY_CONNECTED</code></a></li>
<li><a href="#errors_err_inspector_closed"><code>ERR_INSPECTOR_CLOSED</code></a></li>
<li><a href="#errors_err_inspector_command"><code>ERR_INSPECTOR_COMMAND</code></a></li>
<li><a href="#errors_err_inspector_not_active"><code>ERR_INSPECTOR_NOT_ACTIVE</code></a></li>
<li><a href="#errors_err_inspector_not_available"><code>ERR_INSPECTOR_NOT_AVAILABLE</code></a></li>
<li><a href="#errors_err_inspector_not_connected"><code>ERR_INSPECTOR_NOT_CONNECTED</code></a></li>
<li><a href="#errors_err_inspector_not_worker"><code>ERR_INSPECTOR_NOT_WORKER</code></a></li>
<li><a href="#errors_err_invalid_address_family"><code>ERR_INVALID_ADDRESS_FAMILY</code></a></li>
<li><a href="#errors_err_invalid_arg_type"><code>ERR_INVALID_ARG_TYPE</code></a></li>
<li><a href="#errors_err_invalid_arg_value"><code>ERR_INVALID_ARG_VALUE</code></a></li>
<li><a href="#errors_err_invalid_async_id"><code>ERR_INVALID_ASYNC_ID</code></a></li>
<li><a href="#errors_err_invalid_buffer_size"><code>ERR_INVALID_BUFFER_SIZE</code></a></li>
<li><a href="#errors_err_invalid_callback"><code>ERR_INVALID_CALLBACK</code></a></li>
<li><a href="#errors_err_invalid_char"><code>ERR_INVALID_CHAR</code></a></li>
<li><a href="#errors_err_invalid_cursor_pos"><code>ERR_INVALID_CURSOR_POS</code></a></li>
<li><a href="#errors_err_invalid_fd"><code>ERR_INVALID_FD</code></a></li>
<li><a href="#errors_err_invalid_fd_type"><code>ERR_INVALID_FD_TYPE</code></a></li>
<li><a href="#errors_err_invalid_file_url_host"><code>ERR_INVALID_FILE_URL_HOST</code></a></li>
<li><a href="#errors_err_invalid_file_url_path"><code>ERR_INVALID_FILE_URL_PATH</code></a></li>
<li><a href="#errors_err_invalid_handle_type"><code>ERR_INVALID_HANDLE_TYPE</code></a></li>
<li><a href="#errors_err_invalid_http_token"><code>ERR_INVALID_HTTP_TOKEN</code></a></li>
<li><a href="#errors_err_invalid_ip_address"><code>ERR_INVALID_IP_ADDRESS</code></a></li>
<li><a href="#errors_err_invalid_module_specifier"><code>ERR_INVALID_MODULE_SPECIFIER</code></a></li>
<li><a href="#errors_err_invalid_opt_value"><code>ERR_INVALID_OPT_VALUE</code></a></li>
<li><a href="#errors_err_invalid_opt_value_encoding"><code>ERR_INVALID_OPT_VALUE_ENCODING</code></a></li>
<li><a href="#errors_err_invalid_package_config"><code>ERR_INVALID_PACKAGE_CONFIG</code></a></li>
<li><a href="#errors_err_invalid_package_target"><code>ERR_INVALID_PACKAGE_TARGET</code></a></li>
<li><a href="#errors_err_invalid_performance_mark"><code>ERR_INVALID_PERFORMANCE_MARK</code></a></li>
<li><a href="#errors_err_invalid_protocol"><code>ERR_INVALID_PROTOCOL</code></a></li>
<li><a href="#errors_err_invalid_repl_eval_config"><code>ERR_INVALID_REPL_EVAL_CONFIG</code></a></li>
<li><a href="#errors_err_invalid_repl_input"><code>ERR_INVALID_REPL_INPUT</code></a></li>
<li><a href="#errors_err_invalid_return_property"><code>ERR_INVALID_RETURN_PROPERTY</code></a></li>
<li><a href="#errors_err_invalid_return_property_value"><code>ERR_INVALID_RETURN_PROPERTY_VALUE</code></a></li>
<li><a href="#errors_err_invalid_return_value"><code>ERR_INVALID_RETURN_VALUE</code></a></li>
<li><a href="#errors_err_invalid_sync_fork_input"><code>ERR_INVALID_SYNC_FORK_INPUT</code></a></li>
<li><a href="#errors_err_invalid_this"><code>ERR_INVALID_THIS</code></a></li>
<li><a href="#errors_err_invalid_transfer_object"><code>ERR_INVALID_TRANSFER_OBJECT</code></a></li>
<li><a href="#errors_err_invalid_tuple"><code>ERR_INVALID_TUPLE</code></a></li>
<li><a href="#errors_err_invalid_uri"><code>ERR_INVALID_URI</code></a></li>
<li><a href="#errors_err_invalid_url"><code>ERR_INVALID_URL</code></a></li>
<li><a href="#errors_err_invalid_url_scheme"><code>ERR_INVALID_URL_SCHEME</code></a></li>
<li><a href="#errors_err_ipc_channel_closed"><code>ERR_IPC_CHANNEL_CLOSED</code></a></li>
<li><a href="#errors_err_ipc_disconnected"><code>ERR_IPC_DISCONNECTED</code></a></li>
<li><a href="#errors_err_ipc_one_pipe"><code>ERR_IPC_ONE_PIPE</code></a></li>
<li><a href="#errors_err_ipc_sync_fork"><code>ERR_IPC_SYNC_FORK</code></a></li>
<li><a href="#errors_err_manifest_assert_integrity"><code>ERR_MANIFEST_ASSERT_INTEGRITY</code></a></li>
<li><a href="#errors_err_manifest_dependency_missing"><code>ERR_MANIFEST_DEPENDENCY_MISSING</code></a></li>
<li><a href="#errors_err_manifest_integrity_mismatch"><code>ERR_MANIFEST_INTEGRITY_MISMATCH</code></a></li>
<li><a href="#errors_err_manifest_invalid_resource_field"><code>ERR_MANIFEST_INVALID_RESOURCE_FIELD</code></a></li>
<li><a href="#errors_err_manifest_parse_policy"><code>ERR_MANIFEST_PARSE_POLICY</code></a></li>
<li><a href="#errors_err_manifest_tdz"><code>ERR_MANIFEST_TDZ</code></a></li>
<li><a href="#errors_err_manifest_unknown_onerror"><code>ERR_MANIFEST_UNKNOWN_ONERROR</code></a></li>
<li><a href="#errors_err_memory_allocation_failed"><code>ERR_MEMORY_ALLOCATION_FAILED</code></a></li>
<li><a href="#errors_err_method_not_implemented"><code>ERR_METHOD_NOT_IMPLEMENTED</code></a></li>
<li><a href="#errors_err_missing_args"><code>ERR_MISSING_ARGS</code></a></li>
<li><a href="#errors_err_missing_dynamic_instantiate_hook"><code>ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK</code></a></li>
<li><a href="#errors_err_missing_option"><code>ERR_MISSING_OPTION</code></a></li>
<li><a href="#errors_err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a></li>
<li><a href="#errors_err_missing_passphrase"><code>ERR_MISSING_PASSPHRASE</code></a></li>
<li><a href="#errors_err_missing_platform_for_worker"><code>ERR_MISSING_PLATFORM_FOR_WORKER</code></a></li>
<li><a href="#errors_err_module_not_found"><code>ERR_MODULE_NOT_FOUND</code></a></li>
<li><a href="#errors_err_multiple_callback"><code>ERR_MULTIPLE_CALLBACK</code></a></li>
<li><a href="#errors_err_napi_cons_function"><code>ERR_NAPI_CONS_FUNCTION</code></a></li>
<li><a href="#errors_err_napi_invalid_dataview_args"><code>ERR_NAPI_INVALID_DATAVIEW_ARGS</code></a></li>
<li><a href="#errors_err_napi_invalid_typedarray_alignment"><code>ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT</code></a></li>
<li><a href="#errors_err_napi_invalid_typedarray_length"><code>ERR_NAPI_INVALID_TYPEDARRAY_LENGTH</code></a></li>
<li><a href="#errors_err_napi_tsfn_call_js"><code>ERR_NAPI_TSFN_CALL_JS</code></a></li>
<li><a href="#errors_err_napi_tsfn_get_undefined"><code>ERR_NAPI_TSFN_GET_UNDEFINED</code></a></li>
<li><a href="#errors_err_napi_tsfn_start_idle_loop"><code>ERR_NAPI_TSFN_START_IDLE_LOOP</code></a></li>
<li><a href="#errors_err_napi_tsfn_stop_idle_loop"><code>ERR_NAPI_TSFN_STOP_IDLE_LOOP</code></a></li>
<li><a href="#errors_err_no_crypto"><code>ERR_NO_CRYPTO</code></a></li>
<li><a href="#errors_err_no_icu"><code>ERR_NO_ICU</code></a></li>
<li><a href="#errors_err_non_context_aware_disabled"><code>ERR_NON_CONTEXT_AWARE_DISABLED</code></a></li>
<li><a href="#errors_err_out_of_range"><code>ERR_OUT_OF_RANGE</code></a></li>
<li><a href="#errors_err_package_path_not_exported"><code>ERR_PACKAGE_PATH_NOT_EXPORTED</code></a></li>
<li><a href="#errors_err_proto_access"><code>ERR_PROTO_ACCESS</code></a></li>
<li><a href="#errors_err_require_esm"><code>ERR_REQUIRE_ESM</code></a></li>
<li><a href="#errors_err_script_execution_interrupted"><code>ERR_SCRIPT_EXECUTION_INTERRUPTED</code></a></li>
<li><a href="#errors_err_script_execution_timeout"><code>ERR_SCRIPT_EXECUTION_TIMEOUT</code></a></li>
<li><a href="#errors_err_server_already_listen"><code>ERR_SERVER_ALREADY_LISTEN</code></a></li>
<li><a href="#errors_err_server_not_running"><code>ERR_SERVER_NOT_RUNNING</code></a></li>
<li><a href="#errors_err_socket_already_bound"><code>ERR_SOCKET_ALREADY_BOUND</code></a></li>
<li><a href="#errors_err_socket_bad_buffer_size"><code>ERR_SOCKET_BAD_BUFFER_SIZE</code></a></li>
<li><a href="#errors_err_socket_bad_port"><code>ERR_SOCKET_BAD_PORT</code></a></li>
<li><a href="#errors_err_socket_bad_type"><code>ERR_SOCKET_BAD_TYPE</code></a></li>
<li><a href="#errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a></li>
<li><a href="#errors_err_socket_cannot_send"><code>ERR_SOCKET_CANNOT_SEND</code></a></li>
<li><a href="#errors_err_socket_closed"><code>ERR_SOCKET_CLOSED</code></a></li>
<li><a href="#errors_err_socket_dgram_is_connected"><code>ERR_SOCKET_DGRAM_IS_CONNECTED</code></a></li>
<li><a href="#errors_err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a></li>
<li><a href="#errors_err_socket_dgram_not_running"><code>ERR_SOCKET_DGRAM_NOT_RUNNING</code></a></li>
<li><a href="#errors_err_sri_parse"><code>ERR_SRI_PARSE</code></a></li>
<li><a href="#errors_err_stream_cannot_pipe"><code>ERR_STREAM_CANNOT_PIPE</code></a></li>
<li><a href="#errors_err_stream_destroyed"><code>ERR_STREAM_DESTROYED</code></a></li>
<li><a href="#errors_err_stream_null_values"><code>ERR_STREAM_NULL_VALUES</code></a></li>
<li><a href="#errors_err_stream_premature_close"><code>ERR_STREAM_PREMATURE_CLOSE</code></a></li>
<li><a href="#errors_err_stream_push_after_eof"><code>ERR_STREAM_PUSH_AFTER_EOF</code></a></li>
<li><a href="#errors_err_stream_unshift_after_end_event"><code>ERR_STREAM_UNSHIFT_AFTER_END_EVENT</code></a></li>
<li><a href="#errors_err_stream_wrap"><code>ERR_STREAM_WRAP</code></a></li>
<li><a href="#errors_err_stream_write_after_end"><code>ERR_STREAM_WRITE_AFTER_END</code></a></li>
<li><a href="#errors_err_string_too_long"><code>ERR_STRING_TOO_LONG</code></a></li>
<li><a href="#errors_err_synthetic"><code>ERR_SYNTHETIC</code></a></li>
<li><a href="#errors_err_system_error"><code>ERR_SYSTEM_ERROR</code></a></li>
<li><a href="#errors_err_tls_cert_altname_invalid"><code>ERR_TLS_CERT_ALTNAME_INVALID</code></a></li>
<li><a href="#errors_err_tls_dh_param_size"><code>ERR_TLS_DH_PARAM_SIZE</code></a></li>
<li><a href="#errors_err_tls_handshake_timeout"><code>ERR_TLS_HANDSHAKE_TIMEOUT</code></a></li>
<li><a href="#errors_err_tls_invalid_context"><code>ERR_TLS_INVALID_CONTEXT</code></a></li>
<li><a href="#errors_err_tls_invalid_state"><code>ERR_TLS_INVALID_STATE</code></a></li>
<li><a href="#errors_err_tls_invalid_protocol_method"><code>ERR_TLS_INVALID_PROTOCOL_METHOD</code></a></li>
<li><a href="#errors_err_tls_invalid_protocol_version"><code>ERR_TLS_INVALID_PROTOCOL_VERSION</code></a></li>
<li><a href="#errors_err_tls_protocol_version_conflict"><code>ERR_TLS_PROTOCOL_VERSION_CONFLICT</code></a></li>
<li><a href="#errors_err_tls_renegotiation_disabled"><code>ERR_TLS_RENEGOTIATION_DISABLED</code></a></li>
<li><a href="#errors_err_tls_required_server_name"><code>ERR_TLS_REQUIRED_SERVER_NAME</code></a></li>
<li><a href="#errors_err_tls_session_attack"><code>ERR_TLS_SESSION_ATTACK</code></a></li>
<li><a href="#errors_err_tls_sni_from_server"><code>ERR_TLS_SNI_FROM_SERVER</code></a></li>
<li><a href="#errors_err_tls_psk_set_identiy_hint_failed">ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED</a></li>
<li><a href="#errors_err_trace_events_category_required"><code>ERR_TRACE_EVENTS_CATEGORY_REQUIRED</code></a></li>
<li><a href="#errors_err_trace_events_unavailable"><code>ERR_TRACE_EVENTS_UNAVAILABLE</code></a></li>
<li><a href="#errors_err_transferring_externalized_sharedarraybuffer"><code>ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER</code></a></li>
<li><a href="#errors_err_transform_already_transforming"><code>ERR_TRANSFORM_ALREADY_TRANSFORMING</code></a></li>
<li><a href="#errors_err_transform_with_length_0"><code>ERR_TRANSFORM_WITH_LENGTH_0</code></a></li>
<li><a href="#errors_err_tty_init_failed"><code>ERR_TTY_INIT_FAILED</code></a></li>
<li><a href="#errors_err_uncaught_exception_capture_already_set"><code>ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET</code></a></li>
<li><a href="#errors_err_unescaped_characters"><code>ERR_UNESCAPED_CHARACTERS</code></a></li>
<li><a href="#errors_err_unhandled_error"><code>ERR_UNHANDLED_ERROR</code></a></li>
<li><a href="#errors_err_unknown_builtin_module"><code>ERR_UNKNOWN_BUILTIN_MODULE</code></a></li>
<li><a href="#errors_err_unknown_credential"><code>ERR_UNKNOWN_CREDENTIAL</code></a></li>
<li><a href="#errors_err_unknown_encoding"><code>ERR_UNKNOWN_ENCODING</code></a></li>
<li><a href="#errors_err_unknown_file_extension"><code>ERR_UNKNOWN_FILE_EXTENSION</code></a></li>
<li><a href="#errors_err_unknown_module_format"><code>ERR_UNKNOWN_MODULE_FORMAT</code></a></li>
<li><a href="#errors_err_unknown_signal"><code>ERR_UNKNOWN_SIGNAL</code></a></li>
<li><a href="#errors_err_unsupported_dir_import"><code>ERR_UNSUPPORTED_DIR_IMPORT</code></a></li>
<li><a href="#errors_err_unsupported_esm_url_scheme"><code>ERR_UNSUPPORTED_ESM_URL_SCHEME</code></a></li>
<li><a href="#errors_err_v8breakiterator"><code>ERR_V8BREAKITERATOR</code></a></li>
<li><a href="#errors_err_valid_performance_entry_type"><code>ERR_VALID_PERFORMANCE_ENTRY_TYPE</code></a></li>
<li><a href="#errors_err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a></li>
<li><a href="#errors_err_vm_module_already_linked"><code>ERR_VM_MODULE_ALREADY_LINKED</code></a></li>
<li><a href="#errors_err_vm_module_cached_data_rejected"><code>ERR_VM_MODULE_CACHED_DATA_REJECTED</code></a></li>
<li><a href="#errors_err_vm_module_cannot_create_cached_data"><code>ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA</code></a></li>
<li><a href="#errors_err_vm_module_different_context"><code>ERR_VM_MODULE_DIFFERENT_CONTEXT</code></a></li>
<li><a href="#errors_err_vm_module_linking_errored"><code>ERR_VM_MODULE_LINKING_ERRORED</code></a></li>
<li><a href="#errors_err_vm_module_not_module"><code>ERR_VM_MODULE_NOT_MODULE</code></a></li>
<li><a href="#errors_err_vm_module_status"><code>ERR_VM_MODULE_STATUS</code></a></li>
<li><a href="#errors_err_wasi_already_started"><code>ERR_WASI_ALREADY_STARTED</code></a></li>
<li><a href="#errors_err_wasi_not_started"><code>ERR_WASI_NOT_STARTED</code></a></li>
<li><a href="#errors_err_worker_init_failed"><code>ERR_WORKER_INIT_FAILED</code></a></li>
<li><a href="#errors_err_worker_invalid_exec_argv"><code>ERR_WORKER_INVALID_EXEC_ARGV</code></a></li>
<li><a href="#errors_err_worker_not_running"><code>ERR_WORKER_NOT_RUNNING</code></a></li>
<li><a href="#errors_err_worker_out_of_memory"><code>ERR_WORKER_OUT_OF_MEMORY</code></a></li>
<li><a href="#errors_err_worker_path"><code>ERR_WORKER_PATH</code></a></li>
<li><a href="#errors_err_worker_unserializable_error"><code>ERR_WORKER_UNSERIALIZABLE_ERROR</code></a></li>
<li><a href="#errors_err_worker_unsupported_extension"><code>ERR_WORKER_UNSUPPORTED_EXTENSION</code></a></li>
<li><a href="#errors_err_worker_unsupported_operation"><code>ERR_WORKER_UNSUPPORTED_OPERATION</code></a></li>
<li><a href="#errors_err_zlib_initialization_failed"><code>ERR_ZLIB_INITIALIZATION_FAILED</code></a></li>
<li><a href="#errors_hpe_header_overflow"><code>HPE_HEADER_OVERFLOW</code></a></li>
<li><a href="#errors_module_not_found"><code>MODULE_NOT_FOUND</code></a></li>
</ul>
</li>
<li>
<p><a href="#errors_legacy_node_js_error_codes">Legacy Node.js error codes</a></p>
<ul>
<li><a href="#errors_err_cannot_transfer_object"><code>ERR_CANNOT_TRANSFER_OBJECT</code></a></li>
<li><a href="#errors_err_closed_message_port"><code>ERR_CLOSED_MESSAGE_PORT</code></a></li>
<li><a href="#errors_err_crypto_hash_digest_no_utf16"><code>ERR_CRYPTO_HASH_DIGEST_NO_UTF16</code></a></li>
<li><a href="#errors_err_http2_frame_error"><code>ERR_HTTP2_FRAME_ERROR</code></a></li>
<li><a href="#errors_err_http2_headers_object"><code>ERR_HTTP2_HEADERS_OBJECT</code></a></li>
<li><a href="#errors_err_http2_header_required"><code>ERR_HTTP2_HEADER_REQUIRED</code></a></li>
<li><a href="#errors_err_http2_info_headers_after_respond"><code>ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND</code></a></li>
<li><a href="#errors_err_http2_stream_closed"><code>ERR_HTTP2_STREAM_CLOSED</code></a></li>
<li><a href="#errors_err_http_invalid_char"><code>ERR_HTTP_INVALID_CHAR</code></a></li>
<li><a href="#errors_err_index_out_of_range"><code>ERR_INDEX_OUT_OF_RANGE</code></a></li>
<li><a href="#errors_err_napi_cons_prototype_object"><code>ERR_NAPI_CONS_PROTOTYPE_OBJECT</code></a></li>
<li><a href="#errors_err_no_longer_supported"><code>ERR_NO_LONGER_SUPPORTED</code></a></li>
<li><a href="#errors_err_outofmemory"><code>ERR_OUTOFMEMORY</code></a></li>
<li><a href="#errors_err_parse_history_data"><code>ERR_PARSE_HISTORY_DATA</code></a></li>
<li><a href="#errors_err_stderr_close"><code>ERR_STDERR_CLOSE</code></a></li>
<li><a href="#errors_err_stdout_close"><code>ERR_STDOUT_CLOSE</code></a></li>
<li><a href="#errors_err_stream_read_not_implemented"><code>ERR_STREAM_READ_NOT_IMPLEMENTED</code></a></li>
<li><a href="#errors_err_tls_renegotiation_failed"><code>ERR_TLS_RENEGOTIATION_FAILED</code></a></li>
<li><a href="#errors_err_unknown_builtin_module_1"><code>ERR_UNKNOWN_BUILTIN_MODULE</code></a></li>
<li><a href="#errors_err_unknown_stdin_type"><code>ERR_UNKNOWN_STDIN_TYPE</code></a></li>
<li><a href="#errors_err_unknown_stream_type"><code>ERR_UNKNOWN_STREAM_TYPE</code></a></li>
<li><a href="#errors_err_value_out_of_range"><code>ERR_VALUE_OUT_OF_RANGE</code></a></li>
<li><a href="#errors_err_vm_module_not_linked"><code>ERR_VM_MODULE_NOT_LINKED</code></a></li>
<li><a href="#errors_err_zlib_binding_closed"><code>ERR_ZLIB_BINDING_CLOSED</code></a></li>
<li>
<p><a href="#errors_other_error_codes">Other error codes</a></p>
<ul>
<li><a href="#errors_err_entry_type_mismatch"><code>ERR_ENTRY_TYPE_MISMATCH</code></a></li>
<li><a href="#errors_err_fs_watcher_already_started"><code>ERR_FS_WATCHER_ALREADY_STARTED</code></a></li>
<li><a href="#errors_err_fs_watcher_not_started"><code>ERR_FS_WATCHER_NOT_STARTED</code></a></li>
<li><a href="#errors_err_http2_already_shutdown"><code>ERR_HTTP2_ALREADY_SHUTDOWN</code></a></li>
<li><a href="#errors_err_http2_error_1"><code>ERR_HTTP2_ERROR</code></a></li>
<li><a href="#errors_err_invalid_repl_history"><code>ERR_INVALID_REPL_HISTORY</code></a></li>
<li><a href="#errors_err_invalid_repl_type"><code>ERR_INVALID_REPL_TYPE</code></a></li>
<li><a href="#errors_err_missing_dynamic_instantiate_hook_1"><code>ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK</code></a></li>
<li><a href="#errors_err_stream_has_stringdecoder"><code>ERR_STREAM_HAS_STRINGDECODER</code></a></li>
<li><a href="#errors_err_string_too_large"><code>ERR_STRING_TOO_LARGE</code></a></li>
<li><a href="#errors_err_tty_writable_not_readable"><code>ERR_TTY_WRITABLE_NOT_READABLE</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#events_events">Events</a></span></p>
<ul>
<li><a href="#events_passing_arguments_and_this_to_listeners">Passing arguments and <code>this</code> to listeners</a></li>
<li><a href="#events_asynchronous_vs_synchronous">Asynchronous vs. synchronous</a></li>
<li><a href="#events_handling_events_only_once">Handling events only once</a></li>
<li><a href="#events_error_events">Error events</a></li>
<li><a href="#events_capture_rejections_of_promises">Capture rejections of promises</a></li>
<li>
<p><a href="#events_class_eventemitter">Class: <code>EventEmitter</code></a></p>
<ul>
<li><a href="#events_event_newlistener">Event: 'newListener'</a></li>
<li><a href="#events_event_removelistener">Event: <code>'removeListener'</code></a></li>
<li><span class="stability_0"><a href="#events_eventemitter_listenercount_emitter_eventname"><code>EventEmitter.listenerCount(emitter, eventName)</code></a></span></li>
<li><a href="#events_eventemitter_defaultmaxlisteners"><code>EventEmitter.defaultMaxListeners</code></a></li>
<li><a href="#events_eventemitter_errormonitor"><code>EventEmitter.errorMonitor</code></a></li>
<li><a href="#events_emitter_addlistener_eventname_listener"><code>emitter.addListener(eventName, listener)</code></a></li>
<li><a href="#events_emitter_emit_eventname_args"><code>emitter.emit(eventName[, ...args])</code></a></li>
<li><a href="#events_emitter_eventnames"><code>emitter.eventNames()</code></a></li>
<li><a href="#events_emitter_getmaxlisteners"><code>emitter.getMaxListeners()</code></a></li>
<li><a href="#events_emitter_listenercount_eventname"><code>emitter.listenerCount(eventName)</code></a></li>
<li><a href="#events_emitter_listeners_eventname"><code>emitter.listeners(eventName)</code></a></li>
<li><a href="#events_emitter_off_eventname_listener"><code>emitter.off(eventName, listener)</code></a></li>
<li><a href="#events_emitter_on_eventname_listener"><code>emitter.on(eventName, listener)</code></a></li>
<li><a href="#events_emitter_once_eventname_listener"><code>emitter.once(eventName, listener)</code></a></li>
<li><a href="#events_emitter_prependlistener_eventname_listener"><code>emitter.prependListener(eventName, listener)</code></a></li>
<li><a href="#events_emitter_prependoncelistener_eventname_listener"><code>emitter.prependOnceListener(eventName, listener)</code></a></li>
<li><a href="#events_emitter_removealllisteners_eventname"><code>emitter.removeAllListeners([eventName])</code></a></li>
<li><a href="#events_emitter_removelistener_eventname_listener"><code>emitter.removeListener(eventName, listener)</code></a></li>
<li><a href="#events_emitter_setmaxlisteners_n"><code>emitter.setMaxListeners(n)</code></a></li>
<li><a href="#events_emitter_rawlisteners_eventname"><code>emitter.rawListeners(eventName)</code></a></li>
<li><span class="stability_1"><a href="#events_emitter_symbol_for_nodejs_rejection_err_eventname_args"><code>emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])</code></a></span></li>
</ul>
</li>
<li><a href="#events_events_once_emitter_name"><code>events.once(emitter, name)</code></a></li>
<li><span class="stability_1"><a href="#events_events_capturerejections">events.captureRejections</a></span></li>
<li><span class="stability_1"><a href="#events_events_capturerejectionsymbol">events.captureRejectionSymbol</a></span></li>
<li><a href="#events_events_on_emitter_eventname">events.on(emitter, eventName)</a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#fs_file_system">File system</a></span></p>
<ul>
<li>
<p><a href="#fs_file_paths">File paths</a></p>
<ul>
<li><a href="#fs_url_object_support">URL object support</a></li>
</ul>
</li>
<li><a href="#fs_file_descriptors">File descriptors</a></li>
<li><a href="#fs_threadpool_usage">Threadpool usage</a></li>
<li>
<p><a href="#fs_class_fs_dir">Class: <code>fs.Dir</code></a></p>
<ul>
<li><a href="#fs_dir_close"><code>dir.close()</code></a></li>
<li><a href="#fs_dir_close_callback"><code>dir.close(callback)</code></a></li>
<li><a href="#fs_dir_closesync"><code>dir.closeSync()</code></a></li>
<li><a href="#fs_dir_path"><code>dir.path</code></a></li>
<li><a href="#fs_dir_read"><code>dir.read()</code></a></li>
<li><a href="#fs_dir_read_callback"><code>dir.read(callback)</code></a></li>
<li><a href="#fs_dir_readsync"><code>dir.readSync()</code></a></li>
<li><a href="#fs_dir_symbol_asynciterator"><code>dir[Symbol.asyncIterator]()</code></a></li>
</ul>
</li>
<li>
<p><a href="#fs_class_fs_dirent">Class: <code>fs.Dirent</code></a></p>
<ul>
<li><a href="#fs_dirent_isblockdevice"><code>dirent.isBlockDevice()</code></a></li>
<li><a href="#fs_dirent_ischaracterdevice"><code>dirent.isCharacterDevice()</code></a></li>
<li><a href="#fs_dirent_isdirectory"><code>dirent.isDirectory()</code></a></li>
<li><a href="#fs_dirent_isfifo"><code>dirent.isFIFO()</code></a></li>
<li><a href="#fs_dirent_isfile"><code>dirent.isFile()</code></a></li>
<li><a href="#fs_dirent_issocket"><code>dirent.isSocket()</code></a></li>
<li><a href="#fs_dirent_issymboliclink"><code>dirent.isSymbolicLink()</code></a></li>
<li><a href="#fs_dirent_name"><code>dirent.name</code></a></li>
</ul>
</li>
<li>
<p><a href="#fs_class_fs_fswatcher">Class: <code>fs.FSWatcher</code></a></p>
<ul>
<li><a href="#fs_event_change">Event: <code>'change'</code></a></li>
<li><a href="#fs_event_close">Event: <code>'close'</code></a></li>
<li><a href="#fs_event_error">Event: <code>'error'</code></a></li>
<li><a href="#fs_watcher_close"><code>watcher.close()</code></a></li>
</ul>
</li>
<li>
<p><a href="#fs_class_fs_readstream">Class: <code>fs.ReadStream</code></a></p>
<ul>
<li><a href="#fs_event_close_1">Event: <code>'close'</code></a></li>
<li><a href="#fs_event_open">Event: <code>'open'</code></a></li>
<li><a href="#fs_event_ready">Event: <code>'ready'</code></a></li>
<li><a href="#fs_readstream_bytesread"><code>readStream.bytesRead</code></a></li>
<li><a href="#fs_readstream_path"><code>readStream.path</code></a></li>
<li><a href="#fs_readstream_pending"><code>readStream.pending</code></a></li>
</ul>
</li>
<li>
<p><a href="#fs_class_fs_stats">Class: <code>fs.Stats</code></a></p>
<ul>
<li><a href="#fs_stats_isblockdevice"><code>stats.isBlockDevice()</code></a></li>
<li><a href="#fs_stats_ischaracterdevice"><code>stats.isCharacterDevice()</code></a></li>
<li><a href="#fs_stats_isdirectory"><code>stats.isDirectory()</code></a></li>
<li><a href="#fs_stats_isfifo"><code>stats.isFIFO()</code></a></li>
<li><a href="#fs_stats_isfile"><code>stats.isFile()</code></a></li>
<li><a href="#fs_stats_issocket"><code>stats.isSocket()</code></a></li>
<li><a href="#fs_stats_issymboliclink"><code>stats.isSymbolicLink()</code></a></li>
<li><a href="#fs_stats_dev"><code>stats.dev</code></a></li>
<li><a href="#fs_stats_ino"><code>stats.ino</code></a></li>
<li><a href="#fs_stats_mode"><code>stats.mode</code></a></li>
<li><a href="#fs_stats_nlink"><code>stats.nlink</code></a></li>
<li><a href="#fs_stats_uid"><code>stats.uid</code></a></li>
<li><a href="#fs_stats_gid"><code>stats.gid</code></a></li>
<li><a href="#fs_stats_rdev"><code>stats.rdev</code></a></li>
<li><a href="#fs_stats_size"><code>stats.size</code></a></li>
<li><a href="#fs_stats_blksize"><code>stats.blksize</code></a></li>
<li><a href="#fs_stats_blocks"><code>stats.blocks</code></a></li>
<li><a href="#fs_stats_atimems"><code>stats.atimeMs</code></a></li>
<li><a href="#fs_stats_mtimems"><code>stats.mtimeMs</code></a></li>
<li><a href="#fs_stats_ctimems"><code>stats.ctimeMs</code></a></li>
<li><a href="#fs_stats_birthtimems"><code>stats.birthtimeMs</code></a></li>
<li><a href="#fs_stats_atimens"><code>stats.atimeNs</code></a></li>
<li><a href="#fs_stats_mtimens"><code>stats.mtimeNs</code></a></li>
<li><a href="#fs_stats_ctimens"><code>stats.ctimeNs</code></a></li>
<li><a href="#fs_stats_birthtimens"><code>stats.birthtimeNs</code></a></li>
<li><a href="#fs_stats_atime"><code>stats.atime</code></a></li>
<li><a href="#fs_stats_mtime"><code>stats.mtime</code></a></li>
<li><a href="#fs_stats_ctime"><code>stats.ctime</code></a></li>
<li><a href="#fs_stats_birthtime"><code>stats.birthtime</code></a></li>
<li><a href="#fs_stat_time_values">Stat time values</a></li>
</ul>
</li>
<li>
<p><a href="#fs_class_fs_writestream">Class: <code>fs.WriteStream</code></a></p>
<ul>
<li><a href="#fs_event_close_2">Event: <code>'close'</code></a></li>
<li><a href="#fs_event_open_1">Event: <code>'open'</code></a></li>
<li><a href="#fs_event_ready_1">Event: <code>'ready'</code></a></li>
<li><a href="#fs_writestream_byteswritten"><code>writeStream.bytesWritten</code></a></li>
<li><a href="#fs_writestream_path"><code>writeStream.path</code></a></li>
<li><a href="#fs_writestream_pending"><code>writeStream.pending</code></a></li>
</ul>
</li>
<li><a href="#fs_fs_access_path_mode_callback"><code>fs.access(path[, mode], callback)</code></a></li>
<li><a href="#fs_fs_accesssync_path_mode"><code>fs.accessSync(path[, mode])</code></a></li>
<li><a href="#fs_fs_appendfile_path_data_options_callback"><code>fs.appendFile(path, data[, options], callback)</code></a></li>
<li><a href="#fs_fs_appendfilesync_path_data_options"><code>fs.appendFileSync(path, data[, options])</code></a></li>
<li>
<p><a href="#fs_fs_chmod_path_mode_callback"><code>fs.chmod(path, mode, callback)</code></a></p>
<ul>
<li><a href="#fs_file_modes">File modes</a></li>
</ul>
</li>
<li><a href="#fs_fs_chmodsync_path_mode"><code>fs.chmodSync(path, mode)</code></a></li>
<li><a href="#fs_fs_chown_path_uid_gid_callback"><code>fs.chown(path, uid, gid, callback)</code></a></li>
<li><a href="#fs_fs_chownsync_path_uid_gid"><code>fs.chownSync(path, uid, gid)</code></a></li>
<li><a href="#fs_fs_close_fd_callback"><code>fs.close(fd, callback)</code></a></li>
<li><a href="#fs_fs_closesync_fd"><code>fs.closeSync(fd)</code></a></li>
<li><a href="#fs_fs_constants"><code>fs.constants</code></a></li>
<li><a href="#fs_fs_copyfile_src_dest_flags_callback"><code>fs.copyFile(src, dest[, flags], callback)</code></a></li>
<li><a href="#fs_fs_copyfilesync_src_dest_flags"><code>fs.copyFileSync(src, dest[, flags])</code></a></li>
<li><a href="#fs_fs_createreadstream_path_options"><code>fs.createReadStream(path[, options])</code></a></li>
<li><a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream(path[, options])</code></a></li>
<li><span class="stability_0"><a href="#fs_fs_exists_path_callback"><code>fs.exists(path, callback)</code></a></span></li>
<li><a href="#fs_fs_existssync_path"><code>fs.existsSync(path)</code></a></li>
<li><a href="#fs_fs_fchmod_fd_mode_callback"><code>fs.fchmod(fd, mode, callback)</code></a></li>
<li><a href="#fs_fs_fchmodsync_fd_mode"><code>fs.fchmodSync(fd, mode)</code></a></li>
<li><a href="#fs_fs_fchown_fd_uid_gid_callback"><code>fs.fchown(fd, uid, gid, callback)</code></a></li>
<li><a href="#fs_fs_fchownsync_fd_uid_gid"><code>fs.fchownSync(fd, uid, gid)</code></a></li>
<li><a href="#fs_fs_fdatasync_fd_callback"><code>fs.fdatasync(fd, callback)</code></a></li>
<li><a href="#fs_fs_fdatasyncsync_fd"><code>fs.fdatasyncSync(fd)</code></a></li>
<li><a href="#fs_fs_fstat_fd_options_callback"><code>fs.fstat(fd[, options], callback)</code></a></li>
<li><a href="#fs_fs_fstatsync_fd_options"><code>fs.fstatSync(fd[, options])</code></a></li>
<li><a href="#fs_fs_fsync_fd_callback"><code>fs.fsync(fd, callback)</code></a></li>
<li><a href="#fs_fs_fsyncsync_fd"><code>fs.fsyncSync(fd)</code></a></li>
<li><a href="#fs_fs_ftruncate_fd_len_callback"><code>fs.ftruncate(fd[, len], callback)</code></a></li>
<li><a href="#fs_fs_ftruncatesync_fd_len"><code>fs.ftruncateSync(fd[, len])</code></a></li>
<li><a href="#fs_fs_futimes_fd_atime_mtime_callback"><code>fs.futimes(fd, atime, mtime, callback)</code></a></li>
<li><a href="#fs_fs_futimessync_fd_atime_mtime"><code>fs.futimesSync(fd, atime, mtime)</code></a></li>
<li><a href="#fs_fs_lchmod_path_mode_callback"><code>fs.lchmod(path, mode, callback)</code></a></li>
<li><a href="#fs_fs_lchmodsync_path_mode"><code>fs.lchmodSync(path, mode)</code></a></li>
<li><a href="#fs_fs_lchown_path_uid_gid_callback"><code>fs.lchown(path, uid, gid, callback)</code></a></li>
<li><a href="#fs_fs_lchownsync_path_uid_gid"><code>fs.lchownSync(path, uid, gid)</code></a></li>
<li><a href="#fs_fs_link_existingpath_newpath_callback"><code>fs.link(existingPath, newPath, callback)</code></a></li>
<li><a href="#fs_fs_linksync_existingpath_newpath"><code>fs.linkSync(existingPath, newPath)</code></a></li>
<li><a href="#fs_fs_lstat_path_options_callback"><code>fs.lstat(path[, options], callback)</code></a></li>
<li><a href="#fs_fs_lstatsync_path_options"><code>fs.lstatSync(path[, options])</code></a></li>
<li><a href="#fs_fs_mkdir_path_options_callback"><code>fs.mkdir(path[, options], callback)</code></a></li>
<li><a href="#fs_fs_mkdirsync_path_options"><code>fs.mkdirSync(path[, options])</code></a></li>
<li><a href="#fs_fs_mkdtemp_prefix_options_callback"><code>fs.mkdtemp(prefix[, options], callback)</code></a></li>
<li><a href="#fs_fs_mkdtempsync_prefix_options"><code>fs.mkdtempSync(prefix[, options])</code></a></li>
<li><a href="#fs_fs_open_path_flags_mode_callback"><code>fs.open(path[, flags[, mode]], callback)</code></a></li>
<li><a href="#fs_fs_opendir_path_options_callback"><code>fs.opendir(path[, options], callback)</code></a></li>
<li><a href="#fs_fs_opendirsync_path_options"><code>fs.opendirSync(path[, options])</code></a></li>
<li><a href="#fs_fs_opensync_path_flags_mode"><code>fs.openSync(path[, flags, mode])</code></a></li>
<li><a href="#fs_fs_read_fd_buffer_offset_length_position_callback"><code>fs.read(fd, buffer, offset, length, position, callback)</code></a></li>
<li><a href="#fs_fs_read_fd_options_callback"><code>fs.read(fd, [options,] callback)</code></a></li>
<li><a href="#fs_fs_readdir_path_options_callback"><code>fs.readdir(path[, options], callback)</code></a></li>
<li><a href="#fs_fs_readdirsync_path_options"><code>fs.readdirSync(path[, options])</code></a></li>
<li>
<p><a href="#fs_fs_readfile_path_options_callback"><code>fs.readFile(path[, options], callback)</code></a></p>
<ul>
<li><a href="#fs_file_descriptors_1">File descriptors</a></li>
</ul>
</li>
<li><a href="#fs_fs_readfilesync_path_options"><code>fs.readFileSync(path[, options])</code></a></li>
<li><a href="#fs_fs_readlink_path_options_callback"><code>fs.readlink(path[, options], callback)</code></a></li>
<li><a href="#fs_fs_readlinksync_path_options"><code>fs.readlinkSync(path[, options])</code></a></li>
<li><a href="#fs_fs_readsync_fd_buffer_offset_length_position"><code>fs.readSync(fd, buffer, offset, length, position)</code></a></li>
<li><a href="#fs_fs_readsync_fd_buffer_options"><code>fs.readSync(fd, buffer, [options])</code></a></li>
<li><a href="#fs_fs_readv_fd_buffers_position_callback"><code>fs.readv(fd, buffers[, position], callback)</code></a></li>
<li><a href="#fs_fs_readvsync_fd_buffers_position"><code>fs.readvSync(fd, buffers[, position])</code></a></li>
<li><a href="#fs_fs_realpath_path_options_callback"><code>fs.realpath(path[, options], callback)</code></a></li>
<li><a href="#fs_fs_realpath_native_path_options_callback"><code>fs.realpath.native(path[, options], callback)</code></a></li>
<li><a href="#fs_fs_realpathsync_path_options"><code>fs.realpathSync(path[, options])</code></a></li>
<li><a href="#fs_fs_realpathsync_native_path_options"><code>fs.realpathSync.native(path[, options])</code></a></li>
<li><a href="#fs_fs_rename_oldpath_newpath_callback"><code>fs.rename(oldPath, newPath, callback)</code></a></li>
<li><a href="#fs_fs_renamesync_oldpath_newpath"><code>fs.renameSync(oldPath, newPath)</code></a></li>
<li><span class="stability_1"><a href="#fs_fs_rmdir_path_options_callback"><code>fs.rmdir(path[, options], callback)</code></a></span></li>
<li><span class="stability_1"><a href="#fs_fs_rmdirsync_path_options"><code>fs.rmdirSync(path[, options])</code></a></span></li>
<li><a href="#fs_fs_stat_path_options_callback"><code>fs.stat(path[, options], callback)</code></a></li>
<li><a href="#fs_fs_statsync_path_options"><code>fs.statSync(path[, options])</code></a></li>
<li><a href="#fs_fs_symlink_target_path_type_callback"><code>fs.symlink(target, path[, type], callback)</code></a></li>
<li><a href="#fs_fs_symlinksync_target_path_type"><code>fs.symlinkSync(target, path[, type])</code></a></li>
<li><a href="#fs_fs_truncate_path_len_callback"><code>fs.truncate(path[, len], callback)</code></a></li>
<li><a href="#fs_fs_truncatesync_path_len"><code>fs.truncateSync(path[, len])</code></a></li>
<li><a href="#fs_fs_unlink_path_callback"><code>fs.unlink(path, callback)</code></a></li>
<li><a href="#fs_fs_unlinksync_path"><code>fs.unlinkSync(path)</code></a></li>
<li><a href="#fs_fs_unwatchfile_filename_listener"><code>fs.unwatchFile(filename[, listener])</code></a></li>
<li><a href="#fs_fs_utimes_path_atime_mtime_callback"><code>fs.utimes(path, atime, mtime, callback)</code></a></li>
<li><a href="#fs_fs_utimessync_path_atime_mtime"><code>fs.utimesSync(path, atime, mtime)</code></a></li>
<li>
<p><a href="#fs_fs_watch_filename_options_listener"><code>fs.watch(filename[, options][, listener])</code></a></p>
<ul>
<li>
<p><a href="#fs_caveats">Caveats</a></p>
<ul>
<li><a href="#fs_availability">Availability</a></li>
<li><a href="#fs_inodes">Inodes</a></li>
<li><a href="#fs_filename_argument">Filename argument</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#fs_fs_watchfile_filename_options_listener"><code>fs.watchFile(filename[, options], listener)</code></a></li>
<li><a href="#fs_fs_write_fd_buffer_offset_length_position_callback"><code>fs.write(fd, buffer[, offset[, length[, position]]], callback)</code></a></li>
<li><a href="#fs_fs_write_fd_string_position_encoding_callback"><code>fs.write(fd, string[, position[, encoding]], callback)</code></a></li>
<li>
<p><a href="#fs_fs_writefile_file_data_options_callback"><code>fs.writeFile(file, data[, options], callback)</code></a></p>
<ul>
<li><a href="#fs_using_fs_writefile_with_file_descriptors">Using <code>fs.writeFile()</code> with file descriptors</a></li>
</ul>
</li>
<li><a href="#fs_fs_writefilesync_file_data_options"><code>fs.writeFileSync(file, data[, options])</code></a></li>
<li><a href="#fs_fs_writesync_fd_buffer_offset_length_position"><code>fs.writeSync(fd, buffer[, offset[, length[, position]]])</code></a></li>
<li><a href="#fs_fs_writesync_fd_string_position_encoding"><code>fs.writeSync(fd, string[, position[, encoding]])</code></a></li>
<li><a href="#fs_fs_writev_fd_buffers_position_callback"><code>fs.writev(fd, buffers[, position], callback)</code></a></li>
<li><a href="#fs_fs_writevsync_fd_buffers_position"><code>fs.writevSync(fd, buffers[, position])</code></a></li>
<li>
<p><a href="#fs_fs_promises_api"><code>fs</code> Promises API</a></p>
<ul>
<li>
<p><a href="#fs_class_filehandle">Class: <code>FileHandle</code></a></p>
<ul>
<li><a href="#fs_filehandle_appendfile_data_options"><code>filehandle.appendFile(data, options)</code></a></li>
<li><a href="#fs_filehandle_chmod_mode"><code>filehandle.chmod(mode)</code></a></li>
<li><a href="#fs_filehandle_chown_uid_gid"><code>filehandle.chown(uid, gid)</code></a></li>
<li><a href="#fs_filehandle_close"><code>filehandle.close()</code></a></li>
<li><a href="#fs_filehandle_datasync"><code>filehandle.datasync()</code></a></li>
<li><a href="#fs_filehandle_fd"><code>filehandle.fd</code></a></li>
<li><a href="#fs_filehandle_read_buffer_offset_length_position"><code>filehandle.read(buffer, offset, length, position)</code></a></li>
<li><a href="#fs_filehandle_read_options"><code>filehandle.read(options)</code></a></li>
<li><a href="#fs_filehandle_readfile_options"><code>filehandle.readFile(options)</code></a></li>
<li><a href="#fs_filehandle_readv_buffers_position"><code>filehandle.readv(buffers[, position])</code></a></li>
<li><a href="#fs_filehandle_stat_options"><code>filehandle.stat([options])</code></a></li>
<li><a href="#fs_filehandle_sync"><code>filehandle.sync()</code></a></li>
<li><a href="#fs_filehandle_truncate_len"><code>filehandle.truncate(len)</code></a></li>
<li><a href="#fs_filehandle_utimes_atime_mtime"><code>filehandle.utimes(atime, mtime)</code></a></li>
<li><a href="#fs_filehandle_write_buffer_offset_length_position"><code>filehandle.write(buffer[, offset[, length[, position]]])</code></a></li>
<li><a href="#fs_filehandle_write_string_position_encoding"><code>filehandle.write(string[, position[, encoding]])</code></a></li>
<li><a href="#fs_filehandle_writefile_data_options"><code>filehandle.writeFile(data, options)</code></a></li>
<li><a href="#fs_filehandle_writev_buffers_position"><code>filehandle.writev(buffers[, position])</code></a></li>
</ul>
</li>
<li><a href="#fs_fspromises_access_path_mode"><code>fsPromises.access(path[, mode])</code></a></li>
<li><a href="#fs_fspromises_appendfile_path_data_options"><code>fsPromises.appendFile(path, data[, options])</code></a></li>
<li><a href="#fs_fspromises_chmod_path_mode"><code>fsPromises.chmod(path, mode)</code></a></li>
<li><a href="#fs_fspromises_chown_path_uid_gid"><code>fsPromises.chown(path, uid, gid)</code></a></li>
<li><a href="#fs_fspromises_copyfile_src_dest_flags"><code>fsPromises.copyFile(src, dest[, flags])</code></a></li>
<li><a href="#fs_fspromises_lchmod_path_mode"><code>fsPromises.lchmod(path, mode)</code></a></li>
<li><a href="#fs_fspromises_lchown_path_uid_gid"><code>fsPromises.lchown(path, uid, gid)</code></a></li>
<li><a href="#fs_fspromises_link_existingpath_newpath"><code>fsPromises.link(existingPath, newPath)</code></a></li>
<li><a href="#fs_fspromises_lstat_path_options"><code>fsPromises.lstat(path[, options])</code></a></li>
<li><a href="#fs_fspromises_mkdir_path_options"><code>fsPromises.mkdir(path[, options])</code></a></li>
<li><a href="#fs_fspromises_mkdtemp_prefix_options"><code>fsPromises.mkdtemp(prefix[, options])</code></a></li>
<li><a href="#fs_fspromises_open_path_flags_mode"><code>fsPromises.open(path, flags[, mode])</code></a></li>
<li><a href="#fs_fspromises_opendir_path_options"><code>fsPromises.opendir(path[, options])</code></a></li>
<li><a href="#fs_fspromises_readdir_path_options"><code>fsPromises.readdir(path[, options])</code></a></li>
<li><a href="#fs_fspromises_readfile_path_options"><code>fsPromises.readFile(path[, options])</code></a></li>
<li><a href="#fs_fspromises_readlink_path_options"><code>fsPromises.readlink(path[, options])</code></a></li>
<li><a href="#fs_fspromises_realpath_path_options"><code>fsPromises.realpath(path[, options])</code></a></li>
<li><a href="#fs_fspromises_rename_oldpath_newpath"><code>fsPromises.rename(oldPath, newPath)</code></a></li>
<li><span class="stability_1"><a href="#fs_fspromises_rmdir_path_options"><code>fsPromises.rmdir(path[, options])</code></a></span></li>
<li><a href="#fs_fspromises_stat_path_options"><code>fsPromises.stat(path[, options])</code></a></li>
<li><a href="#fs_fspromises_symlink_target_path_type"><code>fsPromises.symlink(target, path[, type])</code></a></li>
<li><a href="#fs_fspromises_truncate_path_len"><code>fsPromises.truncate(path[, len])</code></a></li>
<li><a href="#fs_fspromises_unlink_path"><code>fsPromises.unlink(path)</code></a></li>
<li><a href="#fs_fspromises_utimes_path_atime_mtime"><code>fsPromises.utimes(path, atime, mtime)</code></a></li>
<li><a href="#fs_fspromises_writefile_file_data_options"><code>fsPromises.writeFile(file, data[, options])</code></a></li>
</ul>
</li>
<li>
<p><a href="#fs_fs_constants_1">FS constants</a></p>
<ul>
<li><a href="#fs_file_access_constants">File access constants</a></li>
<li><a href="#fs_file_copy_constants">File copy constants</a></li>
<li><a href="#fs_file_open_constants">File open constants</a></li>
<li><a href="#fs_file_type_constants">File type constants</a></li>
<li><a href="#fs_file_mode_constants">File mode constants</a></li>
</ul>
</li>
<li><a href="#fs_file_system_flags">File system flags</a></li>
</ul>
</li>
<li>
<p><a href="#globals_global_objects">Global objects</a></p>
<ul>
<li><a href="#globals_class_buffer">Class: <code>Buffer</code></a></li>
<li><a href="#globals_dirname"><code>__dirname</code></a></li>
<li><a href="#globals_filename"><code>__filename</code></a></li>
<li><a href="#globals_clearimmediate_immediateobject"><code>clearImmediate(immediateObject)</code></a></li>
<li><a href="#globals_clearinterval_intervalobject"><code>clearInterval(intervalObject)</code></a></li>
<li><a href="#globals_cleartimeout_timeoutobject"><code>clearTimeout(timeoutObject)</code></a></li>
<li><a href="#globals_console"><code>console</code></a></li>
<li><a href="#globals_exports"><code>exports</code></a></li>
<li><a href="#globals_global"><code>global</code></a></li>
<li><a href="#globals_module"><code>module</code></a></li>
<li><a href="#globals_process"><code>process</code></a></li>
<li><a href="#globals_queuemicrotask_callback"><code>queueMicrotask(callback)</code></a></li>
<li><a href="#globals_require"><code>require()</code></a></li>
<li><a href="#globals_setimmediate_callback_args"><code>setImmediate(callback[, ...args])</code></a></li>
<li><a href="#globals_setinterval_callback_delay_args"><code>setInterval(callback, delay[, ...args])</code></a></li>
<li><a href="#globals_settimeout_callback_delay_args"><code>setTimeout(callback, delay[, ...args])</code></a></li>
<li><a href="#globals_textdecoder"><code>TextDecoder</code></a></li>
<li><a href="#globals_textencoder"><code>TextEncoder</code></a></li>
<li><a href="#globals_url"><code>URL</code></a></li>
<li><a href="#globals_urlsearchparams"><code>URLSearchParams</code></a></li>
<li><a href="#globals_webassembly"><code>WebAssembly</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#http_http">HTTP</a></span></p>
<ul>
<li>
<p><a href="#http_class_http_agent">Class: <code>http.Agent</code></a></p>
<ul>
<li><a href="#http_new_agent_options"><code>new Agent([options])</code></a></li>
<li><a href="#http_agent_createconnection_options_callback"><code>agent.createConnection(options[, callback])</code></a></li>
<li><a href="#http_agent_keepsocketalive_socket"><code>agent.keepSocketAlive(socket)</code></a></li>
<li><a href="#http_agent_reusesocket_socket_request"><code>agent.reuseSocket(socket, request)</code></a></li>
<li><a href="#http_agent_destroy"><code>agent.destroy()</code></a></li>
<li><a href="#http_agent_freesockets"><code>agent.freeSockets</code></a></li>
<li><a href="#http_agent_getname_options"><code>agent.getName(options)</code></a></li>
<li><a href="#http_agent_maxfreesockets"><code>agent.maxFreeSockets</code></a></li>
<li><a href="#http_agent_maxsockets"><code>agent.maxSockets</code></a></li>
<li><a href="#http_agent_requests"><code>agent.requests</code></a></li>
<li><a href="#http_agent_sockets"><code>agent.sockets</code></a></li>
</ul>
</li>
<li>
<p><a href="#http_class_http_clientrequest">Class: <code>http.ClientRequest</code></a></p>
<ul>
<li><a href="#http_event_abort">Event: <code>'abort'</code></a></li>
<li><a href="#http_event_connect">Event: <code>'connect'</code></a></li>
<li><a href="#http_event_continue">Event: <code>'continue'</code></a></li>
<li><a href="#http_event_information">Event: <code>'information'</code></a></li>
<li><a href="#http_event_response">Event: <code>'response'</code></a></li>
<li><a href="#http_event_socket">Event: <code>'socket'</code></a></li>
<li><a href="#http_event_timeout">Event: <code>'timeout'</code></a></li>
<li><a href="#http_event_upgrade">Event: <code>'upgrade'</code></a></li>
<li><a href="#http_request_abort"><code>request.abort()</code></a></li>
<li><a href="#http_request_aborted"><code>request.aborted</code></a></li>
<li><a href="#http_request_connection"><code>request.connection</code></a></li>
<li><a href="#http_request_end_data_encoding_callback"><code>request.end([data[, encoding]][, callback])</code></a></li>
<li><span class="stability_0"><a href="#http_request_finished"><code>request.finished</code></a></span></li>
<li><a href="#http_request_flushheaders"><code>request.flushHeaders()</code></a></li>
<li><a href="#http_request_getheader_name"><code>request.getHeader(name)</code></a></li>
<li><a href="#http_request_maxheaderscount"><code>request.maxHeadersCount</code></a></li>
<li><a href="#http_request_path"><code>request.path</code></a></li>
<li><a href="#http_request_removeheader_name"><code>request.removeHeader(name)</code></a></li>
<li><a href="#http_request_reusedsocket"><code>request.reusedSocket</code></a></li>
<li><a href="#http_request_setheader_name_value"><code>request.setHeader(name, value)</code></a></li>
<li><a href="#http_request_setnodelay_nodelay"><code>request.setNoDelay([noDelay])</code></a></li>
<li><a href="#http_request_setsocketkeepalive_enable_initialdelay"><code>request.setSocketKeepAlive([enable][, initialDelay])</code></a></li>
<li><a href="#http_request_settimeout_timeout_callback"><code>request.setTimeout(timeout[, callback])</code></a></li>
<li><a href="#http_request_socket"><code>request.socket</code></a></li>
<li><a href="#http_request_writableended"><code>request.writableEnded</code></a></li>
<li><a href="#http_request_writablefinished"><code>request.writableFinished</code></a></li>
<li><a href="#http_request_write_chunk_encoding_callback"><code>request.write(chunk[, encoding][, callback])</code></a></li>
</ul>
</li>
<li>
<p><a href="#http_class_http_server">Class: <code>http.Server</code></a></p>
<ul>
<li><a href="#http_event_checkcontinue">Event: <code>'checkContinue'</code></a></li>
<li><a href="#http_event_checkexpectation">Event: <code>'checkExpectation'</code></a></li>
<li><a href="#http_event_clienterror">Event: <code>'clientError'</code></a></li>
<li><a href="#http_event_close">Event: <code>'close'</code></a></li>
<li><a href="#http_event_connect_1">Event: <code>'connect'</code></a></li>
<li><a href="#http_event_connection">Event: <code>'connection'</code></a></li>
<li><a href="#http_event_request">Event: <code>'request'</code></a></li>
<li><a href="#http_event_upgrade_1">Event: <code>'upgrade'</code></a></li>
<li><a href="#http_server_close_callback"><code>server.close([callback])</code></a></li>
<li><a href="#http_server_headerstimeout"><code>server.headersTimeout</code></a></li>
<li><a href="#http_server_listen"><code>server.listen()</code></a></li>
<li><a href="#http_server_listening"><code>server.listening</code></a></li>
<li><a href="#http_server_maxheaderscount"><code>server.maxHeadersCount</code></a></li>
<li><a href="#http_server_settimeout_msecs_callback"><code>server.setTimeout([msecs][, callback])</code></a></li>
<li><a href="#http_server_timeout"><code>server.timeout</code></a></li>
<li><a href="#http_server_keepalivetimeout"><code>server.keepAliveTimeout</code></a></li>
</ul>
</li>
<li>
<p><a href="#http_class_http_serverresponse">Class: <code>http.ServerResponse</code></a></p>
<ul>
<li><a href="#http_event_close_1">Event: <code>'close'</code></a></li>
<li><a href="#http_event_finish">Event: <code>'finish'</code></a></li>
<li><a href="#http_response_addtrailers_headers"><code>response.addTrailers(headers)</code></a></li>
<li><a href="#http_response_connection"><code>response.connection</code></a></li>
<li><a href="#http_response_cork"><code>response.cork()</code></a></li>
<li><a href="#http_response_end_data_encoding_callback"><code>response.end([data[, encoding]][, callback])</code></a></li>
<li><span class="stability_0"><a href="#http_response_finished"><code>response.finished</code></a></span></li>
<li><a href="#http_response_flushheaders"><code>response.flushHeaders()</code></a></li>
<li><a href="#http_response_getheader_name"><code>response.getHeader(name)</code></a></li>
<li><a href="#http_response_getheadernames"><code>response.getHeaderNames()</code></a></li>
<li><a href="#http_response_getheaders"><code>response.getHeaders()</code></a></li>
<li><a href="#http_response_hasheader_name"><code>response.hasHeader(name)</code></a></li>
<li><a href="#http_response_headerssent"><code>response.headersSent</code></a></li>
<li><a href="#http_response_removeheader_name"><code>response.removeHeader(name)</code></a></li>
<li><a href="#http_response_senddate"><code>response.sendDate</code></a></li>
<li><a href="#http_response_setheader_name_value"><code>response.setHeader(name, value)</code></a></li>
<li><a href="#http_response_settimeout_msecs_callback"><code>response.setTimeout(msecs[, callback])</code></a></li>
<li><a href="#http_response_socket"><code>response.socket</code></a></li>
<li><a href="#http_response_statuscode"><code>response.statusCode</code></a></li>
<li><a href="#http_response_statusmessage"><code>response.statusMessage</code></a></li>
<li><a href="#http_response_uncork"><code>response.uncork()</code></a></li>
<li><a href="#http_response_writableended"><code>response.writableEnded</code></a></li>
<li><a href="#http_response_writablefinished"><code>response.writableFinished</code></a></li>
<li><a href="#http_response_write_chunk_encoding_callback"><code>response.write(chunk[, encoding][, callback])</code></a></li>
<li><a href="#http_response_writecontinue"><code>response.writeContinue()</code></a></li>
<li><a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead(statusCode[, statusMessage][, headers])</code></a></li>
<li><a href="#http_response_writeprocessing"><code>response.writeProcessing()</code></a></li>
</ul>
</li>
<li>
<p><a href="#http_class_http_incomingmessage">Class: <code>http.IncomingMessage</code></a></p>
<ul>
<li><a href="#http_event_aborted">Event: <code>'aborted'</code></a></li>
<li><a href="#http_event_close_2">Event: <code>'close'</code></a></li>
<li><a href="#http_message_aborted"><code>message.aborted</code></a></li>
<li><a href="#http_message_complete"><code>message.complete</code></a></li>
<li><a href="#http_message_destroy_error"><code>message.destroy([error])</code></a></li>
<li><a href="#http_message_headers"><code>message.headers</code></a></li>
<li><a href="#http_message_httpversion"><code>message.httpVersion</code></a></li>
<li><a href="#http_message_method"><code>message.method</code></a></li>
<li><a href="#http_message_rawheaders"><code>message.rawHeaders</code></a></li>
<li><a href="#http_message_rawtrailers"><code>message.rawTrailers</code></a></li>
<li><a href="#http_message_settimeout_msecs_callback"><code>message.setTimeout(msecs[, callback])</code></a></li>
<li><a href="#http_message_socket"><code>message.socket</code></a></li>
<li><a href="#http_message_statuscode"><code>message.statusCode</code></a></li>
<li><a href="#http_message_statusmessage"><code>message.statusMessage</code></a></li>
<li><a href="#http_message_trailers"><code>message.trailers</code></a></li>
<li><a href="#http_message_url"><code>message.url</code></a></li>
</ul>
</li>
<li><a href="#http_http_methods"><code>http.METHODS</code></a></li>
<li><a href="#http_http_status_codes"><code>http.STATUS_CODES</code></a></li>
<li><a href="#http_http_createserver_options_requestlistener"><code>http.createServer([options][, requestListener])</code></a></li>
<li><a href="#http_http_get_options_callback"><code>http.get(options[, callback])</code></a></li>
<li><a href="#http_http_get_url_options_callback"><code>http.get(url[, options][, callback])</code></a></li>
<li><a href="#http_http_globalagent"><code>http.globalAgent</code></a></li>
<li><a href="#http_http_maxheadersize"><code>http.maxHeaderSize</code></a></li>
<li><a href="#http_http_request_options_callback"><code>http.request(options[, callback])</code></a></li>
<li><a href="#http_http_request_url_options_callback"><code>http.request(url[, options][, callback])</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#http2_http_2">HTTP/2</a></span></p>
<ul>
<li>
<p><a href="#http2_core_api">Core API</a></p>
<ul>
<li><a href="#http2_server_side_example">Server-side example</a></li>
<li><a href="#http2_client_side_example">Client-side example</a></li>
<li>
<p><a href="#http2_class_http2session">Class: <code>Http2Session</code></a></p>
<ul>
<li><a href="#http2_http2session_and_sockets"><code>Http2Session</code> and sockets</a></li>
<li><a href="#http2_event_close">Event: <code>'close'</code></a></li>
<li><a href="#http2_event_connect">Event: <code>'connect'</code></a></li>
<li><a href="#http2_event_error">Event: <code>'error'</code></a></li>
<li><a href="#http2_event_frameerror">Event: <code>'frameError'</code></a></li>
<li><a href="#http2_event_goaway">Event: <code>'goaway'</code></a></li>
<li><a href="#http2_event_localsettings">Event: <code>'localSettings'</code></a></li>
<li><a href="#http2_event_ping">Event: <code>'ping'</code></a></li>
<li><a href="#http2_event_remotesettings">Event: <code>'remoteSettings'</code></a></li>
<li><a href="#http2_event_stream">Event: <code>'stream'</code></a></li>
<li><a href="#http2_event_timeout">Event: <code>'timeout'</code></a></li>
<li><a href="#http2_http2session_alpnprotocol"><code>http2session.alpnProtocol</code></a></li>
<li><a href="#http2_http2session_close_callback"><code>http2session.close([callback])</code></a></li>
<li><a href="#http2_http2session_closed"><code>http2session.closed</code></a></li>
<li><a href="#http2_http2session_connecting"><code>http2session.connecting</code></a></li>
<li><a href="#http2_http2session_destroy_error_code"><code>http2session.destroy([error][, code])</code></a></li>
<li><a href="#http2_http2session_destroyed"><code>http2session.destroyed</code></a></li>
<li><a href="#http2_http2session_encrypted"><code>http2session.encrypted</code></a></li>
<li><a href="#http2_http2session_goaway_code_laststreamid_opaquedata"><code>http2session.goaway([code[, lastStreamID[, opaqueData]]])</code></a></li>
<li><a href="#http2_http2session_localsettings"><code>http2session.localSettings</code></a></li>
<li><a href="#http2_http2session_originset"><code>http2session.originSet</code></a></li>
<li><a href="#http2_http2session_pendingsettingsack"><code>http2session.pendingSettingsAck</code></a></li>
<li><a href="#http2_http2session_ping_payload_callback"><code>http2session.ping([payload, ]callback)</code></a></li>
<li><a href="#http2_http2session_ref"><code>http2session.ref()</code></a></li>
<li><a href="#http2_http2session_remotesettings"><code>http2session.remoteSettings</code></a></li>
<li><a href="#http2_http2session_settimeout_msecs_callback"><code>http2session.setTimeout(msecs, callback)</code></a></li>
<li><a href="#http2_http2session_socket"><code>http2session.socket</code></a></li>
<li><a href="#http2_http2session_state"><code>http2session.state</code></a></li>
<li><a href="#http2_http2session_settings_settings_callback"><code>http2session.settings([settings][, callback])</code></a></li>
<li><a href="#http2_http2session_type"><code>http2session.type</code></a></li>
<li><a href="#http2_http2session_unref"><code>http2session.unref()</code></a></li>
</ul>
</li>
<li>
<p><a href="#http2_class_serverhttp2session">Class: <code>ServerHttp2Session</code></a></p>
<ul>
<li><a href="#http2_serverhttp2session_altsvc_alt_originorstream"><code>serverhttp2session.altsvc(alt, originOrStream)</code></a></li>
<li><a href="#http2_specifying_alternative_services">Specifying alternative services</a></li>
<li><a href="#http2_serverhttp2session_origin_origins"><code>serverhttp2session.origin(...origins)</code></a></li>
</ul>
</li>
<li>
<p><a href="#http2_class_clienthttp2session">Class: <code>ClientHttp2Session</code></a></p>
<ul>
<li><a href="#http2_event_altsvc">Event: <code>'altsvc'</code></a></li>
<li><a href="#http2_event_origin">Event: <code>'origin'</code></a></li>
<li><a href="#http2_clienthttp2session_request_headers_options"><code>clienthttp2session.request(headers[, options])</code></a></li>
</ul>
</li>
<li>
<p><a href="#http2_class_http2stream">Class: <code>Http2Stream</code></a></p>
<ul>
<li>
<p><a href="#http2_http2stream_lifecycle"><code>Http2Stream</code> Lifecycle</a></p>
<ul>
<li><a href="#http2_creation">Creation</a></li>
<li><a href="#http2_destruction">Destruction</a></li>
</ul>
</li>
<li><a href="#http2_event_aborted">Event: <code>'aborted'</code></a></li>
<li><a href="#http2_event_close_1">Event: <code>'close'</code></a></li>
<li><a href="#http2_event_error_1">Event: <code>'error'</code></a></li>
<li><a href="#http2_event_frameerror_1">Event: <code>'frameError'</code></a></li>
<li><a href="#http2_event_timeout_1">Event: <code>'timeout'</code></a></li>
<li><a href="#http2_event_trailers">Event: <code>'trailers'</code></a></li>
<li><a href="#http2_event_wanttrailers">Event: <code>'wantTrailers'</code></a></li>
<li><a href="#http2_http2stream_aborted"><code>http2stream.aborted</code></a></li>
<li><a href="#http2_http2stream_buffersize"><code>http2stream.bufferSize</code></a></li>
<li><a href="#http2_http2stream_close_code_callback"><code>http2stream.close(code[, callback])</code></a></li>
<li><a href="#http2_http2stream_closed"><code>http2stream.closed</code></a></li>
<li><a href="#http2_http2stream_destroyed"><code>http2stream.destroyed</code></a></li>
<li><a href="#http2_http2stream_endafterheaders"><code>http2stream.endAfterHeaders</code></a></li>
<li><a href="#http2_http2stream_id"><code>http2stream.id</code></a></li>
<li><a href="#http2_http2stream_pending"><code>http2stream.pending</code></a></li>
<li><a href="#http2_http2stream_priority_options"><code>http2stream.priority(options)</code></a></li>
<li><a href="#http2_http2stream_rstcode"><code>http2stream.rstCode</code></a></li>
<li><a href="#http2_http2stream_sentheaders"><code>http2stream.sentHeaders</code></a></li>
<li><a href="#http2_http2stream_sentinfoheaders"><code>http2stream.sentInfoHeaders</code></a></li>
<li><a href="#http2_http2stream_senttrailers"><code>http2stream.sentTrailers</code></a></li>
<li><a href="#http2_http2stream_session"><code>http2stream.session</code></a></li>
<li><a href="#http2_http2stream_settimeout_msecs_callback"><code>http2stream.setTimeout(msecs, callback)</code></a></li>
<li><a href="#http2_http2stream_state"><code>http2stream.state</code></a></li>
<li><a href="#http2_http2stream_sendtrailers_headers"><code>http2stream.sendTrailers(headers)</code></a></li>
</ul>
</li>
<li>
<p><a href="#http2_class_clienthttp2stream">Class: <code>ClientHttp2Stream</code></a></p>
<ul>
<li><a href="#http2_event_continue">Event: <code>'continue'</code></a></li>
<li><a href="#http2_event_headers">Event: <code>'headers'</code></a></li>
<li><a href="#http2_event_push">Event: <code>'push'</code></a></li>
<li><a href="#http2_event_response">Event: <code>'response'</code></a></li>
</ul>
</li>
<li>
<p><a href="#http2_class_serverhttp2stream">Class: <code>ServerHttp2Stream</code></a></p>
<ul>
<li><a href="#http2_http2stream_additionalheaders_headers"><code>http2stream.additionalHeaders(headers)</code></a></li>
<li><a href="#http2_http2stream_headerssent"><code>http2stream.headersSent</code></a></li>
<li><a href="#http2_http2stream_pushallowed"><code>http2stream.pushAllowed</code></a></li>
<li><a href="#http2_http2stream_pushstream_headers_options_callback"><code>http2stream.pushStream(headers[, options], callback)</code></a></li>
<li><a href="#http2_http2stream_respond_headers_options"><code>http2stream.respond([headers[, options]])</code></a></li>
<li><a href="#http2_http2stream_respondwithfd_fd_headers_options"><code>http2stream.respondWithFD(fd[, headers[, options]])</code></a></li>
<li><a href="#http2_http2stream_respondwithfile_path_headers_options"><code>http2stream.respondWithFile(path[, headers[, options]])</code></a></li>
</ul>
</li>
<li>
<p><a href="#http2_class_http2server">Class: <code>Http2Server</code></a></p>
<ul>
<li><a href="#http2_event_checkcontinue">Event: <code>'checkContinue'</code></a></li>
<li><a href="#http2_event_request">Event: <code>'request'</code></a></li>
<li><a href="#http2_event_session">Event: <code>'session'</code></a></li>
<li><a href="#http2_event_sessionerror">Event: <code>'sessionError'</code></a></li>
<li><a href="#http2_event_stream_1">Event: <code>'stream'</code></a></li>
<li><a href="#http2_event_timeout_2">Event: <code>'timeout'</code></a></li>
<li><a href="#http2_server_close_callback"><code>server.close([callback])</code></a></li>
<li><a href="#http2_server_settimeout_msecs_callback"><code>server.setTimeout([msecs][, callback])</code></a></li>
</ul>
</li>
<li>
<p><a href="#http2_class_http2secureserver">Class: <code>Http2SecureServer</code></a></p>
<ul>
<li><a href="#http2_event_checkcontinue_1">Event: <code>'checkContinue'</code></a></li>
<li><a href="#http2_event_request_1">Event: <code>'request'</code></a></li>
<li><a href="#http2_event_session_1">Event: <code>'session'</code></a></li>
<li><a href="#http2_event_sessionerror_1">Event: <code>'sessionError'</code></a></li>
<li><a href="#http2_event_stream_2">Event: <code>'stream'</code></a></li>
<li><a href="#http2_event_timeout_3">Event: <code>'timeout'</code></a></li>
<li><a href="#http2_event_unknownprotocol">Event: <code>'unknownProtocol'</code></a></li>
<li><a href="#http2_server_close_callback_1"><code>server.close([callback])</code></a></li>
<li><a href="#http2_server_settimeout_msecs_callback_1"><code>server.setTimeout([msecs][, callback])</code></a></li>
</ul>
</li>
<li><a href="#http2_http2_createserver_options_onrequesthandler"><code>http2.createServer(options[, onRequestHandler])</code></a></li>
<li><a href="#http2_http2_createsecureserver_options_onrequesthandler"><code>http2.createSecureServer(options[, onRequestHandler])</code></a></li>
<li><a href="#http2_http2_connect_authority_options_listener"><code>http2.connect(authority[, options][, listener])</code></a></li>
<li>
<p><a href="#http2_http2_constants"><code>http2.constants</code></a></p>
<ul>
<li><a href="#http2_error_codes_for_rst_stream_and_goaway">Error codes for <code>RST_STREAM</code> and <code>GOAWAY</code></a></li>
</ul>
</li>
<li><a href="#http2_http2_getdefaultsettings"><code>http2.getDefaultSettings()</code></a></li>
<li><a href="#http2_http2_getpackedsettings_settings"><code>http2.getPackedSettings([settings])</code></a></li>
<li><a href="#http2_http2_getunpackedsettings_buf"><code>http2.getUnpackedSettings(buf)</code></a></li>
<li><a href="#http2_headers_object">Headers object</a></li>
<li><a href="#http2_settings_object">Settings object</a></li>
<li><a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a></li>
<li><a href="#http2_error_handling">Error handling</a></li>
<li><a href="#http2_invalid_character_handling_in_header_names_and_values">Invalid character handling in header names and values</a></li>
<li><a href="#http2_push_streams_on_the_client">Push streams on the client</a></li>
<li><a href="#http2_supporting_the_connect_method">Supporting the <code>CONNECT</code> method</a></li>
<li><a href="#http2_the_extended_connect_protocol">The extended <code>CONNECT</code> protocol</a></li>
</ul>
</li>
<li>
<p><a href="#http2_compatibility_api">Compatibility API</a></p>
<ul>
<li><a href="#http2_alpn_negotiation">ALPN negotiation</a></li>
<li>
<p><a href="#http2_class_http2_http2serverrequest">Class: <code>http2.Http2ServerRequest</code></a></p>
<ul>
<li><a href="#http2_event_aborted_1">Event: <code>'aborted'</code></a></li>
<li><a href="#http2_event_close_2">Event: <code>'close'</code></a></li>
<li><a href="#http2_request_aborted"><code>request.aborted</code></a></li>
<li><a href="#http2_request_authority"><code>request.authority</code></a></li>
<li><a href="#http2_request_complete"><code>request.complete</code></a></li>
<li><a href="#http2_request_destroy_error"><code>request.destroy([error])</code></a></li>
<li><a href="#http2_request_headers"><code>request.headers</code></a></li>
<li><a href="#http2_request_httpversion"><code>request.httpVersion</code></a></li>
<li><a href="#http2_request_method"><code>request.method</code></a></li>
<li><a href="#http2_request_rawheaders"><code>request.rawHeaders</code></a></li>
<li><a href="#http2_request_rawtrailers"><code>request.rawTrailers</code></a></li>
<li><a href="#http2_request_scheme"><code>request.scheme</code></a></li>
<li><a href="#http2_request_settimeout_msecs_callback"><code>request.setTimeout(msecs, callback)</code></a></li>
<li><a href="#http2_request_socket"><code>request.socket</code></a></li>
<li><a href="#http2_request_stream"><code>request.stream</code></a></li>
<li><a href="#http2_request_trailers"><code>request.trailers</code></a></li>
<li><a href="#http2_request_url"><code>request.url</code></a></li>
</ul>
</li>
<li>
<p><a href="#http2_class_http2_http2serverresponse">Class: <code>http2.Http2ServerResponse</code></a></p>
<ul>
<li><a href="#http2_event_close_3">Event: <code>'close'</code></a></li>
<li><a href="#http2_event_finish">Event: <code>'finish'</code></a></li>
<li><a href="#http2_response_addtrailers_headers"><code>response.addTrailers(headers)</code></a></li>
<li><a href="#http2_response_connection"><code>response.connection</code></a></li>
<li><a href="#http2_response_end_data_encoding_callback"><code>response.end([data[, encoding]][, callback])</code></a></li>
<li><span class="stability_0"><a href="#http2_response_finished"><code>response.finished</code></a></span></li>
<li><a href="#http2_response_getheader_name"><code>response.getHeader(name)</code></a></li>
<li><a href="#http2_response_getheadernames"><code>response.getHeaderNames()</code></a></li>
<li><a href="#http2_response_getheaders"><code>response.getHeaders()</code></a></li>
<li><a href="#http2_response_hasheader_name"><code>response.hasHeader(name)</code></a></li>
<li><a href="#http2_response_headerssent"><code>response.headersSent</code></a></li>
<li><a href="#http2_response_removeheader_name"><code>response.removeHeader(name)</code></a></li>
<li><a href="#http2_response_senddate"><code>response.sendDate</code></a></li>
<li><a href="#http2_response_setheader_name_value"><code>response.setHeader(name, value)</code></a></li>
<li><a href="#http2_response_settimeout_msecs_callback"><code>response.setTimeout(msecs[, callback])</code></a></li>
<li><a href="#http2_response_socket"><code>response.socket</code></a></li>
<li><a href="#http2_response_statuscode"><code>response.statusCode</code></a></li>
<li><a href="#http2_response_statusmessage"><code>response.statusMessage</code></a></li>
<li><a href="#http2_response_stream"><code>response.stream</code></a></li>
<li><a href="#http2_response_writableended"><code>response.writableEnded</code></a></li>
<li><a href="#http2_response_write_chunk_encoding_callback"><code>response.write(chunk[, encoding][, callback])</code></a></li>
<li><a href="#http2_response_writecontinue"><code>response.writeContinue()</code></a></li>
<li><a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead(statusCode[, statusMessage][, headers])</code></a></li>
<li><a href="#http2_response_createpushresponse_headers_callback"><code>response.createPushResponse(headers, callback)</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#http2_collecting_http_2_performance_metrics">Collecting HTTP/2 performance metrics</a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#https_https">HTTPS</a></span></p>
<ul>
<li>
<p><a href="#https_class_https_agent">Class: <code>https.Agent</code></a></p>
<ul>
<li>
<p><a href="#https_new_agent_options"><code>new Agent([options])</code></a></p>
<ul>
<li><a href="#https_event_keylog">Event: <code>'keylog'</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#https_class_https_server">Class: <code>https.Server</code></a></p>
<ul>
<li><a href="#https_server_close_callback"><code>server.close([callback])</code></a></li>
<li><a href="#https_server_headerstimeout"><code>server.headersTimeout</code></a></li>
<li><a href="#https_server_listen"><code>server.listen()</code></a></li>
<li><a href="#https_server_maxheaderscount"><code>server.maxHeadersCount</code></a></li>
<li><a href="#https_server_settimeout_msecs_callback"><code>server.setTimeout([msecs][, callback])</code></a></li>
<li><a href="#https_server_timeout"><code>server.timeout</code></a></li>
<li><a href="#https_server_keepalivetimeout"><code>server.keepAliveTimeout</code></a></li>
</ul>
</li>
<li><a href="#https_https_createserver_options_requestlistener"><code>https.createServer([options][, requestListener])</code></a></li>
<li><a href="#https_https_get_options_callback"><code>https.get(options[, callback])</code></a></li>
<li><a href="#https_https_get_url_options_callback"><code>https.get(url[, options][, callback])</code></a></li>
<li><a href="#https_https_globalagent"><code>https.globalAgent</code></a></li>
<li><a href="#https_https_request_options_callback"><code>https.request(options[, callback])</code></a></li>
<li><a href="#https_https_request_url_options_callback"><code>https.request(url[, options][, callback])</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_1"><a href="#inspector_inspector">Inspector</a></span></p>
<ul>
<li><a href="#inspector_inspector_close"><code>inspector.close()</code></a></li>
<li><a href="#inspector_inspector_console"><code>inspector.console</code></a></li>
<li><a href="#inspector_inspector_open_port_host_wait"><code>inspector.open([port[, host[, wait]]])</code></a></li>
<li><a href="#inspector_inspector_url"><code>inspector.url()</code></a></li>
<li><a href="#inspector_inspector_waitfordebugger"><code>inspector.waitForDebugger()</code></a></li>
<li>
<p><a href="#inspector_class_inspector_session">Class: <code>inspector.Session</code></a></p>
<ul>
<li><a href="#inspector_constructor_new_inspector_session">Constructor: <code>new inspector.Session()</code></a></li>
<li><a href="#inspector_event_inspectornotification">Event: <code>'inspectorNotification'</code></a></li>
<li><a href="#inspector_event_inspector_protocol_method">Event: <code>&#x3C;inspector-protocol-method></code>;</a></li>
<li><a href="#inspector_session_connect"><code>session.connect()</code></a></li>
<li><a href="#inspector_session_connecttomainthread"><code>session.connectToMainThread()</code></a></li>
<li><a href="#inspector_session_disconnect"><code>session.disconnect()</code></a></li>
<li><a href="#inspector_session_post_method_params_callback"><code>session.post(method[, params][, callback])</code></a></li>
</ul>
</li>
<li>
<p><a href="#inspector_example_usage">Example usage</a></p>
<ul>
<li><a href="#inspector_cpu_profiler">CPU profiler</a></li>
<li><a href="#inspector_heap_profiler">Heap profiler</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#intl_internationalization_support">Internationalization support</a></p>
<ul>
<li>
<p><a href="#intl_options_for_building_node_js">Options for building Node.js</a></p>
<ul>
<li><a href="#intl_disable_all_internationalization_features_none">Disable all internationalization features (<code>none</code>)</a></li>
<li><a href="#intl_build_with_a_pre_installed_icu_system_icu">Build with a pre-installed ICU (<code>system-icu</code>)</a></li>
<li>
<p><a href="#intl_embed_a_limited_set_of_icu_data_small_icu">Embed a limited set of ICU data (<code>small-icu</code>)</a></p>
<ul>
<li><a href="#intl_providing_icu_data_at_runtime">Providing ICU data at runtime</a></li>
</ul>
</li>
<li><a href="#intl_embed_the_entire_icu_full_icu">Embed the entire ICU (<code>full-icu</code>)</a></li>
</ul>
</li>
<li><a href="#intl_detecting_internationalization_support">Detecting internationalization support</a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#modules_modules">Modules</a></span></p>
<ul>
<li><a href="#modules_accessing_the_main_module">Accessing the main module</a></li>
<li><a href="#modules_addenda_package_manager_tips">Addenda: Package manager tips</a></li>
<li><a href="#modules_addenda_the_mjs_extension">Addenda: The <code>.mjs</code> extension</a></li>
<li><a href="#modules_all_together">All together...</a></li>
<li>
<p><a href="#modules_caching">Caching</a></p>
<ul>
<li><a href="#modules_module_caching_caveats">Module caching caveats</a></li>
</ul>
</li>
<li><a href="#modules_core_modules">Core modules</a></li>
<li><a href="#modules_cycles">Cycles</a></li>
<li><a href="#modules_file_modules">File modules</a></li>
<li><a href="#modules_folders_as_modules">Folders as modules</a></li>
<li><a href="#modules_loading_from_node_modules_folders">Loading from <code>node_modules</code> folders</a></li>
<li><a href="#modules_loading_from_the_global_folders">Loading from the global folders</a></li>
<li><a href="#modules_the_module_wrapper">The module wrapper</a></li>
<li>
<p><a href="#modules_the_module_scope">The module scope</a></p>
<ul>
<li><a href="#modules_dirname"><code>__dirname</code></a></li>
<li><a href="#modules_filename"><code>__filename</code></a></li>
<li><a href="#modules_exports"><code>exports</code></a></li>
<li><a href="#modules_module"><code>module</code></a></li>
<li>
<p><a href="#modules_require_id"><code>require(id)</code></a></p>
<ul>
<li><a href="#modules_require_cache"><code>require.cache</code></a></li>
<li><span class="stability_0"><a href="#modules_require_extensions"><code>require.extensions</code></a></span></li>
<li><a href="#modules_require_main"><code>require.main</code></a></li>
<li>
<p><a href="#modules_require_resolve_request_options"><code>require.resolve(request[, options])</code></a></p>
<ul>
<li><a href="#modules_require_resolve_paths_request"><code>require.resolve.paths(request)</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#modules_the_module_object">The <code>module</code> object</a></p>
<ul>
<li><a href="#modules_module_children"><code>module.children</code></a></li>
<li>
<p><a href="#modules_module_exports"><code>module.exports</code></a></p>
<ul>
<li><a href="#modules_exports_shortcut"><code>exports</code> shortcut</a></li>
</ul>
</li>
<li><a href="#modules_module_filename"><code>module.filename</code></a></li>
<li><a href="#modules_module_id"><code>module.id</code></a></li>
<li><a href="#modules_module_loaded"><code>module.loaded</code></a></li>
<li><a href="#modules_module_parent"><code>module.parent</code></a></li>
<li><a href="#modules_module_path"><code>module.path</code></a></li>
<li><a href="#modules_module_paths"><code>module.paths</code></a></li>
<li><a href="#modules_module_require_id"><code>module.require(id)</code></a></li>
</ul>
</li>
<li>
<p><a href="#modules_the_module_object_1">The <code>Module</code> object</a></p>
<ul>
<li><a href="#modules_module_builtinmodules"><code>module.builtinModules</code></a></li>
<li><a href="#modules_module_createrequire_filename"><code>module.createRequire(filename)</code></a></li>
<li><span class="stability_0"><a href="#modules_module_createrequirefrompath_filename"><code>module.createRequireFromPath(filename)</code></a></span></li>
<li><a href="#modules_module_syncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_1"><a href="#modules_source_map_v3_support">Source map v3 support</a></span></p>
<ul>
<li><a href="#modules_module_findsourcemap_path_error"><code>module.findSourceMap(path[, error])</code></a></li>
<li>
<p><a href="#modules_class_module_sourcemap">Class: <code>module.SourceMap</code></a></p>
<ul>
<li><a href="#modules_new_sourcemap_payload"><code>new SourceMap(payload)</code></a></li>
<li><a href="#modules_sourcemap_payload"><code>sourceMap.payload</code></a></li>
<li><a href="#modules_sourcemap_findentry_linenumber_columnnumber"><code>sourceMap.findEntry(lineNumber, columnNumber)</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#net_net">Net</a></span></p>
<ul>
<li>
<p><a href="#net_ipc_support">IPC support</a></p>
<ul>
<li><a href="#net_identifying_paths_for_ipc_connections">Identifying paths for IPC connections</a></li>
</ul>
</li>
<li>
<p><a href="#net_class_net_server">Class: <code>net.Server</code></a></p>
<ul>
<li><a href="#net_new_net_server_options_connectionlistener"><code>new net.Server([options][, connectionListener])</code></a></li>
<li><a href="#net_event_close">Event: <code>'close'</code></a></li>
<li><a href="#net_event_connection">Event: <code>'connection'</code></a></li>
<li><a href="#net_event_error">Event: <code>'error'</code></a></li>
<li><a href="#net_event_listening">Event: <code>'listening'</code></a></li>
<li><a href="#net_server_address"><code>server.address()</code></a></li>
<li><a href="#net_server_close_callback"><code>server.close([callback])</code></a></li>
<li><span class="stability_0"><a href="#net_server_connections"><code>server.connections</code></a></span></li>
<li><a href="#net_server_getconnections_callback"><code>server.getConnections(callback)</code></a></li>
<li>
<p><a href="#net_server_listen"><code>server.listen()</code></a></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></li>
<li><a href="#net_server_listen_port_host_backlog_callback"><code>server.listen([port[, host[, backlog]]][, callback])</code></a></li>
</ul>
</li>
<li><a href="#net_server_listening"><code>server.listening</code></a></li>
<li><a href="#net_server_maxconnections"><code>server.maxConnections</code></a></li>
<li><a href="#net_server_ref"><code>server.ref()</code></a></li>
<li><a href="#net_server_unref"><code>server.unref()</code></a></li>
</ul>
</li>
<li>
<p><a href="#net_class_net_socket">Class: <code>net.Socket</code></a></p>
<ul>
<li><a href="#net_new_net_socket_options"><code>new net.Socket([options])</code></a></li>
<li><a href="#net_event_close_1">Event: <code>'close'</code></a></li>
<li><a href="#net_event_connect">Event: <code>'connect'</code></a></li>
<li><a href="#net_event_data">Event: <code>'data'</code></a></li>
<li><a href="#net_event_drain">Event: <code>'drain'</code></a></li>
<li><a href="#net_event_end">Event: <code>'end'</code></a></li>
<li><a href="#net_event_error_1">Event: <code>'error'</code></a></li>
<li><a href="#net_event_lookup">Event: <code>'lookup'</code></a></li>
<li><a href="#net_event_ready">Event: <code>'ready'</code></a></li>
<li><a href="#net_event_timeout">Event: <code>'timeout'</code></a></li>
<li><a href="#net_socket_address"><code>socket.address()</code></a></li>
<li><a href="#net_socket_buffersize"><code>socket.bufferSize</code></a></li>
<li><a href="#net_socket_bytesread"><code>socket.bytesRead</code></a></li>
<li><a href="#net_socket_byteswritten"><code>socket.bytesWritten</code></a></li>
<li>
<p><a href="#net_socket_connect"><code>socket.connect()</code></a></p>
<ul>
<li><a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a></li>
<li><a href="#net_socket_connect_path_connectlistener"><code>socket.connect(path[, connectListener])</code></a></li>
<li><a href="#net_socket_connect_port_host_connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a></li>
</ul>
</li>
<li><a href="#net_socket_connecting"><code>socket.connecting</code></a></li>
<li><a href="#net_socket_destroy_error"><code>socket.destroy([error])</code></a></li>
<li><a href="#net_socket_destroyed"><code>socket.destroyed</code></a></li>
<li><a href="#net_socket_end_data_encoding_callback"><code>socket.end([data[, encoding]][, callback])</code></a></li>
<li><a href="#net_socket_localaddress"><code>socket.localAddress</code></a></li>
<li><a href="#net_socket_localport"><code>socket.localPort</code></a></li>
<li><a href="#net_socket_pause"><code>socket.pause()</code></a></li>
<li><a href="#net_socket_pending"><code>socket.pending</code></a></li>
<li><a href="#net_socket_ref"><code>socket.ref()</code></a></li>
<li><a href="#net_socket_remoteaddress"><code>socket.remoteAddress</code></a></li>
<li><a href="#net_socket_remotefamily"><code>socket.remoteFamily</code></a></li>
<li><a href="#net_socket_remoteport"><code>socket.remotePort</code></a></li>
<li><a href="#net_socket_resume"><code>socket.resume()</code></a></li>
<li><a href="#net_socket_setencoding_encoding"><code>socket.setEncoding([encoding])</code></a></li>
<li><a href="#net_socket_setkeepalive_enable_initialdelay"><code>socket.setKeepAlive([enable][, initialDelay])</code></a></li>
<li><a href="#net_socket_setnodelay_nodelay"><code>socket.setNoDelay([noDelay])</code></a></li>
<li><a href="#net_socket_settimeout_timeout_callback"><code>socket.setTimeout(timeout[, callback])</code></a></li>
<li><a href="#net_socket_unref"><code>socket.unref()</code></a></li>
<li><a href="#net_socket_write_data_encoding_callback"><code>socket.write(data[, encoding][, callback])</code></a></li>
</ul>
</li>
<li>
<p><a href="#net_net_connect"><code>net.connect()</code></a></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></li>
<li><a href="#net_net_connect_port_host_connectlistener"><code>net.connect(port[, host][, connectListener])</code></a></li>
</ul>
</li>
<li>
<p><a href="#net_net_createconnection"><code>net.createConnection()</code></a></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></li>
<li><a href="#net_net_createconnection_port_host_connectlistener"><code>net.createConnection(port[, host][, connectListener])</code></a></li>
</ul>
</li>
<li><a href="#net_net_createserver_options_connectionlistener"><code>net.createServer([options][, connectionListener])</code></a></li>
<li><a href="#net_net_isip_input"><code>net.isIP(input)</code></a></li>
<li><a href="#net_net_isipv4_input"><code>net.isIPv4(input)</code></a></li>
<li><a href="#net_net_isipv6_input"><code>net.isIPv6(input)</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#os_os">OS</a></span></p>
<ul>
<li><a href="#os_os_eol"><code>os.EOL</code></a></li>
<li><a href="#os_os_arch"><code>os.arch()</code></a></li>
<li><a href="#os_os_constants"><code>os.constants</code></a></li>
<li><a href="#os_os_cpus"><code>os.cpus()</code></a></li>
<li><a href="#os_os_endianness"><code>os.endianness()</code></a></li>
<li><a href="#os_os_freemem"><code>os.freemem()</code></a></li>
<li><a href="#os_os_getpriority_pid"><code>os.getPriority([pid])</code></a></li>
<li><a href="#os_os_homedir"><code>os.homedir()</code></a></li>
<li><a href="#os_os_hostname"><code>os.hostname()</code></a></li>
<li><a href="#os_os_loadavg"><code>os.loadavg()</code></a></li>
<li><a href="#os_os_networkinterfaces"><code>os.networkInterfaces()</code></a></li>
<li><a href="#os_os_platform"><code>os.platform()</code></a></li>
<li><a href="#os_os_release"><code>os.release()</code></a></li>
<li><a href="#os_os_setpriority_pid_priority"><code>os.setPriority([pid, ]priority)</code></a></li>
<li><a href="#os_os_tmpdir"><code>os.tmpdir()</code></a></li>
<li><a href="#os_os_totalmem"><code>os.totalmem()</code></a></li>
<li><a href="#os_os_type"><code>os.type()</code></a></li>
<li><a href="#os_os_uptime"><code>os.uptime()</code></a></li>
<li><a href="#os_os_userinfo_options"><code>os.userInfo([options])</code></a></li>
<li><a href="#os_os_version"><code>os.version()</code></a></li>
<li>
<p><a href="#os_os_constants_1">OS constants</a></p>
<ul>
<li><a href="#os_signal_constants">Signal constants</a></li>
<li>
<p><a href="#os_error_constants">Error constants</a></p>
<ul>
<li><a href="#os_posix_error_constants">POSIX error constants</a></li>
<li><a href="#os_windows_specific_error_constants">Windows-specific error constants</a></li>
</ul>
</li>
<li><a href="#os_dlopen_constants">dlopen constants</a></li>
<li><a href="#os_priority_constants">Priority constants</a></li>
<li><a href="#os_libuv_constants">libuv constants</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#path_path">Path</a></span></p>
<ul>
<li><a href="#path_windows_vs_posix">Windows vs. POSIX</a></li>
<li><a href="#path_path_basename_path_ext"><code>path.basename(path[, ext])</code></a></li>
<li><a href="#path_path_delimiter"><code>path.delimiter</code></a></li>
<li><a href="#path_path_dirname_path"><code>path.dirname(path)</code></a></li>
<li><a href="#path_path_extname_path"><code>path.extname(path)</code></a></li>
<li><a href="#path_path_format_pathobject"><code>path.format(pathObject)</code></a></li>
<li><a href="#path_path_isabsolute_path"><code>path.isAbsolute(path)</code></a></li>
<li><a href="#path_path_join_paths"><code>path.join([...paths])</code></a></li>
<li><a href="#path_path_normalize_path"><code>path.normalize(path)</code></a></li>
<li><a href="#path_path_parse_path"><code>path.parse(path)</code></a></li>
<li><a href="#path_path_posix"><code>path.posix</code></a></li>
<li><a href="#path_path_relative_from_to"><code>path.relative(from, to)</code></a></li>
<li><a href="#path_path_resolve_paths"><code>path.resolve([...paths])</code></a></li>
<li><a href="#path_path_sep"><code>path.sep</code></a></li>
<li><a href="#path_path_tonamespacedpath_path"><code>path.toNamespacedPath(path)</code></a></li>
<li><a href="#path_path_win32"><code>path.win32</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#perf_hooks_performance_measurement_apis">Performance measurement APIs</a></span></p>
<ul>
<li>
<p><a href="#perf_hooks_perf_hooks_performance"><code>perf_hooks.performance</code></a></p>
<ul>
<li><a href="#perf_hooks_performance_clearmarks_name"><code>performance.clearMarks([name])</code></a></li>
<li><a href="#perf_hooks_performance_mark_name"><code>performance.mark([name])</code></a></li>
<li><a href="#perf_hooks_performance_measure_name_startmark_endmark"><code>performance.measure(name[, startMark[, endMark]])</code></a></li>
<li><a href="#perf_hooks_performance_nodetiming"><code>performance.nodeTiming</code></a></li>
<li><a href="#perf_hooks_performance_now"><code>performance.now()</code></a></li>
<li><a href="#perf_hooks_performance_timeorigin"><code>performance.timeOrigin</code></a></li>
<li><a href="#perf_hooks_performance_timerify_fn"><code>performance.timerify(fn)</code></a></li>
</ul>
</li>
<li>
<p><a href="#perf_hooks_class_performanceentry">Class: <code>PerformanceEntry</code></a></p>
<ul>
<li><a href="#perf_hooks_performanceentry_duration"><code>performanceEntry.duration</code></a></li>
<li><a href="#perf_hooks_performanceentry_name"><code>performanceEntry.name</code></a></li>
<li><a href="#perf_hooks_performanceentry_starttime"><code>performanceEntry.startTime</code></a></li>
<li><a href="#perf_hooks_performanceentry_entrytype"><code>performanceEntry.entryType</code></a></li>
<li><a href="#perf_hooks_performanceentry_kind"><code>performanceEntry.kind</code></a></li>
<li><a href="#perf_hooks_performanceentry_flags">performanceEntry.flags</a></li>
</ul>
</li>
<li>
<p><a href="#perf_hooks_class_performancenodetiming_extends_performanceentry">Class: <code>PerformanceNodeTiming extends PerformanceEntry</code></a></p>
<ul>
<li><a href="#perf_hooks_performancenodetiming_bootstrapcomplete"><code>performanceNodeTiming.bootstrapComplete</code></a></li>
<li><a href="#perf_hooks_performancenodetiming_environment"><code>performanceNodeTiming.environment</code></a></li>
<li><a href="#perf_hooks_performancenodetiming_loopexit"><code>performanceNodeTiming.loopExit</code></a></li>
<li><a href="#perf_hooks_performancenodetiming_loopstart"><code>performanceNodeTiming.loopStart</code></a></li>
<li><a href="#perf_hooks_performancenodetiming_nodestart"><code>performanceNodeTiming.nodeStart</code></a></li>
<li><a href="#perf_hooks_performancenodetiming_v8start"><code>performanceNodeTiming.v8Start</code></a></li>
</ul>
</li>
<li>
<p><a href="#perf_hooks_class_perf_hooks_performanceobserver">Class: <code>perf_hooks.PerformanceObserver</code></a></p>
<ul>
<li><a href="#perf_hooks_new_performanceobserver_callback"><code>new PerformanceObserver(callback)</code></a></li>
<li><a href="#perf_hooks_performanceobserver_disconnect"><code>performanceObserver.disconnect()</code></a></li>
<li><a href="#perf_hooks_performanceobserver_observe_options"><code>performanceObserver.observe(options)</code></a></li>
</ul>
</li>
<li>
<p><a href="#perf_hooks_class_performanceobserverentrylist">Class: <code>PerformanceObserverEntryList</code></a></p>
<ul>
<li><a href="#perf_hooks_performanceobserverentrylist_getentries"><code>performanceObserverEntryList.getEntries()</code></a></li>
<li><a href="#perf_hooks_performanceobserverentrylist_getentriesbyname_name_type"><code>performanceObserverEntryList.getEntriesByName(name[, type])</code></a></li>
<li><a href="#perf_hooks_performanceobserverentrylist_getentriesbytype_type"><code>performanceObserverEntryList.getEntriesByType(type)</code></a></li>
</ul>
</li>
<li>
<p><a href="#perf_hooks_perf_hooks_monitoreventloopdelay_options"><code>perf_hooks.monitorEventLoopDelay([options])</code></a></p>
<ul>
<li>
<p><a href="#perf_hooks_class_histogram">Class: <code>Histogram</code></a></p>
<ul>
<li><a href="#perf_hooks_histogram_disable"><code>histogram.disable()</code></a></li>
<li><a href="#perf_hooks_histogram_enable"><code>histogram.enable()</code></a></li>
<li><a href="#perf_hooks_histogram_exceeds"><code>histogram.exceeds</code></a></li>
<li><a href="#perf_hooks_histogram_max"><code>histogram.max</code></a></li>
<li><a href="#perf_hooks_histogram_mean"><code>histogram.mean</code></a></li>
<li><a href="#perf_hooks_histogram_min"><code>histogram.min</code></a></li>
<li><a href="#perf_hooks_histogram_percentile_percentile"><code>histogram.percentile(percentile)</code></a></li>
<li><a href="#perf_hooks_histogram_percentiles"><code>histogram.percentiles</code></a></li>
<li><a href="#perf_hooks_histogram_reset"><code>histogram.reset()</code></a></li>
<li><a href="#perf_hooks_histogram_stddev"><code>histogram.stddev</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#perf_hooks_examples">Examples</a></p>
<ul>
<li><a href="#perf_hooks_measuring_the_duration_of_async_operations">Measuring the duration of async operations</a></li>
<li><a href="#perf_hooks_measuring_how_long_it_takes_to_load_dependencies">Measuring how long it takes to load dependencies</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_1"><a href="#policy_policies">Policies</a></span></p>
<ul>
<li><a href="#policy_enabling">Enabling</a></li>
<li>
<p><a href="#policy_features">Features</a></p>
<ul>
<li><a href="#policy_error_behavior">Error behavior</a></li>
<li><a href="#policy_integrity_checks">Integrity checks</a></li>
<li>
<p><a href="#policy_dependency_redirection">Dependency redirection</a></p>
<ul>
<li><a href="#policy_example_patched_dependency">Example: Patched dependency</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#process_process">Process</a></p>
<ul>
<li>
<p><a href="#process_process_events">Process events</a></p>
<ul>
<li><a href="#process_event_beforeexit">Event: <code>'beforeExit'</code></a></li>
<li><a href="#process_event_disconnect">Event: <code>'disconnect'</code></a></li>
<li><a href="#process_event_exit">Event: <code>'exit'</code></a></li>
<li><a href="#process_event_message">Event: <code>'message'</code></a></li>
<li><a href="#process_event_multipleresolves">Event: <code>'multipleResolves'</code></a></li>
<li><a href="#process_event_rejectionhandled">Event: <code>'rejectionHandled'</code></a></li>
<li>
<p><a href="#process_event_uncaughtexception">Event: <code>'uncaughtException'</code></a></p>
<ul>
<li><a href="#process_warning_using_uncaughtexception_correctly">Warning: Using <code>'uncaughtException'</code> correctly</a></li>
</ul>
</li>
<li><a href="#process_event_uncaughtexceptionmonitor">Event: <code>'uncaughtExceptionMonitor'</code></a></li>
<li><a href="#process_event_unhandledrejection">Event: <code>'unhandledRejection'</code></a></li>
<li>
<p><a href="#process_event_warning">Event: <code>'warning'</code></a></p>
<ul>
<li><a href="#process_emitting_custom_warnings">Emitting custom warnings</a></li>
</ul>
</li>
<li><a href="#process_signal_events">Signal events</a></li>
</ul>
</li>
<li><a href="#process_process_abort"><code>process.abort()</code></a></li>
<li><a href="#process_process_allowednodeenvironmentflags"><code>process.allowedNodeEnvironmentFlags</code></a></li>
<li><a href="#process_process_arch"><code>process.arch</code></a></li>
<li><a href="#process_process_argv"><code>process.argv</code></a></li>
<li><a href="#process_process_argv0"><code>process.argv0</code></a></li>
<li><a href="#process_process_channel"><code>process.channel</code></a></li>
<li><a href="#process_process_chdir_directory"><code>process.chdir(directory)</code></a></li>
<li><a href="#process_process_config"><code>process.config</code></a></li>
<li><a href="#process_process_connected"><code>process.connected</code></a></li>
<li><a href="#process_process_cpuusage_previousvalue"><code>process.cpuUsage([previousValue])</code></a></li>
<li><a href="#process_process_cwd"><code>process.cwd()</code></a></li>
<li><a href="#process_process_debugport"><code>process.debugPort</code></a></li>
<li><a href="#process_process_disconnect"><code>process.disconnect()</code></a></li>
<li><a href="#process_process_dlopen_module_filename_flags"><code>process.dlopen(module, filename[, flags])</code></a></li>
<li><a href="#process_process_emitwarning_warning_options"><code>process.emitWarning(warning[, options])</code></a></li>
<li>
<p><a href="#process_process_emitwarning_warning_type_code_ctor"><code>process.emitWarning(warning[, type[, code]][, ctor])</code></a></p>
<ul>
<li><a href="#process_avoiding_duplicate_warnings">Avoiding duplicate warnings</a></li>
</ul>
</li>
<li><a href="#process_process_env"><code>process.env</code></a></li>
<li><a href="#process_process_execargv"><code>process.execArgv</code></a></li>
<li><a href="#process_process_execpath"><code>process.execPath</code></a></li>
<li><a href="#process_process_exit_code"><code>process.exit([code])</code></a></li>
<li><a href="#process_process_exitcode"><code>process.exitCode</code></a></li>
<li><a href="#process_process_getegid"><code>process.getegid()</code></a></li>
<li><a href="#process_process_geteuid"><code>process.geteuid()</code></a></li>
<li><a href="#process_process_getgid"><code>process.getgid()</code></a></li>
<li><a href="#process_process_getgroups"><code>process.getgroups()</code></a></li>
<li><a href="#process_process_getuid"><code>process.getuid()</code></a></li>
<li><a href="#process_process_hasuncaughtexceptioncapturecallback"><code>process.hasUncaughtExceptionCaptureCallback()</code></a></li>
<li><a href="#process_process_hrtime_time"><code>process.hrtime([time])</code></a></li>
<li><a href="#process_process_hrtime_bigint"><code>process.hrtime.bigint()</code></a></li>
<li><a href="#process_process_initgroups_user_extragroup"><code>process.initgroups(user, extraGroup)</code></a></li>
<li><a href="#process_process_kill_pid_signal"><code>process.kill(pid[, signal])</code></a></li>
<li><a href="#process_process_mainmodule"><code>process.mainModule</code></a></li>
<li><a href="#process_process_memoryusage"><code>process.memoryUsage()</code></a></li>
<li><a href="#process_process_nexttick_callback_args"><code>process.nextTick(callback[, ...args])</code></a></li>
<li><a href="#process_process_nodeprecation"><code>process.noDeprecation</code></a></li>
<li><a href="#process_process_pid"><code>process.pid</code></a></li>
<li><a href="#process_process_platform"><code>process.platform</code></a></li>
<li><a href="#process_process_ppid"><code>process.ppid</code></a></li>
<li><a href="#process_process_release"><code>process.release</code></a></li>
<li>
<p><a href="#process_process_report"><code>process.report</code></a></p>
<ul>
<li><a href="#process_process_report_compact"><code>process.report.compact</code></a></li>
<li><a href="#process_process_report_directory"><code>process.report.directory</code></a></li>
<li><a href="#process_process_report_filename"><code>process.report.filename</code></a></li>
<li><a href="#process_process_report_getreport_err"><code>process.report.getReport([err])</code></a></li>
<li><span class="stability_1"><a href="#process_process_report_reportonfatalerror"><code>process.report.reportOnFatalError</code></a></span></li>
<li><a href="#process_process_report_reportonsignal"><code>process.report.reportOnSignal</code></a></li>
<li><a href="#process_process_report_reportonuncaughtexception"><code>process.report.reportOnUncaughtException</code></a></li>
<li><a href="#process_process_report_signal"><code>process.report.signal</code></a></li>
<li><a href="#process_process_report_writereport_filename_err"><code>process.report.writeReport([filename][, err])</code></a></li>
</ul>
</li>
<li><a href="#process_process_resourceusage"><code>process.resourceUsage()</code></a></li>
<li><a href="#process_process_send_message_sendhandle_options_callback"><code>process.send(message[, sendHandle[, options]][, callback])</code></a></li>
<li><a href="#process_process_setegid_id"><code>process.setegid(id)</code></a></li>
<li><a href="#process_process_seteuid_id"><code>process.seteuid(id)</code></a></li>
<li><a href="#process_process_setgid_id"><code>process.setgid(id)</code></a></li>
<li><a href="#process_process_setgroups_groups"><code>process.setgroups(groups)</code></a></li>
<li><a href="#process_process_setuid_id"><code>process.setuid(id)</code></a></li>
<li><a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback(fn)</code></a></li>
<li>
<p><a href="#process_process_stderr"><code>process.stderr</code></a></p>
<ul>
<li><a href="#process_process_stderr_fd"><code>process.stderr.fd</code></a></li>
</ul>
</li>
<li>
<p><a href="#process_process_stdin"><code>process.stdin</code></a></p>
<ul>
<li><a href="#process_process_stdin_fd"><code>process.stdin.fd</code></a></li>
</ul>
</li>
<li>
<p><a href="#process_process_stdout"><code>process.stdout</code></a></p>
<ul>
<li><a href="#process_process_stdout_fd"><code>process.stdout.fd</code></a></li>
<li><a href="#process_a_note_on_process_i_o">A note on process I/O</a></li>
</ul>
</li>
<li><a href="#process_process_throwdeprecation"><code>process.throwDeprecation</code></a></li>
<li><a href="#process_process_title"><code>process.title</code></a></li>
<li><a href="#process_process_tracedeprecation"><code>process.traceDeprecation</code></a></li>
<li><a href="#process_process_umask_mask"><code>process.umask([mask])</code></a></li>
<li><a href="#process_process_uptime"><code>process.uptime()</code></a></li>
<li><a href="#process_process_version"><code>process.version</code></a></li>
<li><a href="#process_process_versions"><code>process.versions</code></a></li>
<li><a href="#process_exit_codes">Exit codes</a></li>
</ul>
</li>
<li>
<p><span class="stability_0"><a href="#punycode_punycode">Punycode</a></span></p>
<ul>
<li><a href="#punycode_punycode_decode_string"><code>punycode.decode(string)</code></a></li>
<li><a href="#punycode_punycode_encode_string"><code>punycode.encode(string)</code></a></li>
<li><a href="#punycode_punycode_toascii_domain"><code>punycode.toASCII(domain)</code></a></li>
<li><a href="#punycode_punycode_tounicode_domain"><code>punycode.toUnicode(domain)</code></a></li>
<li>
<p><a href="#punycode_punycode_ucs2"><code>punycode.ucs2</code></a></p>
<ul>
<li><a href="#punycode_punycode_ucs2_decode_string"><code>punycode.ucs2.decode(string)</code></a></li>
<li><a href="#punycode_punycode_ucs2_encode_codepoints"><code>punycode.ucs2.encode(codePoints)</code></a></li>
</ul>
</li>
<li><a href="#punycode_punycode_version"><code>punycode.version</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#querystring_query_string">Query string</a></span></p>
<ul>
<li><a href="#querystring_querystring_decode"><code>querystring.decode()</code></a></li>
<li><a href="#querystring_querystring_encode"><code>querystring.encode()</code></a></li>
<li><a href="#querystring_querystring_escape_str"><code>querystring.escape(str)</code></a></li>
<li><a href="#querystring_querystring_parse_str_sep_eq_options"><code>querystring.parse(str[, sep[, eq[, options]]])</code></a></li>
<li><a href="#querystring_querystring_stringify_obj_sep_eq_options"><code>querystring.stringify(obj[, sep[, eq[, options]]])</code></a></li>
<li><a href="#querystring_querystring_unescape_str"><code>querystring.unescape(str)</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#readline_readline">Readline</a></span></p>
<ul>
<li>
<p><a href="#readline_class_interface">Class: <code>Interface</code></a></p>
<ul>
<li><a href="#readline_event_close">Event: <code>'close'</code></a></li>
<li><a href="#readline_event_line">Event: <code>'line'</code></a></li>
<li><a href="#readline_event_pause">Event: <code>'pause'</code></a></li>
<li><a href="#readline_event_resume">Event: <code>'resume'</code></a></li>
<li><a href="#readline_event_sigcont">Event: <code>'SIGCONT'</code></a></li>
<li><a href="#readline_event_sigint">Event: <code>'SIGINT'</code></a></li>
<li><a href="#readline_event_sigtstp">Event: <code>'SIGTSTP'</code></a></li>
<li><a href="#readline_rl_close"><code>rl.close()</code></a></li>
<li><a href="#readline_rl_pause"><code>rl.pause()</code></a></li>
<li><a href="#readline_rl_prompt_preservecursor"><code>rl.prompt([preserveCursor])</code></a></li>
<li><a href="#readline_rl_question_query_callback"><code>rl.question(query, callback)</code></a></li>
<li><a href="#readline_rl_resume"><code>rl.resume()</code></a></li>
<li><a href="#readline_rl_setprompt_prompt"><code>rl.setPrompt(prompt)</code></a></li>
<li><a href="#readline_rl_write_data_key"><code>rl.write(data[, key])</code></a></li>
<li><a href="#readline_rl_symbol_asynciterator"><code>rl[Symbol.asyncIterator]()</code></a></li>
<li><a href="#readline_rl_line">rl.line</a></li>
<li><a href="#readline_rl_cursor">rl.cursor</a></li>
<li><a href="#readline_rl_getcursorpos"><code>rl.getCursorPos()</code></a></li>
</ul>
</li>
<li><a href="#readline_readline_clearline_stream_dir_callback"><code>readline.clearLine(stream, dir[, callback])</code></a></li>
<li><a href="#readline_readline_clearscreendown_stream_callback"><code>readline.clearScreenDown(stream[, callback])</code></a></li>
<li>
<p><a href="#readline_readline_createinterface_options"><code>readline.createInterface(options)</code></a></p>
<ul>
<li><a href="#readline_use_of_the_completer_function">Use of the <code>completer</code> function</a></li>
</ul>
</li>
<li><a href="#readline_readline_cursorto_stream_x_y_callback"><code>readline.cursorTo(stream, x[, y][, callback])</code></a></li>
<li><a href="#readline_readline_emitkeypressevents_stream_interface"><code>readline.emitKeypressEvents(stream[, interface])</code></a></li>
<li><a href="#readline_readline_movecursor_stream_dx_dy_callback"><code>readline.moveCursor(stream, dx, dy[, callback])</code></a></li>
<li><a href="#readline_example_tiny_cli">Example: Tiny CLI</a></li>
<li><a href="#readline_example_read_file_stream_line_by_line">Example: Read file stream line-by-Line</a></li>
<li><a href="#readline_tty_keybindings">TTY keybindings</a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#repl_repl">REPL</a></span></p>
<ul>
<li>
<p><a href="#repl_design_and_features">Design and features</a></p>
<ul>
<li><a href="#repl_commands_and_special_keys">Commands and special keys</a></li>
<li>
<p><a href="#repl_default_evaluation">Default evaluation</a></p>
<ul>
<li><a href="#repl_javascript_expressions">JavaScript expressions</a></li>
<li><a href="#repl_global_and_local_scope">Global and local scope</a></li>
<li><a href="#repl_accessing_core_node_js_modules">Accessing core Node.js modules</a></li>
<li><a href="#repl_global_uncaught_exceptions">Global uncaught exceptions</a></li>
<li><a href="#repl_assignment_of_the_underscore_variable">Assignment of the <code>_</code> (underscore) variable</a></li>
<li><a href="#repl_await_keyword"><code>await</code> keyword</a></li>
</ul>
</li>
<li><a href="#repl_reverse_i_search">Reverse-i-search</a></li>
<li>
<p><a href="#repl_custom_evaluation_functions">Custom evaluation functions</a></p>
<ul>
<li><a href="#repl_recoverable_errors">Recoverable errors</a></li>
</ul>
</li>
<li><a href="#repl_customizing_repl_output">Customizing REPL output</a></li>
</ul>
</li>
<li>
<p><a href="#repl_class_replserver">Class: <code>REPLServer</code></a></p>
<ul>
<li><a href="#repl_event_exit">Event: <code>'exit'</code></a></li>
<li><a href="#repl_event_reset">Event: <code>'reset'</code></a></li>
<li><a href="#repl_replserver_definecommand_keyword_cmd"><code>replServer.defineCommand(keyword, cmd)</code></a></li>
<li><a href="#repl_replserver_displayprompt_preservecursor"><code>replServer.displayPrompt([preserveCursor])</code></a></li>
<li><a href="#repl_replserver_clearbufferedcommand"><code>replServer.clearBufferedCommand()</code></a></li>
<li><span class="stability_0"><a href="#repl_replserver_parsereplkeyword_keyword_rest"><code>replServer.parseREPLKeyword(keyword[, rest])</code></a></span></li>
<li><a href="#repl_replserver_setuphistory_historypath_callback"><code>replServer.setupHistory(historyPath, callback)</code></a></li>
</ul>
</li>
<li><a href="#repl_repl_start_options"><code>repl.start([options])</code></a></li>
<li>
<p><a href="#repl_the_node_js_repl">The Node.js REPL</a></p>
<ul>
<li><a href="#repl_environment_variable_options">Environment variable options</a></li>
<li><a href="#repl_persistent_history">Persistent history</a></li>
<li><a href="#repl_using_the_node_js_repl_with_advanced_line_editors">Using the Node.js REPL with advanced line-editors</a></li>
<li><a href="#repl_starting_multiple_repl_instances_against_a_single_running_instance">Starting multiple REPL instances against a single running instance</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#report_diagnostic_report">Diagnostic report</a></span></p>
<ul>
<li><a href="#report_usage">Usage</a></li>
<li><a href="#report_configuration">Configuration</a></li>
<li><a href="#report_interaction_with_workers">Interaction with workers</a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#stream_stream">Stream</a></span></p>
<ul>
<li><a href="#stream_organization_of_this_document">Organization of this document</a></li>
<li>
<p><a href="#stream_types_of_streams">Types of streams</a></p>
<ul>
<li><a href="#stream_object_mode">Object mode</a></li>
<li><a href="#stream_buffering">Buffering</a></li>
</ul>
</li>
<li>
<p><a href="#stream_api_for_stream_consumers">API for stream consumers</a></p>
<ul>
<li>
<p><a href="#stream_writable_streams">Writable streams</a></p>
<ul>
<li>
<p><a href="#stream_class_stream_writable">Class: <code>stream.Writable</code></a></p>
<ul>
<li><a href="#stream_event_close">Event: <code>'close'</code></a></li>
<li><a href="#stream_event_drain">Event: <code>'drain'</code></a></li>
<li><a href="#stream_event_error">Event: <code>'error'</code></a></li>
<li><a href="#stream_event_finish">Event: <code>'finish'</code></a></li>
<li><a href="#stream_event_pipe">Event: <code>'pipe'</code></a></li>
<li><a href="#stream_event_unpipe">Event: <code>'unpipe'</code></a></li>
<li><a href="#stream_writable_cork"><code>writable.cork()</code></a></li>
<li><a href="#stream_writable_destroy_error"><code>writable.destroy([error])</code></a></li>
<li><a href="#stream_writable_destroyed"><code>writable.destroyed</code></a></li>
<li><a href="#stream_writable_end_chunk_encoding_callback"><code>writable.end([chunk[, encoding]][, callback])</code></a></li>
<li><a href="#stream_writable_setdefaultencoding_encoding"><code>writable.setDefaultEncoding(encoding)</code></a></li>
<li><a href="#stream_writable_uncork"><code>writable.uncork()</code></a></li>
<li><a href="#stream_writable_writable"><code>writable.writable</code></a></li>
<li><a href="#stream_writable_writableended"><code>writable.writableEnded</code></a></li>
<li><a href="#stream_writable_writablecorked"><code>writable.writableCorked</code></a></li>
<li><a href="#stream_writable_writablefinished"><code>writable.writableFinished</code></a></li>
<li><a href="#stream_writable_writablehighwatermark"><code>writable.writableHighWaterMark</code></a></li>
<li><a href="#stream_writable_writablelength"><code>writable.writableLength</code></a></li>
<li><a href="#stream_writable_writableobjectmode"><code>writable.writableObjectMode</code></a></li>
<li><a href="#stream_writable_write_chunk_encoding_callback"><code>writable.write(chunk[, encoding][, callback])</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#stream_readable_streams">Readable streams</a></p>
<ul>
<li><a href="#stream_two_reading_modes">Two reading modes</a></li>
<li><a href="#stream_three_states">Three states</a></li>
<li><a href="#stream_choose_one_api_style">Choose one API style</a></li>
<li>
<p><a href="#stream_class_stream_readable">Class: <code>stream.Readable</code></a></p>
<ul>
<li><a href="#stream_event_close_1">Event: <code>'close'</code></a></li>
<li><a href="#stream_event_data">Event: <code>'data'</code></a></li>
<li><a href="#stream_event_end">Event: <code>'end'</code></a></li>
<li><a href="#stream_event_error_1">Event: <code>'error'</code></a></li>
<li><a href="#stream_event_pause">Event: <code>'pause'</code></a></li>
<li><a href="#stream_event_readable">Event: <code>'readable'</code></a></li>
<li><a href="#stream_event_resume">Event: <code>'resume'</code></a></li>
<li><a href="#stream_readable_destroy_error"><code>readable.destroy([error])</code></a></li>
<li><a href="#stream_readable_destroyed"><code>readable.destroyed</code></a></li>
<li><a href="#stream_readable_ispaused"><code>readable.isPaused()</code></a></li>
<li><a href="#stream_readable_pause"><code>readable.pause()</code></a></li>
<li><a href="#stream_readable_pipe_destination_options"><code>readable.pipe(destination[, options])</code></a></li>
<li><a href="#stream_readable_read_size"><code>readable.read([size])</code></a></li>
<li><a href="#stream_readable_readable"><code>readable.readable</code></a></li>
<li><a href="#stream_readable_readableencoding"><code>readable.readableEncoding</code></a></li>
<li><a href="#stream_readable_readableended"><code>readable.readableEnded</code></a></li>
<li><a href="#stream_readable_readableflowing"><code>readable.readableFlowing</code></a></li>
<li><a href="#stream_readable_readablehighwatermark"><code>readable.readableHighWaterMark</code></a></li>
<li><a href="#stream_readable_readablelength"><code>readable.readableLength</code></a></li>
<li><a href="#stream_readable_readableobjectmode"><code>readable.readableObjectMode</code></a></li>
<li><a href="#stream_readable_resume"><code>readable.resume()</code></a></li>
<li><a href="#stream_readable_setencoding_encoding"><code>readable.setEncoding(encoding)</code></a></li>
<li><a href="#stream_readable_unpipe_destination"><code>readable.unpipe([destination])</code></a></li>
<li><a href="#stream_readable_unshift_chunk_encoding"><code>readable.unshift(chunk[, encoding])</code></a></li>
<li><a href="#stream_readable_wrap_stream"><code>readable.wrap(stream)</code></a></li>
<li><a href="#stream_readable_symbol_asynciterator"><code>readable[Symbol.asyncIterator]()</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#stream_duplex_and_transform_streams">Duplex and transform streams</a></p>
<ul>
<li><a href="#stream_class_stream_duplex">Class: <code>stream.Duplex</code></a></li>
<li>
<p><a href="#stream_class_stream_transform">Class: <code>stream.Transform</code></a></p>
<ul>
<li><a href="#stream_transform_destroy_error"><code>transform.destroy([error])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#stream_stream_finished_stream_options_callback"><code>stream.finished(stream[, options], callback)</code></a></li>
<li><a href="#stream_stream_pipeline_streams_callback"><code>stream.pipeline(...streams, callback)</code></a></li>
<li><a href="#stream_stream_readable_from_iterable_options"><code>stream.Readable.from(iterable, [options])</code></a></li>
</ul>
</li>
<li>
<p><a href="#stream_api_for_stream_implementers">API for stream implementers</a></p>
<ul>
<li><a href="#stream_simplified_construction">Simplified construction</a></li>
<li>
<p><a href="#stream_implementing_a_writable_stream">Implementing a writable stream</a></p>
<ul>
<li><a href="#stream_constructor_new_stream_writable_options">Constructor: <code>new stream.Writable([options])</code></a></li>
<li><a href="#stream_writable_write_chunk_encoding_callback_1"><code>writable._write(chunk, encoding, callback)</code></a></li>
<li><a href="#stream_writable_writev_chunks_callback"><code>writable._writev(chunks, callback)</code></a></li>
<li><a href="#stream_writable_destroy_err_callback"><code>writable._destroy(err, callback)</code></a></li>
<li><a href="#stream_writable_final_callback"><code>writable._final(callback)</code></a></li>
<li><a href="#stream_errors_while_writing">Errors while writing</a></li>
<li><a href="#stream_an_example_writable_stream">An example writable stream</a></li>
<li><a href="#stream_decoding_buffers_in_a_writable_stream">Decoding buffers in a writable stream</a></li>
</ul>
</li>
<li>
<p><a href="#stream_implementing_a_readable_stream">Implementing a readable stream</a></p>
<ul>
<li><a href="#stream_new_stream_readable_options"><code>new stream.Readable([options])</code></a></li>
<li><a href="#stream_readable_read_size_1"><code>readable._read(size)</code></a></li>
<li><a href="#stream_readable_destroy_err_callback"><code>readable._destroy(err, callback)</code></a></li>
<li><a href="#stream_readable_push_chunk_encoding"><code>readable.push(chunk[, encoding])</code></a></li>
<li><a href="#stream_errors_while_reading">Errors while reading</a></li>
<li><a href="#stream_an_example_counting_stream">An example counting stream</a></li>
</ul>
</li>
<li>
<p><a href="#stream_implementing_a_duplex_stream">Implementing a duplex stream</a></p>
<ul>
<li><a href="#stream_new_stream_duplex_options"><code>new stream.Duplex(options)</code></a></li>
<li><a href="#stream_an_example_duplex_stream">An example duplex stream</a></li>
<li><a href="#stream_object_mode_duplex_streams">Object mode duplex streams</a></li>
</ul>
</li>
<li>
<p><a href="#stream_implementing_a_transform_stream">Implementing a transform stream</a></p>
<ul>
<li><a href="#stream_new_stream_transform_options"><code>new stream.Transform([options])</code></a></li>
<li><a href="#stream_events_finish_and_end">Events: <code>'finish'</code> and <code>'end'</code></a></li>
<li><a href="#stream_transform_flush_callback"><code>transform._flush(callback)</code></a></li>
<li><a href="#stream_transform_transform_chunk_encoding_callback"><code>transform._transform(chunk, encoding, callback)</code></a></li>
<li><a href="#stream_class_stream_passthrough">Class: <code>stream.PassThrough</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#stream_additional_notes">Additional notes</a></p>
<ul>
<li>
<p><a href="#stream_streams_compatibility_with_async_generators_and_async_iterators">Streams compatibility with async generators and async iterators</a></p>
<ul>
<li><a href="#stream_consuming_readable_streams_with_async_iterators">Consuming readable streams with async iterators</a></li>
<li><a href="#stream_creating_readable_streams_with_async_generators">Creating readable streams with async generators</a></li>
<li><a href="#stream_piping_to_writable_streams_from_async_iterators">Piping to writable streams from async iterators</a></li>
</ul>
</li>
<li><a href="#stream_compatibility_with_older_node_js_versions">Compatibility with older Node.js versions</a></li>
<li><a href="#stream_readable_read_0"><code>readable.read(0)</code></a></li>
<li><a href="#stream_readable_push"><code>readable.push('')</code></a></li>
<li><a href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#string_decoder_string_decoder">String decoder</a></span></p>
<ul>
<li>
<p><a href="#string_decoder_class_stringdecoder">Class: <code>StringDecoder</code></a></p>
<ul>
<li><a href="#string_decoder_new_stringdecoder_encoding"><code>new StringDecoder([encoding])</code></a></li>
<li><a href="#string_decoder_stringdecoder_end_buffer"><code>stringDecoder.end([buffer])</code></a></li>
<li><a href="#string_decoder_stringdecoder_write_buffer"><code>stringDecoder.write(buffer)</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#timers_timers">Timers</a></span></p>
<ul>
<li>
<p><a href="#timers_class_immediate">Class: <code>Immediate</code></a></p>
<ul>
<li><a href="#timers_immediate_hasref"><code>immediate.hasRef()</code></a></li>
<li><a href="#timers_immediate_ref"><code>immediate.ref()</code></a></li>
<li><a href="#timers_immediate_unref"><code>immediate.unref()</code></a></li>
</ul>
</li>
<li>
<p><a href="#timers_class_timeout">Class: <code>Timeout</code></a></p>
<ul>
<li><a href="#timers_timeout_hasref"><code>timeout.hasRef()</code></a></li>
<li><a href="#timers_timeout_ref"><code>timeout.ref()</code></a></li>
<li><a href="#timers_timeout_refresh"><code>timeout.refresh()</code></a></li>
<li><a href="#timers_timeout_unref"><code>timeout.unref()</code></a></li>
</ul>
</li>
<li>
<p><a href="#timers_scheduling_timers">Scheduling timers</a></p>
<ul>
<li><a href="#timers_setimmediate_callback_args"><code>setImmediate(callback[, ...args])</code></a></li>
<li><a href="#timers_setinterval_callback_delay_args"><code>setInterval(callback, delay[, ...args])</code></a></li>
<li><a href="#timers_settimeout_callback_delay_args"><code>setTimeout(callback, delay[, ...args])</code></a></li>
</ul>
</li>
<li>
<p><a href="#timers_cancelling_timers">Cancelling timers</a></p>
<ul>
<li><a href="#timers_clearimmediate_immediate"><code>clearImmediate(immediate)</code></a></li>
<li><a href="#timers_clearinterval_timeout"><code>clearInterval(timeout)</code></a></li>
<li><a href="#timers_cleartimeout_timeout"><code>clearTimeout(timeout)</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#tls_tls_ssl">TLS (SSL)</a></span></p>
<ul>
<li>
<p><a href="#tls_tls_ssl_concepts">TLS/SSL concepts</a></p>
<ul>
<li><a href="#tls_perfect_forward_secrecy">Perfect forward secrecy</a></li>
<li><a href="#tls_alpn_and_sni">ALPN and SNI</a></li>
<li><a href="#tls_pre_shared_keys">Pre-shared keys</a></li>
<li><a href="#tls_client_initiated_renegotiation_attack_mitigation">Client-initiated renegotiation attack mitigation</a></li>
<li>
<p><a href="#tls_session_resumption">Session resumption</a></p>
<ul>
<li><a href="#tls_session_identifiers">Session identifiers</a></li>
<li><a href="#tls_session_tickets">Session tickets</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#tls_modifying_the_default_tls_cipher_suite">Modifying the default TLS cipher suite</a></li>
<li>
<p><a href="#tls_class_tls_server">Class: <code>tls.Server</code></a></p>
<ul>
<li><a href="#tls_event_keylog">Event: <code>'keylog'</code></a></li>
<li><a href="#tls_event_newsession">Event: <code>'newSession'</code></a></li>
<li><a href="#tls_event_ocsprequest">Event: <code>'OCSPRequest'</code></a></li>
<li><a href="#tls_event_resumesession">Event: <code>'resumeSession'</code></a></li>
<li><a href="#tls_event_secureconnection">Event: <code>'secureConnection'</code></a></li>
<li><a href="#tls_event_tlsclienterror">Event: <code>'tlsClientError'</code></a></li>
<li><a href="#tls_server_addcontext_hostname_context"><code>server.addContext(hostname, context)</code></a></li>
<li><a href="#tls_server_address"><code>server.address()</code></a></li>
<li><a href="#tls_server_close_callback"><code>server.close([callback])</code></a></li>
<li><span class="stability_0"><a href="#tls_server_connections"><code>server.connections</code></a></span></li>
<li><a href="#tls_server_getticketkeys"><code>server.getTicketKeys()</code></a></li>
<li><a href="#tls_server_listen"><code>server.listen()</code></a></li>
<li><a href="#tls_server_setsecurecontext_options"><code>server.setSecureContext(options)</code></a></li>
<li><a href="#tls_server_setticketkeys_keys"><code>server.setTicketKeys(keys)</code></a></li>
</ul>
</li>
<li>
<p><a href="#tls_class_tls_tlssocket">Class: <code>tls.TLSSocket</code></a></p>
<ul>
<li><a href="#tls_new_tls_tlssocket_socket_options"><code>new tls.TLSSocket(socket[, options])</code></a></li>
<li><a href="#tls_event_keylog_1">Event: <code>'keylog'</code></a></li>
<li><a href="#tls_event_ocspresponse">Event: <code>'OCSPResponse'</code></a></li>
<li><a href="#tls_event_secureconnect">Event: <code>'secureConnect'</code></a></li>
<li><a href="#tls_event_session">Event: <code>'session'</code></a></li>
<li><a href="#tls_tlssocket_address"><code>tlsSocket.address()</code></a></li>
<li><a href="#tls_tlssocket_authorizationerror"><code>tlsSocket.authorizationError</code></a></li>
<li><a href="#tls_tlssocket_authorized"><code>tlsSocket.authorized</code></a></li>
<li><a href="#tls_tlssocket_disablerenegotiation"><code>tlsSocket.disableRenegotiation()</code></a></li>
<li><a href="#tls_tlssocket_enabletrace"><code>tlsSocket.enableTrace()</code></a></li>
<li><a href="#tls_tlssocket_encrypted"><code>tlsSocket.encrypted</code></a></li>
<li><a href="#tls_tlssocket_getcertificate"><code>tlsSocket.getCertificate()</code></a></li>
<li><a href="#tls_tlssocket_getcipher"><code>tlsSocket.getCipher()</code></a></li>
<li><a href="#tls_tlssocket_getephemeralkeyinfo"><code>tlsSocket.getEphemeralKeyInfo()</code></a></li>
<li><a href="#tls_tlssocket_getfinished"><code>tlsSocket.getFinished()</code></a></li>
<li>
<p><a href="#tls_tlssocket_getpeercertificate_detailed"><code>tlsSocket.getPeerCertificate([detailed])</code></a></p>
<ul>
<li><a href="#tls_certificate_object">Certificate object</a></li>
</ul>
</li>
<li><a href="#tls_tlssocket_getpeerfinished"><code>tlsSocket.getPeerFinished()</code></a></li>
<li><a href="#tls_tlssocket_getprotocol"><code>tlsSocket.getProtocol()</code></a></li>
<li><a href="#tls_tlssocket_getsession"><code>tlsSocket.getSession()</code></a></li>
<li><a href="#tls_tlssocket_getsharedsigalgs"><code>tlsSocket.getSharedSigalgs()</code></a></li>
<li><a href="#tls_tlssocket_exportkeyingmaterial_length_label_context"><code>tlsSocket.exportKeyingMaterial(length, label[, context])</code></a></li>
<li><a href="#tls_tlssocket_gettlsticket"><code>tlsSocket.getTLSTicket()</code></a></li>
<li><a href="#tls_tlssocket_issessionreused"><code>tlsSocket.isSessionReused()</code></a></li>
<li><a href="#tls_tlssocket_localaddress"><code>tlsSocket.localAddress</code></a></li>
<li><a href="#tls_tlssocket_localport"><code>tlsSocket.localPort</code></a></li>
<li><a href="#tls_tlssocket_remoteaddress"><code>tlsSocket.remoteAddress</code></a></li>
<li><a href="#tls_tlssocket_remotefamily"><code>tlsSocket.remoteFamily</code></a></li>
<li><a href="#tls_tlssocket_remoteport"><code>tlsSocket.remotePort</code></a></li>
<li><a href="#tls_tlssocket_renegotiate_options_callback"><code>tlsSocket.renegotiate(options, callback)</code></a></li>
<li><a href="#tls_tlssocket_setmaxsendfragment_size"><code>tlsSocket.setMaxSendFragment(size)</code></a></li>
</ul>
</li>
<li><a href="#tls_tls_checkserveridentity_hostname_cert"><code>tls.checkServerIdentity(hostname, cert)</code></a></li>
<li><a href="#tls_tls_connect_options_callback"><code>tls.connect(options[, callback])</code></a></li>
<li><a href="#tls_tls_connect_path_options_callback"><code>tls.connect(path[, options][, callback])</code></a></li>
<li><a href="#tls_tls_connect_port_host_options_callback"><code>tls.connect(port[, host][, options][, callback])</code></a></li>
<li><a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext([options])</code></a></li>
<li><a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer([options][, secureConnectionListener])</code></a></li>
<li><a href="#tls_tls_getciphers"><code>tls.getCiphers()</code></a></li>
<li><a href="#tls_tls_rootcertificates"><code>tls.rootCertificates</code></a></li>
<li><a href="#tls_tls_default_ecdh_curve"><code>tls.DEFAULT_ECDH_CURVE</code></a></li>
<li><a href="#tls_tls_default_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a></li>
<li><a href="#tls_tls_default_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a></li>
<li>
<p><a href="#tls_deprecated_apis">Deprecated APIs</a></p>
<ul>
<li>
<p><span class="stability_0"><a href="#tls_class_cryptostream">Class: <code>CryptoStream</code></a></span></p>
<ul>
<li><a href="#tls_cryptostream_byteswritten"><code>cryptoStream.bytesWritten</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_0"><a href="#tls_class_securepair">Class: <code>SecurePair</code></a></span></p>
<ul>
<li><a href="#tls_event_secure">Event: <code>'secure'</code></a></li>
</ul>
</li>
<li><span class="stability_0"><a href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options"><code>tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_1"><a href="#tracing_trace_events">Trace events</a></span></p>
<ul>
<li>
<p><a href="#tracing_the_trace_events_module">The <code>trace_events</code> module</a></p>
<ul>
<li>
<p><a href="#tracing_tracing_object"><code>Tracing</code> object</a></p>
<ul>
<li><a href="#tracing_tracing_categories"><code>tracing.categories</code></a></li>
<li><a href="#tracing_tracing_disable"><code>tracing.disable()</code></a></li>
<li><a href="#tracing_tracing_enable"><code>tracing.enable()</code></a></li>
<li><a href="#tracing_tracing_enabled"><code>tracing.enabled</code></a></li>
</ul>
</li>
<li><a href="#tracing_trace_events_createtracing_options"><code>trace_events.createTracing(options)</code></a></li>
<li><a href="#tracing_trace_events_getenabledcategories"><code>trace_events.getEnabledCategories()</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#tty_tty">TTY</a></span></p>
<ul>
<li>
<p><a href="#tty_class_tty_readstream">Class: <code>tty.ReadStream</code></a></p>
<ul>
<li><a href="#tty_readstream_israw"><code>readStream.isRaw</code></a></li>
<li><a href="#tty_readstream_istty"><code>readStream.isTTY</code></a></li>
<li><a href="#tty_readstream_setrawmode_mode"><code>readStream.setRawMode(mode)</code></a></li>
</ul>
</li>
<li>
<p><a href="#tty_class_tty_writestream">Class: <code>tty.WriteStream</code></a></p>
<ul>
<li><a href="#tty_event_resize">Event: <code>'resize'</code></a></li>
<li><a href="#tty_writestream_clearline_dir_callback"><code>writeStream.clearLine(dir[, callback])</code></a></li>
<li><a href="#tty_writestream_clearscreendown_callback"><code>writeStream.clearScreenDown([callback])</code></a></li>
<li><a href="#tty_writestream_columns"><code>writeStream.columns</code></a></li>
<li><a href="#tty_writestream_cursorto_x_y_callback"><code>writeStream.cursorTo(x[, y][, callback])</code></a></li>
<li><a href="#tty_writestream_getcolordepth_env"><code>writeStream.getColorDepth([env])</code></a></li>
<li><a href="#tty_writestream_getwindowsize"><code>writeStream.getWindowSize()</code></a></li>
<li><a href="#tty_writestream_hascolors_count_env"><code>writeStream.hasColors([count][, env])</code></a></li>
<li><a href="#tty_writestream_istty"><code>writeStream.isTTY</code></a></li>
<li><a href="#tty_writestream_movecursor_dx_dy_callback"><code>writeStream.moveCursor(dx, dy[, callback])</code></a></li>
<li><a href="#tty_writestream_rows"><code>writeStream.rows</code></a></li>
</ul>
</li>
<li><a href="#tty_tty_isatty_fd"><code>tty.isatty(fd)</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#dgram_udp_datagram_sockets">UDP/datagram sockets</a></span></p>
<ul>
<li>
<p><a href="#dgram_class_dgram_socket">Class: <code>dgram.Socket</code></a></p>
<ul>
<li><a href="#dgram_event_close">Event: <code>'close'</code></a></li>
<li><a href="#dgram_event_connect">Event: <code>'connect'</code></a></li>
<li><a href="#dgram_event_error">Event: <code>'error'</code></a></li>
<li><a href="#dgram_event_listening">Event: <code>'listening'</code></a></li>
<li><a href="#dgram_event_message">Event: <code>'message'</code></a></li>
<li><a href="#dgram_socket_addmembership_multicastaddress_multicastinterface"><code>socket.addMembership(multicastAddress[, multicastInterface])</code></a></li>
<li><a href="#dgram_socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface"><code>socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li>
<li><a href="#dgram_socket_address"><code>socket.address()</code></a></li>
<li><a href="#dgram_socket_bind_port_address_callback"><code>socket.bind([port][, address][, callback])</code></a></li>
<li><a href="#dgram_socket_bind_options_callback"><code>socket.bind(options[, callback])</code></a></li>
<li><a href="#dgram_socket_close_callback"><code>socket.close([callback])</code></a></li>
<li><a href="#dgram_socket_connect_port_address_callback"><code>socket.connect(port[, address][, callback])</code></a></li>
<li><a href="#dgram_socket_disconnect"><code>socket.disconnect()</code></a></li>
<li><a href="#dgram_socket_dropmembership_multicastaddress_multicastinterface"><code>socket.dropMembership(multicastAddress[, multicastInterface])</code></a></li>
<li><a href="#dgram_socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface"><code>socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li>
<li><a href="#dgram_socket_getrecvbuffersize"><code>socket.getRecvBufferSize()</code></a></li>
<li><a href="#dgram_socket_getsendbuffersize"><code>socket.getSendBufferSize()</code></a></li>
<li><a href="#dgram_socket_ref"><code>socket.ref()</code></a></li>
<li><a href="#dgram_socket_remoteaddress"><code>socket.remoteAddress()</code></a></li>
<li>
<p><a href="#dgram_socket_send_msg_offset_length_port_address_callback"><code>socket.send(msg[, offset, length][, port][, address][, callback])</code></a></p>
<ul>
<li><a href="#dgram_note_about_udp_datagram_size">Note about UDP datagram size</a></li>
</ul>
</li>
<li><a href="#dgram_socket_setbroadcast_flag"><code>socket.setBroadcast(flag)</code></a></li>
<li>
<p><a href="#dgram_socket_setmulticastinterface_multicastinterface"><code>socket.setMulticastInterface(multicastInterface)</code></a></p>
<ul>
<li><a href="#dgram_example_ipv6_outgoing_multicast_interface">Example: IPv6 outgoing multicast interface</a></li>
<li><a href="#dgram_example_ipv4_outgoing_multicast_interface">Example: IPv4 outgoing multicast interface</a></li>
<li><a href="#dgram_call_results">Call results</a></li>
</ul>
</li>
<li><a href="#dgram_socket_setmulticastloopback_flag"><code>socket.setMulticastLoopback(flag)</code></a></li>
<li><a href="#dgram_socket_setmulticastttl_ttl"><code>socket.setMulticastTTL(ttl)</code></a></li>
<li><a href="#dgram_socket_setrecvbuffersize_size"><code>socket.setRecvBufferSize(size)</code></a></li>
<li><a href="#dgram_socket_setsendbuffersize_size"><code>socket.setSendBufferSize(size)</code></a></li>
<li><a href="#dgram_socket_setttl_ttl"><code>socket.setTTL(ttl)</code></a></li>
<li><a href="#dgram_socket_unref"><code>socket.unref()</code></a></li>
</ul>
</li>
<li>
<p><a href="#dgram_dgram_module_functions"><code>dgram</code> module functions</a></p>
<ul>
<li><a href="#dgram_dgram_createsocket_options_callback"><code>dgram.createSocket(options[, callback])</code></a></li>
<li><a href="#dgram_dgram_createsocket_type_callback"><code>dgram.createSocket(type[, callback])</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#url_url">URL</a></span></p>
<ul>
<li><a href="#url_url_strings_and_url_objects">URL strings and URL objects</a></li>
<li>
<p><a href="#url_the_whatwg_url_api">The WHATWG URL API</a></p>
<ul>
<li>
<p><a href="#url_class_url">Class: <code>URL</code></a></p>
<ul>
<li><a href="#url_constructor_new_url_input_base">Constructor: <code>new URL(input[, base])</code></a></li>
<li><a href="#url_url_hash"><code>url.hash</code></a></li>
<li><a href="#url_url_host"><code>url.host</code></a></li>
<li><a href="#url_url_hostname"><code>url.hostname</code></a></li>
<li><a href="#url_url_href"><code>url.href</code></a></li>
<li><a href="#url_url_origin"><code>url.origin</code></a></li>
<li><a href="#url_url_password"><code>url.password</code></a></li>
<li><a href="#url_url_pathname"><code>url.pathname</code></a></li>
<li><a href="#url_url_port"><code>url.port</code></a></li>
<li>
<p><a href="#url_url_protocol"><code>url.protocol</code></a></p>
<ul>
<li><a href="#url_special_schemes">Special schemes</a></li>
</ul>
</li>
<li><a href="#url_url_search"><code>url.search</code></a></li>
<li><a href="#url_url_searchparams"><code>url.searchParams</code></a></li>
<li><a href="#url_url_username"><code>url.username</code></a></li>
<li><a href="#url_url_tostring"><code>url.toString()</code></a></li>
<li><a href="#url_url_tojson"><code>url.toJSON()</code></a></li>
</ul>
</li>
<li>
<p><a href="#url_class_urlsearchparams">Class: <code>URLSearchParams</code></a></p>
<ul>
<li><a href="#url_constructor_new_urlsearchparams">Constructor: <code>new URLSearchParams()</code></a></li>
<li><a href="#url_constructor_new_urlsearchparams_string">Constructor: <code>new URLSearchParams(string)</code></a></li>
<li><a href="#url_constructor_new_urlsearchparams_obj">Constructor: <code>new URLSearchParams(obj)</code></a></li>
<li><a href="#url_constructor_new_urlsearchparams_iterable">Constructor: <code>new URLSearchParams(iterable)</code></a></li>
<li><a href="#url_urlsearchparams_append_name_value"><code>urlSearchParams.append(name, value)</code></a></li>
<li><a href="#url_urlsearchparams_delete_name"><code>urlSearchParams.delete(name)</code></a></li>
<li><a href="#url_urlsearchparams_entries"><code>urlSearchParams.entries()</code></a></li>
<li><a href="#url_urlsearchparams_foreach_fn_thisarg"><code>urlSearchParams.forEach(fn[, thisArg])</code></a></li>
<li><a href="#url_urlsearchparams_get_name"><code>urlSearchParams.get(name)</code></a></li>
<li><a href="#url_urlsearchparams_getall_name"><code>urlSearchParams.getAll(name)</code></a></li>
<li><a href="#url_urlsearchparams_has_name"><code>urlSearchParams.has(name)</code></a></li>
<li><a href="#url_urlsearchparams_keys"><code>urlSearchParams.keys()</code></a></li>
<li><a href="#url_urlsearchparams_set_name_value"><code>urlSearchParams.set(name, value)</code></a></li>
<li><a href="#url_urlsearchparams_sort"><code>urlSearchParams.sort()</code></a></li>
<li><a href="#url_urlsearchparams_tostring"><code>urlSearchParams.toString()</code></a></li>
<li><a href="#url_urlsearchparams_values"><code>urlSearchParams.values()</code></a></li>
<li><a href="#url_urlsearchparams_symbol_iterator"><code>urlSearchParams[Symbol.iterator]()</code></a></li>
</ul>
</li>
<li><a href="#url_url_domaintoascii_domain"><code>url.domainToASCII(domain)</code></a></li>
<li><a href="#url_url_domaintounicode_domain"><code>url.domainToUnicode(domain)</code></a></li>
<li><a href="#url_url_fileurltopath_url"><code>url.fileURLToPath(url)</code></a></li>
<li><a href="#url_url_format_url_options"><code>url.format(URL[, options])</code></a></li>
<li><a href="#url_url_pathtofileurl_path"><code>url.pathToFileURL(path)</code></a></li>
</ul>
</li>
<li>
<p><a href="#url_legacy_url_api">Legacy URL API</a></p>
<ul>
<li>
<p><a href="#url_legacy_urlobject">Legacy <code>urlObject</code></a></p>
<ul>
<li><a href="#url_urlobject_auth"><code>urlObject.auth</code></a></li>
<li><a href="#url_urlobject_hash"><code>urlObject.hash</code></a></li>
<li><a href="#url_urlobject_host"><code>urlObject.host</code></a></li>
<li><a href="#url_urlobject_hostname"><code>urlObject.hostname</code></a></li>
<li><a href="#url_urlobject_href"><code>urlObject.href</code></a></li>
<li><a href="#url_urlobject_path"><code>urlObject.path</code></a></li>
<li><a href="#url_urlobject_pathname"><code>urlObject.pathname</code></a></li>
<li><a href="#url_urlobject_port"><code>urlObject.port</code></a></li>
<li><a href="#url_urlobject_protocol"><code>urlObject.protocol</code></a></li>
<li><a href="#url_urlobject_query"><code>urlObject.query</code></a></li>
<li><a href="#url_urlobject_search"><code>urlObject.search</code></a></li>
<li><a href="#url_urlobject_slashes"><code>urlObject.slashes</code></a></li>
</ul>
</li>
<li><a href="#url_url_format_urlobject"><code>url.format(urlObject)</code></a></li>
<li><a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse(urlString[, parseQueryString[, slashesDenoteHost]])</code></a></li>
<li><a href="#url_url_resolve_from_to"><code>url.resolve(from, to)</code></a></li>
</ul>
</li>
<li>
<p><a href="#url_percent_encoding_in_urls">Percent-encoding in URLs</a></p>
<ul>
<li><a href="#url_legacy_api">Legacy API</a></li>
<li><a href="#url_whatwg_api">WHATWG API</a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#util_util">Util</a></span></p>
<ul>
<li><a href="#util_util_callbackify_original"><code>util.callbackify(original)</code></a></li>
<li><a href="#util_util_debuglog_section"><code>util.debuglog(section)</code></a></li>
<li><a href="#util_util_deprecate_fn_msg_code"><code>util.deprecate(fn, msg[, code])</code></a></li>
<li><a href="#util_util_format_format_args"><code>util.format(format[, ...args])</code></a></li>
<li><a href="#util_util_formatwithoptions_inspectoptions_format_args"><code>util.formatWithOptions(inspectOptions, format[, ...args])</code></a></li>
<li><a href="#util_util_getsystemerrorname_err"><code>util.getSystemErrorName(err)</code></a></li>
<li><a href="#util_util_inherits_constructor_superconstructor"><code>util.inherits(constructor, superConstructor)</code></a></li>
<li><a href="#util_util_inspect_object_options"><code>util.inspect(object[, options])</code></a></li>
<li>
<p><a href="#util_util_inspect_object_showhidden_depth_colors"><code>util.inspect(object[, showHidden[, depth[, colors]]])</code></a></p>
<ul>
<li>
<p><a href="#util_customizing_util_inspect_colors">Customizing <code>util.inspect</code> colors</a></p>
<ul>
<li><a href="#util_modifiers">Modifiers</a></li>
<li><a href="#util_foreground_colors">Foreground colors</a></li>
<li><a href="#util_background_colors">Background colors</a></li>
</ul>
</li>
<li><a href="#util_custom_inspection_functions_on_objects">Custom inspection functions on objects</a></li>
<li><a href="#util_util_inspect_custom"><code>util.inspect.custom</code></a></li>
<li><a href="#util_util_inspect_defaultoptions"><code>util.inspect.defaultOptions</code></a></li>
</ul>
</li>
<li><a href="#util_util_isdeepstrictequal_val1_val2"><code>util.isDeepStrictEqual(val1, val2)</code></a></li>
<li>
<p><a href="#util_util_promisify_original"><code>util.promisify(original)</code></a></p>
<ul>
<li><a href="#util_custom_promisified_functions">Custom promisified functions</a></li>
<li><a href="#util_util_promisify_custom"><code>util.promisify.custom</code></a></li>
</ul>
</li>
<li>
<p><a href="#util_class_util_textdecoder">Class: <code>util.TextDecoder</code></a></p>
<ul>
<li>
<p><a href="#util_whatwg_supported_encodings">WHATWG supported encodings</a></p>
<ul>
<li><a href="#util_encodings_supported_without_icu">Encodings Supported Without ICU</a></li>
<li><a href="#util_encodings_supported_by_default_with_icu">Encodings Supported by Default (With ICU)</a></li>
<li><a href="#util_encodings_requiring_full_icu_data">Encodings requiring full ICU data</a></li>
</ul>
</li>
<li><a href="#util_new_textdecoder_encoding_options"><code>new TextDecoder([encoding[, options]])</code></a></li>
<li><a href="#util_textdecoder_decode_input_options"><code>textDecoder.decode([input[, options]])</code></a></li>
<li><a href="#util_textdecoder_encoding"><code>textDecoder.encoding</code></a></li>
<li><a href="#util_textdecoder_fatal"><code>textDecoder.fatal</code></a></li>
<li><a href="#util_textdecoder_ignorebom"><code>textDecoder.ignoreBOM</code></a></li>
</ul>
</li>
<li>
<p><a href="#util_class_util_textencoder">Class: <code>util.TextEncoder</code></a></p>
<ul>
<li><a href="#util_textencoder_encode_input"><code>textEncoder.encode([input])</code></a></li>
<li><a href="#util_textencoder_encodeinto_src_dest"><code>textEncoder.encodeInto(src, dest)</code></a></li>
<li><a href="#util_textencoder_encoding"><code>textEncoder.encoding</code></a></li>
</ul>
</li>
<li>
<p><a href="#util_util_types"><code>util.types</code></a></p>
<ul>
<li><a href="#util_util_types_isanyarraybuffer_value"><code>util.types.isAnyArrayBuffer(value)</code></a></li>
<li><a href="#util_util_types_isarraybufferview_value"><code>util.types.isArrayBufferView(value)</code></a></li>
<li><a href="#util_util_types_isargumentsobject_value"><code>util.types.isArgumentsObject(value)</code></a></li>
<li><a href="#util_util_types_isarraybuffer_value"><code>util.types.isArrayBuffer(value)</code></a></li>
<li><a href="#util_util_types_isasyncfunction_value"><code>util.types.isAsyncFunction(value)</code></a></li>
<li><a href="#util_util_types_isbigint64array_value"><code>util.types.isBigInt64Array(value)</code></a></li>
<li><a href="#util_util_types_isbiguint64array_value"><code>util.types.isBigUint64Array(value)</code></a></li>
<li><a href="#util_util_types_isbooleanobject_value"><code>util.types.isBooleanObject(value)</code></a></li>
<li><a href="#util_util_types_isboxedprimitive_value"><code>util.types.isBoxedPrimitive(value)</code></a></li>
<li><a href="#util_util_types_isdataview_value"><code>util.types.isDataView(value)</code></a></li>
<li><a href="#util_util_types_isdate_value"><code>util.types.isDate(value)</code></a></li>
<li><a href="#util_util_types_isexternal_value"><code>util.types.isExternal(value)</code></a></li>
<li><a href="#util_util_types_isfloat32array_value"><code>util.types.isFloat32Array(value)</code></a></li>
<li><a href="#util_util_types_isfloat64array_value"><code>util.types.isFloat64Array(value)</code></a></li>
<li><a href="#util_util_types_isgeneratorfunction_value"><code>util.types.isGeneratorFunction(value)</code></a></li>
<li><a href="#util_util_types_isgeneratorobject_value"><code>util.types.isGeneratorObject(value)</code></a></li>
<li><a href="#util_util_types_isint8array_value"><code>util.types.isInt8Array(value)</code></a></li>
<li><a href="#util_util_types_isint16array_value"><code>util.types.isInt16Array(value)</code></a></li>
<li><a href="#util_util_types_isint32array_value"><code>util.types.isInt32Array(value)</code></a></li>
<li><a href="#util_util_types_ismap_value"><code>util.types.isMap(value)</code></a></li>
<li><a href="#util_util_types_ismapiterator_value"><code>util.types.isMapIterator(value)</code></a></li>
<li><a href="#util_util_types_ismodulenamespaceobject_value"><code>util.types.isModuleNamespaceObject(value)</code></a></li>
<li><a href="#util_util_types_isnativeerror_value"><code>util.types.isNativeError(value)</code></a></li>
<li><a href="#util_util_types_isnumberobject_value"><code>util.types.isNumberObject(value)</code></a></li>
<li><a href="#util_util_types_ispromise_value"><code>util.types.isPromise(value)</code></a></li>
<li><a href="#util_util_types_isproxy_value"><code>util.types.isProxy(value)</code></a></li>
<li><a href="#util_util_types_isregexp_value"><code>util.types.isRegExp(value)</code></a></li>
<li><a href="#util_util_types_isset_value"><code>util.types.isSet(value)</code></a></li>
<li><a href="#util_util_types_issetiterator_value"><code>util.types.isSetIterator(value)</code></a></li>
<li><a href="#util_util_types_issharedarraybuffer_value"><code>util.types.isSharedArrayBuffer(value)</code></a></li>
<li><a href="#util_util_types_isstringobject_value"><code>util.types.isStringObject(value)</code></a></li>
<li><a href="#util_util_types_issymbolobject_value"><code>util.types.isSymbolObject(value)</code></a></li>
<li><a href="#util_util_types_istypedarray_value"><code>util.types.isTypedArray(value)</code></a></li>
<li><a href="#util_util_types_isuint8array_value"><code>util.types.isUint8Array(value)</code></a></li>
<li><a href="#util_util_types_isuint8clampedarray_value"><code>util.types.isUint8ClampedArray(value)</code></a></li>
<li><a href="#util_util_types_isuint16array_value"><code>util.types.isUint16Array(value)</code></a></li>
<li><a href="#util_util_types_isuint32array_value"><code>util.types.isUint32Array(value)</code></a></li>
<li><a href="#util_util_types_isweakmap_value"><code>util.types.isWeakMap(value)</code></a></li>
<li><a href="#util_util_types_isweakset_value"><code>util.types.isWeakSet(value)</code></a></li>
<li><a href="#util_util_types_iswebassemblycompiledmodule_value"><code>util.types.isWebAssemblyCompiledModule(value)</code></a></li>
</ul>
</li>
<li>
<p><a href="#util_deprecated_apis">Deprecated APIs</a></p>
<ul>
<li><span class="stability_0"><a href="#util_util_extend_target_source"><code>util._extend(target, source)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isarray_object"><code>util.isArray(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isboolean_object"><code>util.isBoolean(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isbuffer_object"><code>util.isBuffer(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isdate_object"><code>util.isDate(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_iserror_object"><code>util.isError(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isfunction_object"><code>util.isFunction(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isnull_object"><code>util.isNull(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isnullorundefined_object"><code>util.isNullOrUndefined(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isnumber_object"><code>util.isNumber(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isobject_object"><code>util.isObject(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isprimitive_object"><code>util.isPrimitive(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isregexp_object"><code>util.isRegExp(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isstring_object"><code>util.isString(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_issymbol_object"><code>util.isSymbol(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_isundefined_object"><code>util.isUndefined(object)</code></a></span></li>
<li><span class="stability_0"><a href="#util_util_log_string"><code>util.log(string)</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li>
<p><a href="#v8_v8">V8</a></p>
<ul>
<li><a href="#v8_v8_cacheddataversiontag"><code>v8.cachedDataVersionTag()</code></a></li>
<li><a href="#v8_v8_getheapspacestatistics"><code>v8.getHeapSpaceStatistics()</code></a></li>
<li><a href="#v8_v8_getheapsnapshot"><code>v8.getHeapSnapshot()</code></a></li>
<li><a href="#v8_v8_getheapstatistics"><code>v8.getHeapStatistics()</code></a></li>
<li><a href="#v8_v8_getheapcodestatistics"><code>v8.getHeapCodeStatistics()</code></a></li>
<li><a href="#v8_v8_setflagsfromstring_flags"><code>v8.setFlagsFromString(flags)</code></a></li>
<li><a href="#v8_v8_writeheapsnapshot_filename"><code>v8.writeHeapSnapshot([filename])</code></a></li>
<li>
<p><a href="#v8_serialization_api">Serialization API</a></p>
<ul>
<li><a href="#v8_v8_serialize_value"><code>v8.serialize(value)</code></a></li>
<li><a href="#v8_v8_deserialize_buffer"><code>v8.deserialize(buffer)</code></a></li>
<li>
<p><a href="#v8_class_v8_serializer">Class: <code>v8.Serializer</code></a></p>
<ul>
<li><a href="#v8_new_serializer"><code>new Serializer()</code></a></li>
<li><a href="#v8_serializer_writeheader"><code>serializer.writeHeader()</code></a></li>
<li><a href="#v8_serializer_writevalue_value"><code>serializer.writeValue(value)</code></a></li>
<li><a href="#v8_serializer_releasebuffer"><code>serializer.releaseBuffer()</code></a></li>
<li><a href="#v8_serializer_transferarraybuffer_id_arraybuffer"><code>serializer.transferArrayBuffer(id, arrayBuffer)</code></a></li>
<li><a href="#v8_serializer_writeuint32_value"><code>serializer.writeUint32(value)</code></a></li>
<li><a href="#v8_serializer_writeuint64_hi_lo"><code>serializer.writeUint64(hi, lo)</code></a></li>
<li><a href="#v8_serializer_writedouble_value"><code>serializer.writeDouble(value)</code></a></li>
<li><a href="#v8_serializer_writerawbytes_buffer"><code>serializer.writeRawBytes(buffer)</code></a></li>
<li><a href="#v8_serializer_writehostobject_object"><code>serializer._writeHostObject(object)</code></a></li>
<li><a href="#v8_serializer_getdatacloneerror_message"><code>serializer._getDataCloneError(message)</code></a></li>
<li><a href="#v8_serializer_getsharedarraybufferid_sharedarraybuffer"><code>serializer._getSharedArrayBufferId(sharedArrayBuffer)</code></a></li>
<li><a href="#v8_serializer_settreatarraybufferviewsashostobjects_flag"><code>serializer._setTreatArrayBufferViewsAsHostObjects(flag)</code></a></li>
</ul>
</li>
<li>
<p><a href="#v8_class_v8_deserializer">Class: <code>v8.Deserializer</code></a></p>
<ul>
<li><a href="#v8_new_deserializer_buffer"><code>new Deserializer(buffer)</code></a></li>
<li><a href="#v8_deserializer_readheader"><code>deserializer.readHeader()</code></a></li>
<li><a href="#v8_deserializer_readvalue"><code>deserializer.readValue()</code></a></li>
<li><a href="#v8_deserializer_transferarraybuffer_id_arraybuffer"><code>deserializer.transferArrayBuffer(id, arrayBuffer)</code></a></li>
<li><a href="#v8_deserializer_getwireformatversion"><code>deserializer.getWireFormatVersion()</code></a></li>
<li><a href="#v8_deserializer_readuint32"><code>deserializer.readUint32()</code></a></li>
<li><a href="#v8_deserializer_readuint64"><code>deserializer.readUint64()</code></a></li>
<li><a href="#v8_deserializer_readdouble"><code>deserializer.readDouble()</code></a></li>
<li><a href="#v8_deserializer_readrawbytes_length"><code>deserializer.readRawBytes(length)</code></a></li>
<li><a href="#v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a></li>
</ul>
</li>
<li><a href="#v8_class_v8_defaultserializer">Class: <code>v8.DefaultSerializer</code></a></li>
<li><a href="#v8_class_v8_defaultdeserializer">Class: <code>v8.DefaultDeserializer</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#vm_vm_executing_javascript">VM (executing JavaScript)</a></span></p>
<ul>
<li>
<p><a href="#vm_class_vm_script">Class: <code>vm.Script</code></a></p>
<ul>
<li><a href="#vm_constructor_new_vm_script_code_options">Constructor: <code>new vm.Script(code[, options])</code></a></li>
<li><a href="#vm_script_createcacheddata"><code>script.createCachedData()</code></a></li>
<li><a href="#vm_script_runincontext_contextifiedobject_options"><code>script.runInContext(contextifiedObject[, options])</code></a></li>
<li><a href="#vm_script_runinnewcontext_contextobject_options"><code>script.runInNewContext([contextObject[, options]])</code></a></li>
<li><a href="#vm_script_runinthiscontext_options"><code>script.runInThisContext([options])</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_1"><a href="#vm_class_vm_module">Class: <code>vm.Module</code></a></span></p>
<ul>
<li><a href="#vm_module_dependencyspecifiers"><code>module.dependencySpecifiers</code></a></li>
<li><a href="#vm_module_error"><code>module.error</code></a></li>
<li><a href="#vm_module_evaluate_options"><code>module.evaluate([options])</code></a></li>
<li><a href="#vm_module_link_linker"><code>module.link(linker)</code></a></li>
<li><a href="#vm_module_namespace"><code>module.namespace</code></a></li>
<li><a href="#vm_module_status"><code>module.status</code></a></li>
<li><a href="#vm_module_identifier"><code>module.identifier</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_1"><a href="#vm_class_vm_sourcetextmodule">Class: <code>vm.SourceTextModule</code></a></span></p>
<ul>
<li><a href="#vm_constructor_new_vm_sourcetextmodule_code_options">Constructor: <code>new vm.SourceTextModule(code[, options])</code></a></li>
<li><a href="#vm_sourcetextmodule_createcacheddata"><code>sourceTextModule.createCachedData()</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_1"><a href="#vm_class_vm_syntheticmodule">Class: <code>vm.SyntheticModule</code></a></span></p>
<ul>
<li><a href="#vm_constructor_new_vm_syntheticmodule_exportnames_evaluatecallback_options">Constructor: <code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code></a></li>
<li><a href="#vm_syntheticmodule_setexport_name_value"><code>syntheticModule.setExport(name, value)</code></a></li>
</ul>
</li>
<li><a href="#vm_vm_compilefunction_code_params_options"><code>vm.compileFunction(code[, params[, options]])</code></a></li>
<li><a href="#vm_vm_createcontext_contextobject_options"><code>vm.createContext([contextObject[, options]])</code></a></li>
<li><a href="#vm_vm_iscontext_object"><code>vm.isContext(object)</code></a></li>
<li><a href="#vm_vm_runincontext_code_contextifiedobject_options"><code>vm.runInContext(code, contextifiedObject[, options])</code></a></li>
<li><a href="#vm_vm_runinnewcontext_code_contextobject_options"><code>vm.runInNewContext(code[, contextObject[, options]])</code></a></li>
<li><a href="#vm_vm_runinthiscontext_code_options"><code>vm.runInThisContext(code[, options])</code></a></li>
<li><a href="#vm_example_running_an_http_server_within_a_vm">Example: Running an HTTP server within a VM</a></li>
<li><a href="#vm_what_does_it_mean_to_contextify_an_object">What does it mean to "contextify" an object?</a></li>
<li><a href="#vm_timeout_limitations_when_using_process_nexttick_promises_and_queuemicrotask">Timeout limitations when using <code>process.nextTick()</code>, promises, and <code>queueMicrotask()</code></a></li>
</ul>
</li>
<li>
<p><span class="stability_1"><a href="#wasi_webassembly_system_interface_wasi">WebAssembly System Interface (WASI)</a></span></p>
<ul>
<li>
<p><a href="#wasi_class_wasi">Class: <code>WASI</code></a></p>
<ul>
<li><a href="#wasi_new_wasi_options"><code>new WASI([options])</code></a></li>
<li><a href="#wasi_wasi_start_instance"><code>wasi.start(instance)</code></a></li>
<li><a href="#wasi_wasi_wasiimport"><code>wasi.wasiImport</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#worker_threads_worker_threads">Worker threads</a></span></p>
<ul>
<li><a href="#worker_threads_worker_ismainthread"><code>worker.isMainThread</code></a></li>
<li><a href="#worker_threads_worker_movemessageporttocontext_port_contextifiedsandbox"><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code></a></li>
<li><a href="#worker_threads_worker_parentport"><code>worker.parentPort</code></a></li>
<li><a href="#worker_threads_worker_receivemessageonport_port"><code>worker.receiveMessageOnPort(port)</code></a></li>
<li><a href="#worker_threads_worker_resourcelimits"><code>worker.resourceLimits</code></a></li>
<li><a href="#worker_threads_worker_share_env"><code>worker.SHARE_ENV</code></a></li>
<li><a href="#worker_threads_worker_threadid"><code>worker.threadId</code></a></li>
<li><a href="#worker_threads_worker_workerdata"><code>worker.workerData</code></a></li>
<li><a href="#worker_threads_class_messagechannel">Class: <code>MessageChannel</code></a></li>
<li>
<p><a href="#worker_threads_class_messageport">Class: <code>MessagePort</code></a></p>
<ul>
<li><a href="#worker_threads_event_close">Event: <code>'close'</code></a></li>
<li><a href="#worker_threads_event_message">Event: <code>'message'</code></a></li>
<li><a href="#worker_threads_port_close"><code>port.close()</code></a></li>
<li>
<p><a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage(value[, transferList])</code></a></p>
<ul>
<li><a href="#worker_threads_considerations_when_transferring_typedarrays_and_buffers">Considerations when transferring TypedArrays and Buffers</a></li>
</ul>
</li>
<li><a href="#worker_threads_port_ref"><code>port.ref()</code></a></li>
<li><a href="#worker_threads_port_start"><code>port.start()</code></a></li>
<li><a href="#worker_threads_port_unref"><code>port.unref()</code></a></li>
</ul>
</li>
<li>
<p><a href="#worker_threads_class_worker">Class: <code>Worker</code></a></p>
<ul>
<li><a href="#worker_threads_new_worker_filename_options"><code>new Worker(filename[, options])</code></a></li>
<li><a href="#worker_threads_event_error">Event: <code>'error'</code></a></li>
<li><a href="#worker_threads_event_exit">Event: <code>'exit'</code></a></li>
<li><a href="#worker_threads_event_message_1">Event: <code>'message'</code></a></li>
<li><a href="#worker_threads_event_online">Event: <code>'online'</code></a></li>
<li><a href="#worker_threads_worker_getheapsnapshot"><code>worker.getHeapSnapshot()</code></a></li>
<li><a href="#worker_threads_worker_postmessage_value_transferlist"><code>worker.postMessage(value[, transferList])</code></a></li>
<li><a href="#worker_threads_worker_ref"><code>worker.ref()</code></a></li>
<li><a href="#worker_threads_worker_resourcelimits_1"><code>worker.resourceLimits</code></a></li>
<li><a href="#worker_threads_worker_stderr"><code>worker.stderr</code></a></li>
<li><a href="#worker_threads_worker_stdin"><code>worker.stdin</code></a></li>
<li><a href="#worker_threads_worker_stdout"><code>worker.stdout</code></a></li>
<li><a href="#worker_threads_worker_terminate"><code>worker.terminate()</code></a></li>
<li><a href="#worker_threads_worker_threadid_1"><code>worker.threadId</code></a></li>
<li><a href="#worker_threads_worker_unref"><code>worker.unref()</code></a></li>
</ul>
</li>
</ul>
</li>
<li>
<p><span class="stability_2"><a href="#zlib_zlib">Zlib</a></span></p>
<ul>
<li><a href="#zlib_threadpool_usage_and_performance_considerations">Threadpool usage and performance considerations</a></li>
<li><a href="#zlib_compressing_http_requests_and_responses">Compressing HTTP requests and responses</a></li>
<li>
<p><a href="#zlib_memory_usage_tuning">Memory usage tuning</a></p>
<ul>
<li><a href="#zlib_for_zlib_based_streams">For zlib-based streams</a></li>
<li><a href="#zlib_for_brotli_based_streams">For Brotli-based streams</a></li>
</ul>
</li>
<li><a href="#zlib_flushing">Flushing</a></li>
<li>
<p><a href="#zlib_constants">Constants</a></p>
<ul>
<li><a href="#zlib_zlib_constants">zlib constants</a></li>
<li>
<p><a href="#zlib_brotli_constants">Brotli constants</a></p>
<ul>
<li><a href="#zlib_flush_operations">Flush operations</a></li>
<li><a href="#zlib_compressor_options">Compressor options</a></li>
<li><a href="#zlib_decompressor_options">Decompressor options</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#zlib_class_options">Class: <code>Options</code></a></li>
<li><a href="#zlib_class_brotlioptions">Class: <code>BrotliOptions</code></a></li>
<li><a href="#zlib_class_zlib_brotlicompress">Class: <code>zlib.BrotliCompress</code></a></li>
<li><a href="#zlib_class_zlib_brotlidecompress">Class: <code>zlib.BrotliDecompress</code></a></li>
<li><a href="#zlib_class_zlib_deflate">Class: <code>zlib.Deflate</code></a></li>
<li><a href="#zlib_class_zlib_deflateraw">Class: <code>zlib.DeflateRaw</code></a></li>
<li><a href="#zlib_class_zlib_gunzip">Class: <code>zlib.Gunzip</code></a></li>
<li><a href="#zlib_class_zlib_gzip">Class: <code>zlib.Gzip</code></a></li>
<li><a href="#zlib_class_zlib_inflate">Class: <code>zlib.Inflate</code></a></li>
<li><a href="#zlib_class_zlib_inflateraw">Class: <code>zlib.InflateRaw</code></a></li>
<li><a href="#zlib_class_zlib_unzip">Class: <code>zlib.Unzip</code></a></li>
<li>
<p><a href="#zlib_class_zlib_zlibbase">Class: <code>zlib.ZlibBase</code></a></p>
<ul>
<li><span class="stability_0"><a href="#zlib_zlib_bytesread"><code>zlib.bytesRead</code></a></span></li>
<li><a href="#zlib_zlib_byteswritten"><code>zlib.bytesWritten</code></a></li>
<li><a href="#zlib_zlib_close_callback"><code>zlib.close([callback])</code></a></li>
<li><a href="#zlib_zlib_flush_kind_callback"><code>zlib.flush([kind, ]callback)</code></a></li>
<li><a href="#zlib_zlib_params_level_strategy_callback"><code>zlib.params(level, strategy, callback)</code></a></li>
<li><a href="#zlib_zlib_reset"><code>zlib.reset()</code></a></li>
</ul>
</li>
<li><a href="#zlib_zlib_constants_1"><code>zlib.constants</code></a></li>
<li><a href="#zlib_zlib_createbrotlicompress_options"><code>zlib.createBrotliCompress([options])</code></a></li>
<li><a href="#zlib_zlib_createbrotlidecompress_options"><code>zlib.createBrotliDecompress([options])</code></a></li>
<li><a href="#zlib_zlib_createdeflate_options"><code>zlib.createDeflate([options])</code></a></li>
<li><a href="#zlib_zlib_createdeflateraw_options"><code>zlib.createDeflateRaw([options])</code></a></li>
<li><a href="#zlib_zlib_creategunzip_options"><code>zlib.createGunzip([options])</code></a></li>
<li><a href="#zlib_zlib_creategzip_options"><code>zlib.createGzip([options])</code></a></li>
<li><a href="#zlib_zlib_createinflate_options"><code>zlib.createInflate([options])</code></a></li>
<li><a href="#zlib_zlib_createinflateraw_options"><code>zlib.createInflateRaw([options])</code></a></li>
<li><a href="#zlib_zlib_createunzip_options"><code>zlib.createUnzip([options])</code></a></li>
<li>
<p><a href="#zlib_convenience_methods">Convenience methods</a></p>
<ul>
<li><a href="#zlib_zlib_brotlicompress_buffer_options_callback"><code>zlib.brotliCompress(buffer[, options], callback)</code></a></li>
<li><a href="#zlib_zlib_brotlicompresssync_buffer_options"><code>zlib.brotliCompressSync(buffer[, options])</code></a></li>
<li><a href="#zlib_zlib_brotlidecompress_buffer_options_callback"><code>zlib.brotliDecompress(buffer[, options], callback)</code></a></li>
<li><a href="#zlib_zlib_brotlidecompresssync_buffer_options"><code>zlib.brotliDecompressSync(buffer[, options])</code></a></li>
<li><a href="#zlib_zlib_deflate_buffer_options_callback"><code>zlib.deflate(buffer[, options], callback)</code></a></li>
<li><a href="#zlib_zlib_deflatesync_buffer_options"><code>zlib.deflateSync(buffer[, options])</code></a></li>
<li><a href="#zlib_zlib_deflateraw_buffer_options_callback"><code>zlib.deflateRaw(buffer[, options], callback)</code></a></li>
<li><a href="#zlib_zlib_deflaterawsync_buffer_options"><code>zlib.deflateRawSync(buffer[, options])</code></a></li>
<li><a href="#zlib_zlib_gunzip_buffer_options_callback"><code>zlib.gunzip(buffer[, options], callback)</code></a></li>
<li><a href="#zlib_zlib_gunzipsync_buffer_options"><code>zlib.gunzipSync(buffer[, options])</code></a></li>
<li><a href="#zlib_zlib_gzip_buffer_options_callback"><code>zlib.gzip(buffer[, options], callback)</code></a></li>
<li><a href="#zlib_zlib_gzipsync_buffer_options"><code>zlib.gzipSync(buffer[, options])</code></a></li>
<li><a href="#zlib_zlib_inflate_buffer_options_callback"><code>zlib.inflate(buffer[, options], callback)</code></a></li>
<li><a href="#zlib_zlib_inflatesync_buffer_options"><code>zlib.inflateSync(buffer[, options])</code></a></li>
<li><a href="#zlib_zlib_inflateraw_buffer_options_callback"><code>zlib.inflateRaw(buffer[, options], callback)</code></a></li>
<li><a href="#zlib_zlib_inflaterawsync_buffer_options"><code>zlib.inflateRawSync(buffer[, options])</code></a></li>
<li><a href="#zlib_zlib_unzip_buffer_options_callback"><code>zlib.unzip(buffer[, options], callback)</code></a></li>
<li><a href="#zlib_zlib_unzipsync_buffer_options"><code>zlib.unzipSync(buffer[, options])</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>

      <div id="apicontent">
        <h1>About this documentation<span><a class="mark" href="#documentation_about_this_documentation" id="documentation_about_this_documentation">#</a></span></h1>


<p>Welcome to the official API reference documentation for Node.js!</p>
<p>Node.js is a JavaScript runtime built on the <a href="https://v8.dev/">V8 JavaScript engine</a>.</p>
<h2>Contributing<span><a class="mark" href="#documentation_contributing" id="documentation_contributing">#</a></span></h2>
<p>Report errors in this documentation in <a href="https://github.com/nodejs/node/issues/new">the issue tracker</a>. See
<a href="https://github.com/nodejs/node/blob/master/CONTRIBUTING.md">the contributing guide</a> for directions on how to submit pull requests.</p>
<h2>Stability index<span><a class="mark" href="#documentation_stability_index" id="documentation_stability_index">#</a></span></h2>

<p>Throughout the documentation are indications of a section's stability. Some APIs
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.</p>
<p>The stability indices are as follows:</p>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated. The feature may emit warnings. Backward
compatibility is not guaranteed.</div><p></p>
<!-- separator -->
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental. The feature is not subject to
<a href="https://semver.org/">Semantic Versioning</a> rules. Non-backward compatible changes or removal may
occur in any future release. Use of the feature is not recommended in
production environments.</div><p></p>
<!-- separator -->
<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable. Compatibility with the npm ecosystem is a high
priority.</div><p></p>
<p>Use caution when making use of Experimental features, particularly within
modules. End users may not be aware that experimental features are being used.
Bugs or behavior changes may surprise end users when Experimental API
modifications occur. To avoid surprises, use of an Experimental feature may need
a command-line flag. Experimental features may also emit a <a href="#process_event_warning">warning</a>.</p>
<h2>JSON output<span><a class="mark" href="#documentation_json_output" id="documentation_json_output">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.12</span>
</div>
<p>Every <code>.html</code> document has a corresponding <code>.json</code> document. This is for IDEs
and other utilities that consume the documentation.</p>
<h2>System calls and man pages<span><a class="mark" href="#documentation_system_calls_and_man_pages" id="documentation_system_calls_and_man_pages">#</a></span></h2>
<p>Node.js functions which wrap a system call will document that. The docs link
to the corresponding man pages which describe how the system call works.</p>
<p>Most Unix system calls have Windows analogues. Still, behavior differences may
be unavoidable.</p>
<h1>Usage and example<span><a class="mark" href="#synopsis_usage_and_example" id="synopsis_usage_and_example">#</a></span></h1>
<h2>Usage<span><a class="mark" href="#synopsis_usage" id="synopsis_usage">#</a></span></h2>


<p><code>node [options] [V8 options] [script.js | -e "script" | - ] [arguments]</code></p>
<p>Please see the <a href="#cli_command_line_options">Command Line Options</a> document for more information.</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 in this document start with <code>$</code> or <code>></code> to replicate how they would
appear in a user's terminal. Do not include the <code>$</code> and <code>></code> characters. They are
there to show the start of each command.</p>
<p>Lines that don’t start with <code>$</code> or <code>></code> character show the output of the previous
command.</p>
<p>First, make sure to have downloaded and installed Node.js. See <a href="https://nodejs.org/en/download/package-manager/">this guide</a>
for further install information.</p>
<p>Now, create an empty project folder called <code>projects</code>, then navigate into it.</p>
<p>Linux and Mac:</p>
<pre><code class="language-console">$ mkdir ~/projects
$ cd ~/projects
</code></pre>
<p>Windows CMD:</p>
<pre><code class="language-console">> mkdir %USERPROFILE%\projects
> cd %USERPROFILE%\projects
</code></pre>
<p>Windows PowerShell:</p>
<pre><code class="language-console">> mkdir $env:USERPROFILE\projects
> cd $env:USERPROFILE\projects
</code></pre>
<p>Next, create a new source file in the <code>projects</code>
folder and call it <code>hello-world.js</code>.</p>
<p>Open <code>hello-world.js</code> in any preferred text editor and
paste in the following content:</p>
<pre><code class="language-js">const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
</code></pre>
<p>Save the file, go back to the terminal window, and enter the following command:</p>
<pre><code class="language-console">$ node hello-world.js
</code></pre>
<p>Output like this should appear in the terminal:</p>
<pre><code class="language-console">Server running at http://127.0.0.1:3000/
</code></pre>
<p>Now, open any preferred web browser and visit <code>http://127.0.0.1:3000</code>.</p>
<p>If the browser displays the string <code>Hello, World!</code>, that indicates
the server is working.</p>
<h1>Assert<span><a class="mark" href="#assert_assert" id="assert_assert">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>assert</code> module provides a set of assertion functions for verifying
invariants.</p>
<h2>Strict assertion mode<span><a class="mark" href="#assert_strict_assertion_mode" id="assert_strict_assertion_mode">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.2</td>
<td><p>Changed "strict mode" to "strict assertion mode" and "legacy mode" to "legacy assertion mode" to avoid confusion with the more usual meaining of "strict mode".</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>Added error diffs to the strict assertion mode.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>Added strict assertion mode to the assert module.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p><span>Added in: v9.9.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>In strict assertion mode, non-strict methods behave like their corresponding
strict methods. For example, <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a> will behave like
<a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a>.</p>
<p>In strict assertion mode, error messages for objects display a diff. In legacy
assertion mode, error messages for objects display the objects, often truncated.</p>
<p>To use strict assertion mode:</p>
<pre><code class="language-js">const assert = require('assert').strict;
</code></pre>
<p>Example error diff:</p>
<pre><code class="language-js">const assert = require('assert').strict;

assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected ... Lines skipped
//
//   [
//     [
// ...
//       2,
// +     3
// -     '3'
//     ],
// ...
//     5
//   ]
</code></pre>
<p>To deactivate the colors, use the <code>NO_COLOR</code> or <code>NODE_DISABLE_COLORS</code>
environment variables. This will also deactivate the colors in the REPL. For
more on color support in terminal environments, read the tty
<a href="#tty_writestream_getcolordepth_env">getColorDepth()</a> documentation.</p>
<h2>Legacy assertion mode<span><a class="mark" href="#assert_legacy_assertion_mode" id="assert_legacy_assertion_mode">#</a></span></h2>
<p>Legacy assertion mode uses the <a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">Abstract Equality Comparison</a> in:</p>
<ul>
<li><a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a></li>
<li><a href="#assert_assert_equal_actual_expected_message"><code>assert.equal()</code></a></li>
<li><a href="#assert_assert_notdeepequal_actual_expected_message"><code>assert.notDeepEqual()</code></a></li>
<li><a href="#assert_assert_notequal_actual_expected_message"><code>assert.notEqual()</code></a></li>
</ul>
<p>To use legacy assertion mode:</p>
<pre><code class="language-js">const assert = require('assert');
</code></pre>
<p>Whenever possible, use the <a href="#assert_strict_assertion_mode">strict assertion mode</a> instead. Otherwise, the
<a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">Abstract Equality Comparison</a> may cause surprising results. This is
especially true for <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a>, where the comparison rules are
lax:</p>
<pre><code class="language-js">// WARNING: This does not throw an AssertionError!
assert.deepEqual(/a/gi, new Date());
</code></pre>
<h2>Class: assert.AssertionError<a class="srclink" href="https://github.com/nodejs/node/blob/e3e0927bb93ed92bcdfe81e7ad9af3d78ccc74fb/lib/assert.js#L146">[src]</a><span><a class="mark" href="#assert_class_assert_assertionerror" id="assert_class_assert_assertionerror">#</a></span></h2>
<ul>
<li>Extends: <a href="#errors_class_error" class="type">&#x3C;errors.Error></a></li>
</ul>
<p>Indicates the failure of an assertion. All errors thrown by the <code>assert</code> module
will be instances of the <code>AssertionError</code> class.</p>
<h3><code>new assert.AssertionError(options)</code><span><a class="mark" href="#assert_new_assert_assertionerror_options" id="assert_new_assert_assertionerror_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If provided, the error message is set to this value.</li>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The <code>actual</code> property on the error instance.</li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The <code>expected</code> property on the error instance.</li>
<li><code>operator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <code>operator</code> property on the error instance.</li>
<li><code>stackStartFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> If provided, the generated stack trace omits
frames before this function.</li>
</ul>
</li>
</ul>
<p>A subclass of <code>Error</code> that indicates the failure of an assertion.</p>
<p>All instances contain the built-in <code>Error</code> properties (<code>message</code> and <code>name</code>)
and:</p>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Set to the <code>actual</code> argument for methods such as
<a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual()</code></a>.</li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Set to the <code>expected</code> value for methods such as
<a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual()</code></a>.</li>
<li><code>generatedMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Indicates if the message was auto-generated
(<code>true</code>) or not.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Value is always <code>ERR_ASSERTION</code> to show that the error is an
assertion error.</li>
<li><code>operator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Set to the passed in operator value.</li>
</ul>
<pre><code class="language-js">const assert = require('assert');

// Generate an AssertionError to compare the error message later:
const { message } = new assert.AssertionError({
  actual: 1,
  expected: 2,
  operator: 'strictEqual'
});

// Verify error output:
try {
  assert.strictEqual(1, 2);
} catch (err) {
  assert(err instanceof assert.AssertionError);
  assert.strictEqual(err.message, message);
  assert.strictEqual(err.name, 'AssertionError');
  assert.strictEqual(err.actual, 1);
  assert.strictEqual(err.expected, 2);
  assert.strictEqual(err.code, 'ERR_ASSERTION');
  assert.strictEqual(err.operator, 'strictEqual');
  assert.strictEqual(err.generatedMessage, true);
}
</code></pre>
<h2><code>assert(value[, message])</code><span><a class="mark" href="#assert_assert_value_message" id="assert_assert_value_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The input that is checked for being truthy.</li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p>An alias of <a href="#assert_assert_ok_value_message"><code>assert.ok()</code></a>.</p>
<h2><code>assert.deepEqual(actual, expected[, message])</code><span><a class="mark" href="#assert_assert_deepequal_actual_expected_message" id="assert_assert_deepequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>The type tags are now properly compared and there are a couple minor comparison adjustments to make the check less surprising.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>Error</code> names and messages are now properly compared</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>Set</code> and <code>Map</code> content is also compared</p></td></tr>
<tr><td>v6.4.0, v4.7.1</td>
<td><p>Typed array slices are handled correctly now.</p></td></tr>
<tr><td>v6.1.0, v4.5.0</td>
<td><p>Objects with circular references can be used as inputs now.</p></td></tr>
<tr><td>v5.10.1, v4.4.3</td>
<td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p><strong>Strict assertion mode</strong></p>
<p>An alias of <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a> instead.</div><p></p>
<p>Tests for deep equality between the <code>actual</code> and <code>expected</code> parameters. Consider
using <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a> instead. <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a> can have
surprising results.</p>
<p><em>Deep equality</em> means that the enumerable "own" properties of child objects
are also recursively evaluated by the following rules.</p>
<h3>Comparison details<span><a class="mark" href="#assert_comparison_details" id="assert_comparison_details">#</a></span></h3>
<ul>
<li>Primitive values are compared with the <a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">Abstract Equality Comparison</a>
( <code>==</code> ).</li>
<li><a href="https://tc39.github.io/ecma262/#sec-object.prototype.tostring">Type tags</a> of objects should be the same.</li>
<li>Only <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">enumerable "own" properties</a> are considered.</li>
<li><a href="#errors_class_error"><code>Error</code></a> names and messages are always compared, even if these are not
enumerable properties.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript">Object wrappers</a> are compared both as objects and unwrapped values.</li>
<li><code>Object</code> properties are compared unordered.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> keys and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a> items are compared unordered.</li>
<li>Recursion stops when both sides differ or both sides encounter a circular
reference.</li>
<li>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.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol"><code>Symbol</code></a> properties are not compared.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> comparison does not rely on their values.</li>
</ul>
<p>The following example does not throw an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> because the
primitives are considered equal by the <a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">Abstract Equality Comparison</a>
( <code>==</code> ).</p>
<pre><code class="language-js">// WARNING: This does not throw an AssertionError!
assert.deepEqual('+00000000', false);
</code></pre>
<p>"Deep" equality means that the enumerable "own" properties of child objects
are evaluated also:</p>
<pre><code class="language-js">const assert = require('assert');

const obj1 = {
  a: {
    b: 1
  }
};
const obj2 = {
  a: {
    b: 2
  }
};
const obj3 = {
  a: {
    b: 1
  }
};
const obj4 = Object.create(obj1);

assert.deepEqual(obj1, obj1);
// OK

// Values of b are different:
assert.deepEqual(obj1, obj2);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }

assert.deepEqual(obj1, obj3);
// OK

// Prototypes are ignored:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}
</code></pre>
<p>If the values are not equal, an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code>
property set equal to the value of the <code>message</code> parameter. If the <code>message</code>
parameter is undefined, a default error message is assigned. If the <code>message</code>
parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the
<a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a>.</p>
<h2><code>assert.deepStrictEqual(actual, expected[, message])</code><span><a class="mark" href="#assert_assert_deepstrictequal_actual_expected_message" id="assert_assert_deepstrictequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Enumerable symbol properties are now compared.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>NaN</code> is now compared using the <a href="https://tc39.github.io/ecma262/#sec-samevaluezero">SameValueZero</a> comparison.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p>The <code>Error</code> names and messages are now properly compared</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>Set</code> and <code>Map</code> content is also compared</p></td></tr>
<tr><td>v6.4.0, v4.7.1</td>
<td><p>Typed array slices are handled correctly now.</p></td></tr>
<tr><td>v6.1.0</td>
<td><p>Objects with circular references can be used as inputs now.</p></td></tr>
<tr><td>v5.10.1, v4.4.3</td>
<td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr>
<tr><td>v1.2.0</td>
<td><p><span>Added in: v1.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p>Tests for deep equality between the <code>actual</code> and <code>expected</code> parameters.
"Deep" equality means that the enumerable "own" properties of child objects
are recursively evaluated also by the following rules.</p>
<h3>Comparison details<span><a class="mark" href="#assert_comparison_details_1" id="assert_comparison_details_1">#</a></span></h3>
<ul>
<li>Primitive values are compared using the <a href="https://tc39.github.io/ecma262/#sec-samevalue">SameValue Comparison</a>, used by
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is"><code>Object.is()</code></a>.</li>
<li><a href="https://tc39.github.io/ecma262/#sec-object.prototype.tostring">Type tags</a> of objects should be the same.</li>
<li><a href="https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots"><code>[[Prototype]]</code></a> of objects are compared using
the <a href="https://tc39.github.io/ecma262/#sec-strict-equality-comparison">Strict Equality Comparison</a>.</li>
<li>Only <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">enumerable "own" properties</a> are considered.</li>
<li><a href="#errors_class_error"><code>Error</code></a> names and messages are always compared, even if these are not
enumerable properties.</li>
<li>Enumerable own <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol"><code>Symbol</code></a> properties are compared as well.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript">Object wrappers</a> are compared both as objects and unwrapped values.</li>
<li><code>Object</code> properties are compared unordered.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> keys and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a> items are compared unordered.</li>
<li>Recursion stops when both sides differ or both sides encounter a circular
reference.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> comparison does not rely on their values. See
below for further details.</li>
</ul>
<pre><code class="language-js">const assert = require('assert').strict;

// This fails because 1 !== '1'.
assert.deepStrictEqual({ a: 1 }, { a: '1' });
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
//   {
// +   a: 1
// -   a: '1'
//   }

// The following objects don't have own properties
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);

// Different [[Prototype]]:
assert.deepStrictEqual(object, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + {}
// - Date {}

// Different type tags:
assert.deepStrictEqual(date, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 2018-04-26T00:49:08.604Z
// - Date {}

assert.deepStrictEqual(NaN, NaN);
// OK, because of the SameValue comparison

// Different unwrapped numbers:
assert.deepStrictEqual(new Number(1), new Number(2));
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + [Number: 1]
// - [Number: 2]

assert.deepStrictEqual(new String('foo'), Object('foo'));
// OK because the object and the string are identical when unwrapped.

assert.deepStrictEqual(-0, -0);
// OK

// Different zeros using the SameValue Comparison:
assert.deepStrictEqual(0, -0);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 0
// - -0

const symbol1 = Symbol();
const symbol2 = Symbol();
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
// OK, because it is the same symbol on both objects.

assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
//
// {
//   [Symbol()]: 1
// }

const weakMap1 = new WeakMap();
const weakMap2 = new WeakMap([[{}, {}]]);
const weakMap3 = new WeakMap();
weakMap3.unequal = true;

assert.deepStrictEqual(weakMap1, weakMap2);
// OK, because it is impossible to compare the entries

// Fails because weakMap3 has a property that weakMap1 does not contain:
assert.deepStrictEqual(weakMap1, weakMap3);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
//   WeakMap {
// +   [items unknown]
// -   [items unknown],
// -   unequal: true
//   }
</code></pre>
<p>If the values are not equal, an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code>
property set equal to the value of the <code>message</code> parameter. If the <code>message</code>
parameter is undefined, a default error message is assigned. If the <code>message</code>
parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
<h2><code>assert.doesNotMatch(string, regexp[, message])</code><span><a class="mark" href="#assert_assert_doesnotmatch_string_regexp_message" id="assert_assert_doesnotmatch_string_regexp_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.16.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">&#x3C;string></a></li>
<li><code>regexp</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type">&#x3C;RegExp></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Expects the <code>string</code> input not to match the regular expression.</p>
<p>This feature is currently experimental and the name might change or it might be
completely removed again.</p>
<pre><code class="language-js">const assert = require('assert').strict;

assert.doesNotMatch('I will fail', /fail/);
// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...

assert.doesNotMatch(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.

assert.doesNotMatch('I will pass', /different/);
// OK
</code></pre>
<p>If the values do match, or if the <code>string</code> argument is of another type than
<code>string</code>, an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code> property set equal
to the value of the <code>message</code> parameter. If the <code>message</code> parameter is
undefined, a default error message is assigned. If the <code>message</code> parameter is an
instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the
<a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a>.</p>
<h2><code>assert.doesNotReject(asyncFn[, error][, message])</code><span><a class="mark" href="#assert_assert_doesnotreject_asyncfn_error_message" id="assert_assert_doesnotreject_asyncfn_error_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>asyncFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type">&#x3C;RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Awaits the <code>asyncFn</code> promise or, if <code>asyncFn</code> is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is not rejected.</p>
<p>If <code>asyncFn</code> is a function and it throws an error synchronously,
<code>assert.doesNotReject()</code> will return a rejected <code>Promise</code> with that error. If
the function does not return a promise, <code>assert.doesNotReject()</code> will return a
rejected <code>Promise</code> with an <a href="#errors_err_invalid_return_value"><code>ERR_INVALID_RETURN_VALUE</code></a> error. In both cases
the error handler is skipped.</p>
<p>Using <code>assert.doesNotReject()</code> is actually not useful because there is little
benefit in catching a rejection and then rejecting it again. Instead, consider
adding a comment next to the specific code path that should not reject and keep
error messages as expressive as possible.</p>
<p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a> or a validation
function. See <a href="#assert_assert_throws_fn_error_message"><code>assert.throws()</code></a> for more details.</p>
<p>Besides the async nature to await the completion behaves identically to
<a href="#assert_assert_doesnotthrow_fn_error_message"><code>assert.doesNotThrow()</code></a>.</p>
<!-- eslint-disable no-restricted-syntax -->
<pre><code class="language-js">(async () => {
  await assert.doesNotReject(
    async () => {
      throw new TypeError('Wrong value');
    },
    SyntaxError
  );
})();
</code></pre>
<!-- eslint-disable no-restricted-syntax -->
<pre><code class="language-js">assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
  .then(() => {
    // ...
  });
</code></pre>
<h2><code>assert.doesNotThrow(fn[, error][, message])</code><span><a class="mark" href="#assert_assert_doesnotthrow_fn_error_message" id="assert_assert_doesnotthrow_fn_error_message">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.11.0, v4.4.5</td>
<td><p>The <code>message</code> parameter is respected now.</p></td></tr>
<tr><td>v4.2.0</td>
<td><p>The <code>error</code> parameter can now be an arrow function.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type">&#x3C;RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Asserts that the function <code>fn</code> does not throw an error.</p>
<p>Using <code>assert.doesNotThrow()</code> is actually not useful because there
is no benefit in catching an error and then rethrowing it. Instead, consider
adding a comment next to the specific code path that should not throw and keep
error messages as expressive as possible.</p>
<p>When <code>assert.doesNotThrow()</code> is called, it will immediately call the <code>fn</code>
function.</p>
<p>If an error is thrown and it is the same type as that specified by the <code>error</code>
parameter, then an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown. If the error is of a
different type, or if the <code>error</code> parameter is undefined, the error is
propagated back to the caller.</p>
<p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a> or a validation
function. See <a href="#assert_assert_throws_fn_error_message"><code>assert.throws()</code></a> for more details.</p>
<p>The following, for instance, will throw the <a href="#errors_class_typeerror"><code>TypeError</code></a> because there is no
matching error type in the assertion:</p>
<!-- eslint-disable no-restricted-syntax -->
<pre><code class="language-js">assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  SyntaxError
);
</code></pre>
<p>However, the following will result in an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> with the message
'Got unwanted exception...':</p>
<!-- eslint-disable no-restricted-syntax -->
<pre><code class="language-js">assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  TypeError
);
</code></pre>
<p>If an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown and a value is provided for the <code>message</code>
parameter, the value of <code>message</code> will be appended to the <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a>
message:</p>
<!-- eslint-disable no-restricted-syntax -->
<pre><code class="language-js">assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  /Wrong value/,
  'Whoops'
);
// Throws: AssertionError: Got unwanted exception: Whoops
</code></pre>
<h2><code>assert.equal(actual, expected[, message])</code><span><a class="mark" href="#assert_assert_equal_actual_expected_message" id="assert_assert_equal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p><strong>Strict assertion mode</strong></p>
<p>An alias of <a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#assert_assert_strictequal_actual_expected_message"><code>assert.strictEqual()</code></a> instead.</div><p></p>
<p>Tests shallow, coercive equality between the <code>actual</code> and <code>expected</code> parameters
using the <a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">Abstract Equality Comparison</a> ( <code>==</code> ).</p>
<pre><code class="language-js">const assert = require('assert');

assert.equal(1, 1);
// OK, 1 == 1
assert.equal(1, '1');
// OK, 1 == '1'

assert.equal(1, 2);
// AssertionError: 1 == 2
assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
</code></pre>
<p>If the values are not equal, an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code>
property set equal to the value of the <code>message</code> parameter. If the <code>message</code>
parameter is undefined, a default error message is assigned. If the <code>message</code>
parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
<h2><code>assert.fail([message])</code><span><a class="mark" href="#assert_assert_fail_message" id="assert_assert_fail_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> <strong>Default:</strong> <code>'Failed'</code></li>
</ul>
<p>Throws an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> with the provided error message or a default
error message. If the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then
it will be thrown instead of the <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a>.</p>
<pre><code class="language-js">const assert = require('assert').strict;

assert.fail();
// AssertionError [ERR_ASSERTION]: Failed

assert.fail('boom');
// AssertionError [ERR_ASSERTION]: boom

assert.fail(new TypeError('need array'));
// TypeError: need array
</code></pre>
<p>Using <code>assert.fail()</code> with more than two arguments is possible but deprecated.
See below for further details.</p>
<h2><code>assert.fail(actual, expected[, message[, operator[, stackStartFn]]])</code><span><a class="mark" href="#assert_assert_fail_actual_expected_message_operator_stackstartfn" id="assert_assert_fail_actual_expected_message_operator_stackstartfn">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Calling <code>assert.fail()</code> with more than one argument is deprecated and emits a warning.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>assert.fail([message])</code> or other assert
functions instead.</div><p></p>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>operator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'!='</code></li>
<li><code>stackStartFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> <strong>Default:</strong> <code>assert.fail</code></li>
</ul>
<p>If <code>message</code> is falsy, the error message is set as the values of <code>actual</code> and
<code>expected</code> separated by the provided <code>operator</code>. If just the two <code>actual</code> and
<code>expected</code> arguments are provided, <code>operator</code> will default to <code>'!='</code>. If
<code>message</code> is provided as third argument it will be used as the error message and
the other arguments will be stored as properties on the thrown object. If
<code>stackStartFn</code> is provided, all stack frames above that function will be
removed from stacktrace (see <a href="#errors_error_capturestacktrace_targetobject_constructoropt"><code>Error.captureStackTrace</code></a>). If no arguments are
given, the default message <code>Failed</code> will be used.</p>
<pre><code class="language-js">const assert = require('assert').strict;

assert.fail('a', 'b');
// AssertionError [ERR_ASSERTION]: 'a' != 'b'

assert.fail(1, 2, undefined, '>');
// AssertionError [ERR_ASSERTION]: 1 > 2

assert.fail(1, 2, 'fail');
// AssertionError [ERR_ASSERTION]: fail

assert.fail(1, 2, 'whoops', '>');
// AssertionError [ERR_ASSERTION]: whoops

assert.fail(1, 2, new TypeError('need array'));
// TypeError: need array
</code></pre>
<p>In the last three cases <code>actual</code>, <code>expected</code>, and <code>operator</code> have no
influence on the error message.</p>
<p>Example use of <code>stackStartFn</code> for truncating the exception's stacktrace:</p>
<pre><code class="language-js">function suppressFrame() {
  assert.fail('a', 'b', undefined, '!==', suppressFrame);
}
suppressFrame();
// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
//     at repl:1:1
//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)
//     ...
</code></pre>
<h2><code>assert.ifError(value)</code><span><a class="mark" href="#assert_assert_iferror_value" id="assert_assert_iferror_value">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Instead of throwing the original error it is now wrapped into an [<code>AssertionError</code>][] that contains the full stack trace.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Value may now only be <code>undefined</code> or <code>null</code>. Before all falsy values were handled the same as <code>null</code> and did not throw.</p></td></tr>
<tr><td>v0.1.97</td>
<td><p><span>Added in: v0.1.97</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Throws <code>value</code> if <code>value</code> is not <code>undefined</code> or <code>null</code>. This is useful when
testing the <code>error</code> argument in callbacks. The stack trace contains all frames
from the error passed to <code>ifError()</code> including the potential new frames for
<code>ifError()</code> itself.</p>
<pre><code class="language-js">const assert = require('assert').strict;

assert.ifError(null);
// OK
assert.ifError(0);
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
assert.ifError('error');
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
assert.ifError(new Error());
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error

// Create some random error frames.
let err;
(function errorFrame() {
  err = new Error('test error');
})();

(function ifErrorFrame() {
  assert.ifError(err);
})();
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
//     at ifErrorFrame
//     at errorFrame
</code></pre>
<h2><code>assert.match(string, regexp[, message])</code><span><a class="mark" href="#assert_assert_match_string_regexp_message" id="assert_assert_match_string_regexp_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.16.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">&#x3C;string></a></li>
<li><code>regexp</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type">&#x3C;RegExp></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Expects the <code>string</code> input to match the regular expression.</p>
<p>This feature is currently experimental and the name might change or it might be
completely removed again.</p>
<pre><code class="language-js">const assert = require('assert').strict;

assert.match('I will fail', /pass/);
// AssertionError [ERR_ASSERTION]: The input did not match the regular ...

assert.match(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.

assert.match('I will pass', /pass/);
// OK
</code></pre>
<p>If the values do not match, or if the <code>string</code> argument is of another type than
<code>string</code>, an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code> property set equal
to the value of the <code>message</code> parameter. If the <code>message</code> parameter is
undefined, a default error message is assigned. If the <code>message</code> parameter is an
instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the
<a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a>.</p>
<h2><code>assert.notDeepEqual(actual, expected[, message])</code><span><a class="mark" href="#assert_assert_notdeepequal_actual_expected_message" id="assert_assert_notdeepequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>Error</code> names and messages are now properly compared</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>Set</code> and <code>Map</code> content is also compared</p></td></tr>
<tr><td>v6.4.0, v4.7.1</td>
<td><p>Typed array slices are handled correctly now.</p></td></tr>
<tr><td>v6.1.0, v4.5.0</td>
<td><p>Objects with circular references can be used as inputs now.</p></td></tr>
<tr><td>v5.10.1, v4.4.3</td>
<td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p><strong>Strict assertion mode</strong></p>
<p>An alias of <a href="#assert_assert_notdeepstrictequal_actual_expected_message"><code>assert.notDeepStrictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#assert_assert_notdeepstrictequal_actual_expected_message"><code>assert.notDeepStrictEqual()</code></a> instead.</div><p></p>
<p>Tests for any deep inequality. Opposite of <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a>.</p>
<pre><code class="language-js">const assert = require('assert');

const obj1 = {
  a: {
    b: 1
  }
};
const obj2 = {
  a: {
    b: 2
  }
};
const obj3 = {
  a: {
    b: 1
  }
};
const obj4 = Object.create(obj1);

assert.notDeepEqual(obj1, obj1);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }

assert.notDeepEqual(obj1, obj2);
// OK

assert.notDeepEqual(obj1, obj3);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }

assert.notDeepEqual(obj1, obj4);
// OK
</code></pre>
<p>If the values are deeply equal, an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown with a
<code>message</code> property set equal to the value of the <code>message</code> parameter. If the
<code>message</code> parameter is undefined, a default error message is assigned. If the
<code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown
instead of the <code>AssertionError</code>.</p>
<h2><code>assert.notDeepStrictEqual(actual, expected[, message])</code><span><a class="mark" href="#assert_assert_notdeepstrictequal_actual_expected_message" id="assert_assert_notdeepstrictequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>-0</code> and <code>+0</code> are not considered equal anymore.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>NaN</code> is now compared using the <a href="https://tc39.github.io/ecma262/#sec-samevaluezero">SameValueZero</a> comparison.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>Error</code> names and messages are now properly compared</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>Set</code> and <code>Map</code> content is also compared</p></td></tr>
<tr><td>v6.4.0, v4.7.1</td>
<td><p>Typed array slices are handled correctly now.</p></td></tr>
<tr><td>v6.1.0</td>
<td><p>Objects with circular references can be used as inputs now.</p></td></tr>
<tr><td>v5.10.1, v4.4.3</td>
<td><p>Handle non-<code>Uint8Array</code> typed arrays correctly.</p></td></tr>
<tr><td>v1.2.0</td>
<td><p><span>Added in: v1.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p>Tests for deep strict inequality. Opposite of <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a>.</p>
<pre><code class="language-js">const assert = require('assert').strict;

assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
// OK
</code></pre>
<p>If the values are deeply and strictly equal, an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown
with a <code>message</code> property set equal to the value of the <code>message</code> parameter. If
the <code>message</code> parameter is undefined, a default error message is assigned. If
the <code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown
instead of the <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a>.</p>
<h2><code>assert.notEqual(actual, expected[, message])</code><span><a class="mark" href="#assert_assert_notequal_actual_expected_message" id="assert_assert_notequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p><strong>Strict assertion mode</strong></p>
<p>An alias of <a href="#assert_assert_notstrictequal_actual_expected_message"><code>assert.notStrictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#assert_assert_notstrictequal_actual_expected_message"><code>assert.notStrictEqual()</code></a> instead.</div><p></p>
<p>Tests shallow, coercive inequality with the <a href="https://tc39.github.io/ecma262/#sec-abstract-equality-comparison">Abstract Equality Comparison</a>
( <code>!=</code> ).</p>
<pre><code class="language-js">const assert = require('assert');

assert.notEqual(1, 2);
// OK

assert.notEqual(1, 1);
// AssertionError: 1 != 1

assert.notEqual(1, '1');
// AssertionError: 1 != '1'
</code></pre>
<p>If the values are equal, an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code>
property set equal to the value of the <code>message</code> parameter. If the <code>message</code>
parameter is undefined, a default error message is assigned. If the <code>message</code>
parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
<h2><code>assert.notStrictEqual(actual, expected[, message])</code><span><a class="mark" href="#assert_assert_notstrictequal_actual_expected_message" id="assert_assert_notstrictequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Used comparison changed from Strict Equality to <code>Object.is()</code></p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p>Tests strict inequality between the <code>actual</code> and <code>expected</code> parameters as
determined by the <a href="https://tc39.github.io/ecma262/#sec-samevalue">SameValue Comparison</a>.</p>
<pre><code class="language-js">const assert = require('assert').strict;

assert.notStrictEqual(1, 2);
// OK

assert.notStrictEqual(1, 1);
// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
//
// 1

assert.notStrictEqual(1, '1');
// OK
</code></pre>
<p>If the values are strictly equal, an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown with a
<code>message</code> property set equal to the value of the <code>message</code> parameter. If the
<code>message</code> parameter is undefined, a default error message is assigned. If the
<code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown
instead of the <code>AssertionError</code>.</p>
<h2><code>assert.ok(value[, message])</code><span><a class="mark" href="#assert_assert_ok_value_message" id="assert_assert_ok_value_message">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>assert.ok()</code> (no arguments) will now use a predefined error message.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p>Tests if <code>value</code> is truthy. It is equivalent to
<code>assert.equal(!!value, true, message)</code>.</p>
<p>If <code>value</code> is not truthy, an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown with a <code>message</code>
property set equal to the value of the <code>message</code> parameter. If the <code>message</code>
parameter is <code>undefined</code>, a default error message is assigned. If the <code>message</code>
parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.
If no arguments are passed in at all <code>message</code> will be set to the string:
<code>'No value argument passed to `assert.ok()`'</code>.</p>
<p>Be aware that in the <code>repl</code> the error message will be different to the one
thrown in a file! See below for further details.</p>
<pre><code class="language-js">const assert = require('assert').strict;

assert.ok(true);
// OK
assert.ok(1);
// OK

assert.ok();
// AssertionError: No value argument passed to `assert.ok()`

assert.ok(false, 'it\'s false');
// AssertionError: it's false

// In the repl:
assert.ok(typeof 123 === 'string');
// AssertionError: false == true

// In a file (e.g. test.js):
assert.ok(typeof 123 === 'string');
// AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(typeof 123 === 'string')

assert.ok(false);
// AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(false)

assert.ok(0);
// AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(0)

// Using `assert()` works the same:
assert(0);
// AssertionError: The expression evaluated to a falsy value:
//
//   assert(0)
</code></pre>
<h2><code>assert.rejects(asyncFn[, error][, message])</code><span><a class="mark" href="#assert_assert_rejects_asyncfn_error_message" id="assert_assert_rejects_asyncfn_error_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>asyncFn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type">&#x3C;RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Awaits the <code>asyncFn</code> promise or, if <code>asyncFn</code> is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is rejected.</p>
<p>If <code>asyncFn</code> is a function and it throws an error synchronously,
<code>assert.rejects()</code> will return a rejected <code>Promise</code> with that error. If the
function does not return a promise, <code>assert.rejects()</code> will return a rejected
<code>Promise</code> with an <a href="#errors_err_invalid_return_value"><code>ERR_INVALID_RETURN_VALUE</code></a> error. In both cases the error
handler is skipped.</p>
<p>Besides the async nature to await the completion behaves identically to
<a href="#assert_assert_throws_fn_error_message"><code>assert.throws()</code></a>.</p>
<p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>, a validation function,
an object where each property will be tested for, or an instance of error where
each property will be tested for including the non-enumerable <code>message</code> and
<code>name</code> properties.</p>
<p>If specified, <code>message</code> will be the message provided by the <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a>
if the <code>asyncFn</code> fails to reject.</p>
<pre><code class="language-js">(async () => {
  await assert.rejects(
    async () => {
      throw new TypeError('Wrong value');
    },
    {
      name: 'TypeError',
      message: 'Wrong value'
    }
  );
})();
</code></pre>
<pre><code class="language-js">(async () => {
  await assert.rejects(
    async () => {
      throw new TypeError('Wrong value');
    },
    (err) => {
      assert.strictEqual(err.name, 'TypeError');
      assert.strictEqual(err.message, 'Wrong value');
      return true;
    }
  );
})();
</code></pre>
<pre><code class="language-js">assert.rejects(
  Promise.reject(new Error('Wrong value')),
  Error
).then(() => {
  // ...
});
</code></pre>
<p><code>error</code> cannot be a string. If a string is provided as the second
argument, then <code>error</code> is assumed to be omitted and the string will be used for
<code>message</code> instead. This can lead to easy-to-miss mistakes. Please read the
example in <a href="#assert_assert_throws_fn_error_message"><code>assert.throws()</code></a> carefully if using a string as the second
argument gets considered.</p>
<h2><code>assert.strictEqual(actual, expected[, message])</code><span><a class="mark" href="#assert_assert_strictequal_actual_expected_message" id="assert_assert_strictequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Used comparison changed from Strict Equality to <code>Object.is()</code></p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p>Tests strict equality between the <code>actual</code> and <code>expected</code> parameters as
determined by the <a href="https://tc39.github.io/ecma262/#sec-samevalue">SameValue Comparison</a>.</p>
<pre><code class="language-js">const assert = require('assert').strict;

assert.strictEqual(1, 2);
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 2

assert.strictEqual(1, 1);
// OK

assert.strictEqual('Hello foobar', 'Hello World!');
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
// + actual - expected
//
// + 'Hello foobar'
// - 'Hello World!'
//          ^

const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2

assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
// TypeError: Inputs are not identical
</code></pre>
<p>If the values are not strictly equal, an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a> is thrown with a
<code>message</code> property set equal to the value of the <code>message</code> parameter. If the
<code>message</code> parameter is undefined, a default error message is assigned. If the
<code>message</code> parameter is an instance of an <a href="#errors_class_error"><code>Error</code></a> then it will be thrown
instead of the <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a>.</p>
<h2><code>assert.throws(fn[, error][, message])</code><span><a class="mark" href="#assert_assert_throws_fn_error_message" id="assert_assert_throws_fn_error_message">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.2.0</td>
<td><p>The <code>error</code> parameter can be an object containing regular expressions now.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>error</code> parameter can now be an object as well.</p></td></tr>
<tr><td>v4.2.0</td>
<td><p>The <code>error</code> parameter can now be an arrow function.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" class="type">&#x3C;RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Expects the function <code>fn</code> to throw an error.</p>
<p>If specified, <code>error</code> can be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes"><code>Class</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>, a validation function,
a validation object where each property will be tested for strict deep equality,
or an instance of error where each property will be tested for strict deep
equality including the non-enumerable <code>message</code> and <code>name</code> properties. When
using an object, it is also possible to use a regular expression, when
validating against a string property. See below for examples.</p>
<p>If specified, <code>message</code> will be appended to the message provided by the
<code>AssertionError</code> if the <code>fn</code> call fails to throw or in case the error validation
fails.</p>
<p>Custom validation object/error instance:</p>
<pre><code class="language-js">const err = new TypeError('Wrong value');
err.code = 404;
err.foo = 'bar';
err.info = {
  nested: true,
  baz: 'text'
};
err.reg = /abc/i;

assert.throws(
  () => {
    throw err;
  },
  {
    name: 'TypeError',
    message: 'Wrong value',
    info: {
      nested: true,
      baz: 'text'
    }
    // Only properties on the validation object will be tested for.
    // Using nested objects requires all properties to be present. Otherwise
    // the validation is going to fail.
  }
);

// Using regular expressions to validate error properties:
assert.throws(
  () => {
    throw err;
  },
  {
    // The `name` and `message` properties are strings and using regular
    // expressions on those will match against the string. If they fail, an
    // error is thrown.
    name: /^TypeError$/,
    message: /Wrong/,
    foo: 'bar',
    info: {
      nested: true,
      // It is not possible to use regular expressions for nested properties!
      baz: 'text'
    },
    // The `reg` property contains a regular expression and only if the
    // validation object contains an identical regular expression, it is going
    // to pass.
    reg: /abc/i
  }
);

// Fails due to the different `message` and `name` properties:
assert.throws(
  () => {
    const otherErr = new Error('Not found');
    // Copy all enumerable properties from `err` to `otherErr`.
    for (const [key, value] of Object.entries(err)) {
      otherErr[key] = value;
    }
    throw otherErr;
  },
  // The error's `message` and `name` properties will also be checked when using
  // an error as validation object.
  err
);
</code></pre>
<p>Validate instanceof using constructor:</p>
<pre><code class="language-js">assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  Error
);
</code></pre>
<p>Validate error message using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>:</p>
<p>Using a regular expression runs <code>.toString</code> on the error object, and will
therefore also include the error name.</p>
<pre><code class="language-js">assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  /^Error: Wrong value$/
);
</code></pre>
<p>Custom error validation:</p>
<p>The function must return <code>true</code> to indicate all internal validations passed.
It will otherwise fail with an <a href="#assert_class_assert_assertionerror"><code>AssertionError</code></a>.</p>
<pre><code class="language-js">assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  (err) => {
    assert(err instanceof Error);
    assert(/value/.test(err));
    // Avoid returning anything from validation functions besides `true`.
    // Otherwise, it's not clear what part of the validation failed. Instead,
    // throw an error about the specific validation that failed (as done in this
    // example) and add as much helpful debugging information to that error as
    // possible.
    return true;
  },
  'unexpected error'
);
</code></pre>
<p><code>error</code> cannot be a string. If a string is provided as the second
argument, then <code>error</code> is assumed to be omitted and the string will be used for
<code>message</code> instead. This can lead to easy-to-miss mistakes. Using the same
message as the thrown error message is going to result in an
<code>ERR_AMBIGUOUS_ARGUMENT</code> error. Please read the example below carefully if using
a string as the second argument gets considered:</p>
<!-- eslint-disable no-restricted-syntax -->
<pre><code class="language-js">function throwingFirst() {
  throw new Error('First');
}

function throwingSecond() {
  throw new Error('Second');
}

function notThrowing() {}

// The second argument is a string and the input function threw an Error.
// The first case will not throw as it does not match for the error message
// thrown by the input function!
assert.throws(throwingFirst, 'Second');
// In the next example the message has no benefit over the message from the
// error and since it is not clear if the user intended to actually match
// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
assert.throws(throwingSecond, 'Second');
// TypeError [ERR_AMBIGUOUS_ARGUMENT]

// The string is only used (as message) in case the function does not throw:
assert.throws(notThrowing, 'Second');
// AssertionError [ERR_ASSERTION]: Missing expected exception: Second

// If it was intended to match for the error message do this instead:
// It does not throw because the error messages match.
assert.throws(throwingSecond, /Second$/);

// If the error message does not match, an AssertionError is thrown.
assert.throws(throwingFirst, /Second$/);
// AssertionError [ERR_ASSERTION]
</code></pre>
<p>Due to the confusing error-prone notation, avoid a string as the second
argument.</p>
<h1>Async hooks<span><a class="mark" href="#async_hooks_async_hooks" id="async_hooks_async_hooks">#</a></span></h1>

<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>The <code>async_hooks</code> module provides an API to track asynchronous resources. It
can be accessed using:</p>
<pre><code class="language-js">const async_hooks = require('async_hooks');
</code></pre>
<h2>Terminology<span><a class="mark" href="#async_hooks_terminology" id="async_hooks_terminology">#</a></span></h2>
<p>An asynchronous resource represents an object with an associated callback.
This callback may be called multiple times, for example, the <code>'connection'</code>
event in <code>net.createServer()</code>, or just a single time like in <code>fs.open()</code>.
A resource can also be closed before the callback is called. <code>AsyncHook</code> does
not explicitly distinguish between these different cases but will represent them
as the abstract concept that is a resource.</p>
<p>If <a href="#worker_threads_class_worker"><code>Worker</code></a>s are used, each thread has an independent <code>async_hooks</code>
interface, and each thread will use a new set of async IDs.</p>
<h2>Public API<span><a class="mark" href="#async_hooks_public_api" id="async_hooks_public_api">#</a></span></h2>
<h3>Overview<span><a class="mark" href="#async_hooks_overview" id="async_hooks_overview">#</a></span></h3>
<p>Following is a simple overview of the public API.</p>
<pre><code class="language-js">const async_hooks = require('async_hooks');

// Return the ID of the current execution context.
const eid = async_hooks.executionAsyncId();

// Return the ID of the handle responsible for triggering the callback of the
// current execution scope to call.
const tid = async_hooks.triggerAsyncId();

// Create a new AsyncHook instance. All of these callbacks are optional.
const asyncHook =
    async_hooks.createHook({ init, before, after, destroy, promiseResolve });

// Allow callbacks of this AsyncHook instance to call. This is not an implicit
// action after running the constructor, and must be explicitly run to begin
// executing callbacks.
asyncHook.enable();

// Disable listening for new asynchronous events.
asyncHook.disable();

//
// The following are the callbacks that can be passed to createHook().
//

// init is called during object construction. The resource may not have
// completed construction when this callback runs, therefore all fields of the
// resource referenced by "asyncId" may not have been populated.
function init(asyncId, type, triggerAsyncId, resource) { }

// Before is called just before the resource's callback is called. It can be
// called 0-N times for handles (e.g. TCPWrap), and will be called exactly 1
// time for requests (e.g. FSReqCallback).
function before(asyncId) { }

// After is called just after the resource's callback has finished.
function after(asyncId) { }

// Destroy is called when the resource 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>
<p><code>callbacks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#async_hooks_hook_callbacks">Hook Callbacks</a> to register</p>
<ul>
<li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;Function></a> The <a href="#async_hooks_destroy_asyncid"><code>destroy</code> callback</a>.</li>
<li><code>promiseResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#async_hooks_promiseresolve_asyncid"><code>promiseResolve</code> callback</a>.</li>
</ul>
</li>
<li>Returns: <a href="#async_hooks_async_hooks_createhook_callbacks" class="type">&#x3C;AsyncHook></a> Instance used for disabling and enabling hooks</li>
</ul>
<p>Registers functions to be called for different lifetime events of each async
operation.</p>
<p>The callbacks <code>init()</code>/<code>before()</code>/<code>after()</code>/<code>destroy()</code> are called for the
respective asynchronous event during a resource's lifetime.</p>
<p>All callbacks are optional. For example, if only resource cleanup needs to
be tracked, then only the <code>destroy</code> callback needs to be passed. The
specifics of all functions that can be passed to <code>callbacks</code> is in the
<a href="#async_hooks_hook_callbacks">Hook Callbacks</a> section.</p>
<pre><code class="language-js">const async_hooks = require('async_hooks');

const asyncHook = async_hooks.createHook({
  init(asyncId, type, triggerAsyncId, resource) { },
  destroy(asyncId) { }
});
</code></pre>
<p>The callbacks will be inherited via the prototype chain:</p>
<pre><code class="language-js">class MyAsyncCallbacks {
  init(asyncId, type, triggerAsyncId, resource) { }
  destroy(asyncId) {}
}

class MyAddedCallbacks extends MyAsyncCallbacks {
  before(asyncId) { }
  after(asyncId) { }
}

const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
</code></pre>
<h5>Error handling<span><a class="mark" href="#async_hooks_error_handling" id="async_hooks_error_handling">#</a></span></h5>
<p>If any <code>AsyncHook</code> callbacks throw, the application will print the stack trace
and exit. The exit path does follow that of an uncaught exception, but
all <code>'uncaughtException'</code> listeners are removed, thus forcing the process to
exit. The <code>'exit'</code> callbacks will still be called unless the application is run
with <code>--abort-on-uncaught-exception</code>, in which case a stack trace will be
printed and the application exits, leaving a core file.</p>
<p>The reason for this error handling behavior is that these callbacks are running
at potentially volatile points in an object's lifetime, for example during
class construction and destruction. Because of this, it is deemed necessary to
bring down the process quickly in order to prevent an unintentional abort in the
future. This is subject to change in the future if a comprehensive analysis is
performed to ensure an exception can follow the normal control flow without
unintentional side effects.</p>
<h5>Printing in AsyncHooks callbacks<span><a class="mark" href="#async_hooks_printing_in_asynchooks_callbacks" id="async_hooks_printing_in_asynchooks_callbacks">#</a></span></h5>
<p>Because printing to the console is an asynchronous operation, <code>console.log()</code>
will cause the AsyncHooks callbacks to be called. Using <code>console.log()</code> or
similar asynchronous operations inside an AsyncHooks callback function will thus
cause an infinite recursion. An easy solution to this when debugging is to use a
synchronous logging operation such as <code>fs.writeFileSync(file, msg, flag)</code>.
This will print to the file and will not invoke AsyncHooks recursively because
it is synchronous.</p>
<pre><code class="language-js">const fs = require('fs');
const util = require('util');

function debug(...args) {
  // Use a function like this one when debugging inside an AsyncHooks callback
  fs.writeFileSync('log.out', `${util.format(...args)}\n`, { flag: 'a' });
}
</code></pre>
<p>If an asynchronous operation is needed for logging, it is possible to keep
track of what caused the asynchronous operation using the information
provided by AsyncHooks itself. The logging should then be skipped when
it was the logging itself that caused AsyncHooks callback to call. By
doing this the otherwise infinite recursion is broken.</p>
<h3>Class: <code>AsyncHook</code><span><a class="mark" href="#async_hooks_class_asynchook" id="async_hooks_class_asynchook">#</a></span></h3>
<p>The class <code>AsyncHook</code> exposes an interface for tracking lifetime events
of asynchronous operations.</p>
<h4><code>asyncHook.enable()</code><span><a class="mark" href="#async_hooks_asynchook_enable" id="async_hooks_asynchook_enable">#</a></span></h4>
<ul>
<li>Returns: <a href="#async_hooks_async_hooks_createhook_callbacks" class="type">&#x3C;AsyncHook></a> A reference to <code>asyncHook</code>.</li>
</ul>
<p>Enable the callbacks for a given <code>AsyncHook</code> instance. If no callbacks are
provided enabling is a noop.</p>
<p>The <code>AsyncHook</code> instance is disabled by default. If the <code>AsyncHook</code> instance
should be enabled immediately after creation, the following pattern can be used.</p>
<pre><code class="language-js">const async_hooks = require('async_hooks');

const hook = async_hooks.createHook(callbacks).enable();
</code></pre>
<h4><code>asyncHook.disable()</code><span><a class="mark" href="#async_hooks_asynchook_disable" id="async_hooks_asynchook_disable">#</a></span></h4>
<ul>
<li>Returns: <a href="#async_hooks_async_hooks_createhook_callbacks" class="type">&#x3C;AsyncHook></a> A reference to <code>asyncHook</code>.</li>
</ul>
<p>Disable the callbacks for a given <code>AsyncHook</code> instance from the global pool of
<code>AsyncHook</code> callbacks to be executed. Once a hook has been disabled it will not
be called again until enabled.</p>
<p>For API consistency <code>disable()</code> also returns the <code>AsyncHook</code> instance.</p>
<h4>Hook callbacks<span><a class="mark" href="#async_hooks_hook_callbacks" id="async_hooks_hook_callbacks">#</a></span></h4>
<p>Key events in the lifetime of asynchronous events have been categorized into
four areas: instantiation, before/after the callback is called, and when the
instance is destroyed.</p>
<h5><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>
<ul>
<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;Object></a> Reference to the resource representing the async
operation, needs to be released during <em>destroy</em>.</li>
</ul>
<p>Called when a class is constructed that has the <em>possibility</em> to emit an
asynchronous event. This <em>does not</em> mean the instance must call
<code>before</code>/<code>after</code> before <code>destroy</code> is called, only that the possibility
exists.</p>
<p>This behavior can be observed by doing something like opening a resource then
closing it before the resource can be used. The following snippet demonstrates
this.</p>
<pre><code class="language-js">require('net').createServer().listen(function() { this.close(); });
// OR
clearTimeout(setTimeout(() => {}, 10));
</code></pre>
<p>Every new resource is assigned an ID that is unique within the scope of the
current Node.js instance.</p>
<h6><code>type</code><span><a class="mark" href="#async_hooks_type" id="async_hooks_type">#</a></span></h6>
<p>The <code>type</code> is a string identifying the type of resource that caused
<code>init</code> to be called. Generally, it will correspond to the name of the
resource's constructor.</p>
<pre><code class="language-text">FSEVENTWRAP, FSREQCALLBACK, GETADDRINFOREQWRAP, GETNAMEINFOREQWRAP, HTTPINCOMINGMESSAGE,
HTTPCLIENTREQUEST, JSSTREAM, PIPECONNECTWRAP, PIPEWRAP, PROCESSWRAP, QUERYWRAP,
SHUTDOWNWRAP, SIGNALWRAP, STATWATCHER, TCPCONNECTWRAP, TCPSERVERWRAP, TCPWRAP,
TTYWRAP, UDPSENDWRAP, UDPWRAP, WRITEWRAP, ZLIB, SSLCONNECTION, PBKDF2REQUEST,
RANDOMBYTESREQUEST, TLSWRAP, Microtask, Timeout, Immediate, TickObject
</code></pre>
<p>There is also the <code>PROMISE</code> resource type, which is used to track <code>Promise</code>
instances and asynchronous work scheduled by them.</p>
<p>Users are able to define their own <code>type</code> when using the public embedder API.</p>
<p>It is possible to have type name collisions. Embedders are encouraged to use
unique prefixes, such as the npm package name, to prevent collisions when
listening to the hooks.</p>
<h6><code>triggerAsyncId</code><span><a class="mark" href="#async_hooks_triggerasyncid" id="async_hooks_triggerasyncid">#</a></span></h6>
<p><code>triggerAsyncId</code> is the <code>asyncId</code> of the resource that caused (or "triggered")
the new resource to initialize and that caused <code>init</code> to call. This is different
from <code>async_hooks.executionAsyncId()</code> that only shows <em>when</em> a resource was
created, while <code>triggerAsyncId</code> shows <em>why</em> a resource was created.</p>
<p>The following is a simple demonstration of <code>triggerAsyncId</code>:</p>
<pre><code class="language-js">async_hooks.createHook({
  init(asyncId, type, triggerAsyncId) {
    const eid = async_hooks.executionAsyncId();
    fs.writeSync(
      1, `${type}(${asyncId}): trigger: ${triggerAsyncId} execution: ${eid}\n`);
  }
}).enable();

require('net').createServer((conn) => {}).listen(8080);
</code></pre>
<p>Output when hitting the server with <code>nc localhost 8080</code>:</p>
<pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1
TCPWRAP(7): trigger: 5 execution: 0
</code></pre>
<p>The <code>TCPSERVERWRAP</code> is the server which receives the connections.</p>
<p>The <code>TCPWRAP</code> is the new connection from the client. When a new
connection is made, the <code>TCPWrap</code> instance is immediately constructed. This
happens outside of any JavaScript stack. (An <code>executionAsyncId()</code> of <code>0</code> means
that it is being executed from C++ with no JavaScript stack above it.) With only
that information, it would be impossible to link resources together in
terms of what caused them to be created, so <code>triggerAsyncId</code> is given the task
of propagating what resource is responsible for the new resource's existence.</p>
<h6><code>resource</code><span><a class="mark" href="#async_hooks_resource" id="async_hooks_resource">#</a></span></h6>
<p><code>resource</code> is an object that represents the actual async resource that has
been initialized. This can contain useful information that can vary based on
the value of <code>type</code>. For instance, for the <code>GETADDRINFOREQWRAP</code> resource type,
<code>resource</code> provides the host name used when looking up the IP address for the
host in <code>net.Server.listen()</code>. The API for accessing this information is
currently not considered public, but using the Embedder API, users can provide
and document their own resource objects. For example, such a resource object
could contain the SQL query being executed.</p>
<p>In the case of Promises, the <code>resource</code> object will have an
<code>isChainedPromise</code> property, set to <code>true</code> if the promise has a parent promise,
and <code>false</code> otherwise. For example, in the case of <code>b = a.then(handler)</code>, <code>a</code> is
considered a parent <code>Promise</code> of <code>b</code>. Here, <code>b</code> is considered a chained promise.</p>
<p>In some cases the resource object is reused for performance reasons, it is
thus not safe to use it as a key in a <code>WeakMap</code> or add properties to it.</p>
<h6>Asynchronous context example<span><a class="mark" href="#async_hooks_asynchronous_context_example" id="async_hooks_asynchronous_context_example">#</a></span></h6>
<p>The following is an example with additional information about the calls to
<code>init</code> between the <code>before</code> and <code>after</code> calls, specifically what the
callback to <code>listen()</code> will look like. The output formatting is slightly more
elaborate to make calling context easier to see.</p>
<pre><code class="language-js">let indent = 0;
async_hooks.createHook({
  init(asyncId, type, triggerAsyncId) {
    const eid = async_hooks.executionAsyncId();
    const indentStr = ' '.repeat(indent);
    fs.writeSync(
      1,
      `${indentStr}${type}(${asyncId}):` +
      ` trigger: ${triggerAsyncId} execution: ${eid}\n`);
  },
  before(asyncId) {
    const indentStr = ' '.repeat(indent);
    fs.writeFileSync('log.out',
                     `${indentStr}before:  ${asyncId}\n`, { flag: 'a' });
    indent += 2;
  },
  after(asyncId) {
    indent -= 2;
    const indentStr = ' '.repeat(indent);
    fs.writeFileSync('log.out',
                     `${indentStr}after:  ${asyncId}\n`, { flag: 'a' });
  },
  destroy(asyncId) {
    const indentStr = ' '.repeat(indent);
    fs.writeFileSync('log.out',
                     `${indentStr}destroy:  ${asyncId}\n`, { flag: 'a' });
  },
}).enable();

require('net').createServer(() => {}).listen(8080, () => {
  // Let's wait 10ms before logging the server started.
  setTimeout(() => {
    console.log('>>>', async_hooks.executionAsyncId());
  }, 10);
});
</code></pre>
<p>Output from only starting the server:</p>
<pre><code class="language-console">TCPSERVERWRAP(5): trigger: 1 execution: 1
TickObject(6): trigger: 5 execution: 1
before:  6
  Timeout(7): trigger: 6 execution: 6
after:   6
destroy: 6
before:  7
>>> 7
  TickObject(8): trigger: 7 execution: 7
after:   7
before:  8
after:   8
</code></pre>
<p>As illustrated in the example, <code>executionAsyncId()</code> and <code>execution</code> each specify
the value of the current execution context; which is delineated by calls to
<code>before</code> and <code>after</code>.</p>
<p>Only using <code>execution</code> to graph resource allocation results in the following:</p>
<pre><code class="language-console">Timeout(7) -> TickObject(6) -> root(1)
</code></pre>
<p>The <code>TCPSERVERWRAP</code> is not part of this graph, even though it was the reason for
<code>console.log()</code> being called. This is because binding to a port without a host
name 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>
<ul>
<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>When an asynchronous operation is initiated (such as a TCP server receiving a
new connection) or completes (such as writing data to disk) a callback is
called to notify the user. The <code>before</code> callback is called just before said
callback is executed. <code>asyncId</code> is the unique identifier assigned to the
resource about to execute the callback.</p>
<p>The <code>before</code> callback will be called 0 to N times. The <code>before</code> callback
will typically be called 0 times if the asynchronous operation was cancelled
or, for example, if no connections are received by a TCP server. Persistent
asynchronous resources like a TCP server will typically call the <code>before</code>
callback multiple times, while other operations like <code>fs.open()</code> will call
it only once.</p>
<h5><code>after(asyncId)</code><span><a class="mark" href="#async_hooks_after_asyncid" id="async_hooks_after_asyncid">#</a></span></h5>
<ul>
<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Called immediately after the callback specified in <code>before</code> is completed.</p>
<p>If an uncaught exception occurs during execution of the callback, then <code>after</code>
will run <em>after</em> the <code>'uncaughtException'</code> event is emitted or a <code>domain</code>'s
handler runs.</p>
<h5><code>destroy(asyncId)</code><span><a class="mark" href="#async_hooks_destroy_asyncid" id="async_hooks_destroy_asyncid">#</a></span></h5>
<ul>
<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Called after the resource corresponding to <code>asyncId</code> is destroyed. It is also
called asynchronously from the embedder API <code>emitDestroy()</code>.</p>
<p>Some resources depend on garbage collection for cleanup, so if a reference is
made to the <code>resource</code> object passed to <code>init</code> it is possible that <code>destroy</code>
will never be called, causing a memory leak in the application. If the resource
does not depend on garbage collection, then this will not be an issue.</p>
<h5><code>promiseResolve(asyncId)</code><span><a class="mark" href="#async_hooks_promiseresolve_asyncid" id="async_hooks_promiseresolve_asyncid">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v8.6.0</span>
</div>
<ul>
<li><code>asyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Called when the <code>resolve</code> function passed to the <code>Promise</code> constructor is
invoked (either directly or through other means of resolving a promise).</p>
<p><code>resolve()</code> does not do any observable synchronous work.</p>
<p>The <code>Promise</code> is not necessarily fulfilled or rejected at this point if the
<code>Promise</code> was resolved by assuming the state of another <code>Promise</code>.</p>
<pre><code class="language-js">new Promise((resolve) => resolve(true)).then((a) => {});
</code></pre>
<p>calls the following callbacks:</p>
<pre><code class="language-text">init for PROMISE with id 5, trigger id: 1
  promise resolve 5      # corresponds to resolve(true)
init for PROMISE with id 6, trigger id: 5  # the Promise returned by then()
  before 6               # the then() callback is entered
  promise resolve 6      # the then() callback resolves the promise by returning
  after 6
</code></pre>
<h4><code>async_hooks.executionAsyncResource()</code><span><a class="mark" href="#async_hooks_async_hooks_executionasyncresource" id="async_hooks_async_hooks_executionasyncresource">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The resource representing the current execution.
Useful to store data within the resource.</li>
</ul>
<p>Resource objects returned by <code>executionAsyncResource()</code> are most often internal
Node.js handle objects with undocumented APIs. Using any functions or properties
on the object is likely to crash your application and should be avoided.</p>
<p>Using <code>executionAsyncResource()</code> in the top-level execution context will
return an empty object as there is no handle or request object to use,
but having an object representing the top-level can be helpful.</p>
<pre><code class="language-js">const { open } = require('fs');
const { executionAsyncId, executionAsyncResource } = require('async_hooks');

console.log(executionAsyncId(), executionAsyncResource());  // 1 {}
open(__filename, 'r', (err, fd) => {
  console.log(executionAsyncId(), executionAsyncResource());  // 7 FSReqWrap
});
</code></pre>
<p>This can be used to implement continuation local storage without the
use of a tracking <code>Map</code> to store the metadata:</p>
<pre><code class="language-js">const { createServer } = require('http');
const {
  executionAsyncId,
  executionAsyncResource,
  createHook
} = require('async_hooks');
const sym = Symbol('state'); // Private symbol to avoid pollution

createHook({
  init(asyncId, type, triggerAsyncId, resource) {
    const cr = executionAsyncResource();
    if (cr) {
      resource[sym] = cr[sym];
    }
  }
}).enable();

const server = createServer((req, res) => {
  executionAsyncResource()[sym] = { state: req.url };
  setTimeout(function() {
    res.end(JSON.stringify(executionAsyncResource()[sym]));
  }, 100);
}).listen(3000);
</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>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.2.0</td>
<td><p>Renamed from <code>currentId</code></p></td></tr>
<tr><td>v8.1.0</td>
<td><p><span>Added in: v8.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The <code>asyncId</code> of the current execution context. Useful to
track when something calls.</li>
</ul>
<pre><code class="language-js">const async_hooks = require('async_hooks');

console.log(async_hooks.executionAsyncId());  // 1 - bootstrap
fs.open(path, 'r', (err, fd) => {
  console.log(async_hooks.executionAsyncId());  // 6 - open()
});
</code></pre>
<p>The ID returned from <code>executionAsyncId()</code> is related to execution timing, not
causality (which is covered by <code>triggerAsyncId()</code>):</p>
<pre><code class="language-js">const server = net.createServer((conn) => {
  // Returns the ID of the server, not of the new connection, because the
  // callback runs in the execution scope of the server's MakeCallback().
  async_hooks.executionAsyncId();

}).listen(port, () => {
  // Returns the ID of a TickObject (i.e. process.nextTick()) because all
  // callbacks passed to .listen() are wrapped in a nextTick().
  async_hooks.executionAsyncId();
});
</code></pre>
<p>Promise contexts may not get precise <code>executionAsyncIds</code> by default.
See the section on <a href="#async_hooks_promise_execution_tracking">promise execution tracking</a>.</p>
<h4><code>async_hooks.triggerAsyncId()</code><span><a class="mark" href="#async_hooks_async_hooks_triggerasyncid" id="async_hooks_async_hooks_triggerasyncid">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The ID of the resource responsible for calling the callback
that is currently being executed.</li>
</ul>
<pre><code class="language-js">const server = net.createServer((conn) => {
  // The resource that caused (or triggered) this callback to be called
  // was that of the new connection. Thus the return value of triggerAsyncId()
  // is the asyncId of "conn".
  async_hooks.triggerAsyncId();

}).listen(port, () => {
  // Even though all callbacks passed to .listen() are wrapped in a nextTick()
  // the callback itself exists because the call to the server's .listen()
  // was made. So the return value would be the ID of the server.
  async_hooks.triggerAsyncId();
});
</code></pre>
<p>Promise contexts may not get valid <code>triggerAsyncId</code>s by default. See
the section on <a href="#async_hooks_promise_execution_tracking">promise execution tracking</a>.</p>
<h2>Promise execution tracking<span><a class="mark" href="#async_hooks_promise_execution_tracking" id="async_hooks_promise_execution_tracking">#</a></span></h2>
<p>By default, promise executions are not assigned <code>asyncId</code>s due to the relatively
expensive nature of the <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">promise introspection API</a> provided by
V8. This means that programs using promises or <code>async</code>/<code>await</code> will not get
correct execution and trigger ids for promise callback contexts by default.</p>
<pre><code class="language-js">const ah = require('async_hooks');
Promise.resolve(1729).then(() => {
  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);
});
// produces:
// eid 1 tid 0
</code></pre>
<p>Observe that the <code>then()</code> callback claims to have executed in the context of the
outer scope even though there was an asynchronous hop involved. Also,
the <code>triggerAsyncId</code> value is <code>0</code>, which means that we are missing context about
the resource that caused (triggered) the <code>then()</code> callback to be executed.</p>
<p>Installing async hooks via <code>async_hooks.createHook</code> enables promise execution
tracking:</p>
<pre><code class="language-js">const ah = require('async_hooks');
ah.createHook({ init() {} }).enable(); // forces PromiseHooks to be enabled.
Promise.resolve(1729).then(() => {
  console.log(`eid ${ah.executionAsyncId()} tid ${ah.triggerAsyncId()}`);
});
// produces:
// eid 7 tid 6
</code></pre>
<p>In this example, adding any actual hook function enabled the tracking of
promises. There are two promises in the example above; the promise created by
<code>Promise.resolve()</code> and the promise returned by the call to <code>then()</code>. In the
example above, the first promise got the <code>asyncId</code> <code>6</code> and the latter got
<code>asyncId</code> <code>7</code>. During the execution of the <code>then()</code> callback, we are executing
in the context of promise with <code>asyncId</code> <code>7</code>. This promise was triggered by
async resource <code>6</code>.</p>
<p>Another subtlety with promises is that <code>before</code> and <code>after</code> callbacks are run
only on chained promises. That means promises not created by <code>then()</code>/<code>catch()</code>
will not have the <code>before</code> and <code>after</code> callbacks fired on them. For more details
see the details of the V8 <a href="https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit">PromiseHooks</a> API.</p>
<h2>JavaScript embedder API<span><a class="mark" href="#async_hooks_javascript_embedder_api" id="async_hooks_javascript_embedder_api">#</a></span></h2>
<p>Library developers that handle their own asynchronous resources performing tasks
like I/O, connection pooling, or managing callback queues may use the
<code>AsyncResource</code> JavaScript API so that all the appropriate callbacks are called.</p>
<h3>Class: <code>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="language-js">const { AsyncResource, executionAsyncId } = require('async_hooks');

// AsyncResource() is meant to be extended. Instantiating a
// new AsyncResource() also triggers init. If triggerAsyncId is omitted then
// async_hook.executionAsyncId() is used.
const asyncResource = new AsyncResource(
  type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }
);

// Run a function in the execution context of the resource. This will
// * establish the context of the resource
// * trigger the AsyncHooks before callbacks
// * call the provided function `fn` with the supplied arguments
// * trigger the AsyncHooks after callbacks
// * restore the original execution context
asyncResource.runInAsyncScope(fn, thisArg, ...args);

// Call AsyncHooks destroy callbacks.
asyncResource.emitDestroy();

// Return the unique ID assigned to the AsyncResource instance.
asyncResource.asyncId();

// Return the trigger ID for the AsyncResource instance.
asyncResource.triggerAsyncId();
</code></pre>
<h4><code>new AsyncResource(type[, options])</code><span><a class="mark" href="#async_hooks_new_asyncresource_type_options" id="async_hooks_new_asyncresource_type_options">#</a></span></h4>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The type of async event.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>triggerAsyncId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;boolean></a> If set to <code>true</code>, disables <code>emitDestroy</code>
when the object is garbage collected. This usually does not need to be set
(even if <code>emitDestroy</code> is called manually), unless the resource's <code>asyncId</code>
is retrieved and the sensitive API's <code>emitDestroy</code> is called with it.
When set to <code>false</code>, the <code>emitDestroy</code> call on garbage collection
will only take place if there is at least one active <code>destroy</code> hook.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Example usage:</p>
<pre><code class="language-js">class DBQuery extends AsyncResource {
  constructor(db) {
    super('DBQuery');
    this.db = db;
  }

  getInfo(query, callback) {
    this.db.get(query, (err, data) => {
      this.runInAsyncScope(callback, null, err, data);
    });
  }

  close() {
    this.db = null;
    this.emitDestroy();
  }
}
</code></pre>
<h4><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">&#x3C;Function></a> The function to call in the execution context of this async
resource.</li>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The receiver to be used for the function call.</li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Optional arguments to pass to the function.</li>
</ul>
<p>Call the provided function with the provided arguments in the execution context
of the async resource. This will establish the context, trigger the AsyncHooks
before callbacks, call the function, trigger the AsyncHooks after callbacks, and
then restore the original execution context.</p>
<h4><code>asyncResource.emitDestroy()</code><span><a class="mark" href="#async_hooks_asyncresource_emitdestroy" id="async_hooks_asyncresource_emitdestroy">#</a></span></h4>
<ul>
<li>Returns: <a href="#async_hooks_class_asyncresource" class="type">&#x3C;AsyncResource></a> A reference to <code>asyncResource</code>.</li>
</ul>
<p>Call all <code>destroy</code> hooks. This should only ever be called once. An error will
be thrown if it is called more than once. This <strong>must</strong> be manually called. If
the resource is left to be collected by the GC then the <code>destroy</code> hooks will
never be called.</p>
<h4><code>asyncResource.asyncId()</code><span><a class="mark" href="#async_hooks_asyncresource_asyncid" id="async_hooks_asyncresource_asyncid">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The unique <code>asyncId</code> assigned to the resource.</li>
</ul>
<h4><code>asyncResource.triggerAsyncId()</code><span><a class="mark" href="#async_hooks_asyncresource_triggerasyncid" id="async_hooks_asyncresource_triggerasyncid">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The same <code>triggerAsyncId</code> that is passed to the
<code>AsyncResource</code> constructor.</li>
</ul>
<p><a id="async-resource-worker-pool"></a></p>
<h3>Using <code>AsyncResource</code> for a <code>Worker</code> thread pool<span><a class="mark" href="#async_hooks_using_asyncresource_for_a_worker_thread_pool" id="async_hooks_using_asyncresource_for_a_worker_thread_pool">#</a></span></h3>
<p>The following example shows how to use the <code>AsyncResource</code> class to properly
provide async tracking for a <a href="#worker_threads_class_worker"><code>Worker</code></a> pool. Other resource pools, such as
database connection pools, can follow a similar model.</p>
<p>Assuming that the task is adding two numbers, using a file named
<code>task_processor.js</code> with the following content:</p>
<pre><code class="language-js">const { parentPort } = require('worker_threads');
parentPort.on('message', (task) => {
  parentPort.postMessage(task.a + task.b);
});
</code></pre>
<p>a Worker pool around it could use the following structure:</p>
<pre><code class="language-js">const { AsyncResource } = require('async_hooks');
const { EventEmitter } = require('events');
const path = require('path');
const { Worker } = require('worker_threads');

const kTaskInfo = Symbol('kTaskInfo');
const kWorkerFreedEvent = Symbol('kWorkerFreedEvent');

class WorkerPoolTaskInfo extends AsyncResource {
  constructor(callback) {
    super('WorkerPoolTaskInfo');
    this.callback = callback;
  }

  done(err, result) {
    this.runInAsyncScope(this.callback, null, err, result);
    this.emitDestroy();  // `TaskInfo`s are used only once.
  }
}

class WorkerPool extends EventEmitter {
  constructor(numThreads) {
    super();
    this.numThreads = numThreads;
    this.workers = [];
    this.freeWorkers = [];

    for (let i = 0; i &#x3C; numThreads; i++)
      this.addNewWorker();
  }

  addNewWorker() {
    const worker = new Worker(path.resolve(__dirname, 'task_processor.js'));
    worker.on('message', (result) => {
      // In case of success: Call the callback that was passed to `runTask`,
      // remove the `TaskInfo` associated with the Worker, and mark it as free
      // again.
      worker[kTaskInfo].done(null, result);
      worker[kTaskInfo] = null;
      this.freeWorkers.push(worker);
      this.emit(kWorkerFreedEvent);
    });
    worker.on('error', (err) => {
      // In case of an uncaught exception: Call the callback that was passed to
      // `runTask` with the error.
      if (worker[kTaskInfo])
        worker[kTaskInfo].done(err, null);
      else
        this.emit('error', err);
      // Remove the worker from the list and start a new Worker to replace the
      // current one.
      this.workers.splice(this.workers.indexOf(worker), 1);
      this.addNewWorker();
    });
    this.workers.push(worker);
    this.freeWorkers.push(worker);
    this.emit(kWorkerFreedEvent);
  }

  runTask(task, callback) {
    if (this.freeWorkers.length === 0) {
      // No free threads, wait until a worker thread becomes free.
      this.once(kWorkerFreedEvent, () => this.runTask(task, callback));
      return;
    }

    const worker = this.freeWorkers.pop();
    worker[kTaskInfo] = new WorkerPoolTaskInfo(callback);
    worker.postMessage(task);
  }

  close() {
    for (const worker of this.workers) worker.terminate();
  }
}

module.exports = WorkerPool;
</code></pre>
<p>Without the explicit tracking added by the <code>WorkerPoolTaskInfo</code> objects,
it would appear that the callbacks are associated with the individual <code>Worker</code>
objects. However, the creation of the <code>Worker</code>s is not associated with the
creation of the tasks and does not provide information about when tasks
were scheduled.</p>
<p>This pool could be used as follows:</p>
<pre><code class="language-js">const WorkerPool = require('./worker_pool.js');
const os = require('os');

const pool = new WorkerPool(os.cpus().length);

let finished = 0;
for (let i = 0; i &#x3C; 10; i++) {
  pool.runTask({ a: 42, b: 100 }, (err, result) => {
    console.log(i, err, result);
    if (++finished === 10)
      pool.close();
  });
}
</code></pre>
<h3>Integrating <code>AsyncResource</code> with <code>EventEmitter</code><span><a class="mark" href="#async_hooks_integrating_asyncresource_with_eventemitter" id="async_hooks_integrating_asyncresource_with_eventemitter">#</a></span></h3>
<p>Event listeners triggered by an <a href="#events_class_eventemitter"><code>EventEmitter</code></a> may be run in a different
execution context than the one that was active when <code>eventEmitter.on()</code> was
called.</p>
<p>The following example shows how to use the <code>AsyncResource</code> class to properly
associate an event listener with the correct execution context. The same
approach can be applied to a <a href="#stream_stream"><code>Stream</code></a> or a similar event-driven class.</p>
<pre><code class="language-js">const { createServer } = require('http');
const { AsyncResource, executionAsyncId } = require('async_hooks');

const server = createServer((req, res) => {
  const asyncResource = new AsyncResource('request');
  // The listener will always run in the execution context of `asyncResource`.
  req.on('close', asyncResource.runInAsyncScope.bind(asyncResource, () => {
    // Prints: true
    console.log(asyncResource.asyncId() === executionAsyncId());
  }));
  res.end();
}).listen(3000);
</code></pre>
<h2>Class: <code>AsyncLocalStorage</code><span><a class="mark" href="#async_hooks_class_asynclocalstorage" id="async_hooks_class_asynclocalstorage">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<p>This class is used to create asynchronous state within callbacks and promise
chains. It allows storing data throughout the lifetime of a web request
or any other asynchronous duration. It is similar to thread-local storage
in other languages.</p>
<p>The following example uses <code>AsyncLocalStorage</code> to build a simple logger
that assigns IDs to incoming HTTP requests and includes them in messages
logged within each request.</p>
<pre><code class="language-js">const http = require('http');
const { AsyncLocalStorage } = require('async_hooks');

const asyncLocalStorage = new AsyncLocalStorage();

function logWithId(msg) {
  const id = asyncLocalStorage.getStore();
  console.log(`${id !== undefined ? id : '-'}:`, msg);
}

let idSeq = 0;
http.createServer((req, res) => {
  asyncLocalStorage.run(idSeq++, () => {
    logWithId('start');
    // Imagine any chain of async operations here
    setImmediate(() => {
      logWithId('finish');
      res.end();
    });
  });
}).listen(8080);

http.get('http://localhost:8080');
http.get('http://localhost:8080');
// Prints:
//   0: start
//   1: start
//   0: finish
//   1: finish
</code></pre>
<p>When having multiple instances of <code>AsyncLocalStorage</code>, they are independent
from each other. It is safe to instantiate this class multiple times.</p>
<h3><code>new AsyncLocalStorage()</code><span><a class="mark" href="#async_hooks_new_asynclocalstorage" id="async_hooks_new_asynclocalstorage">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<p>Creates a new instance of <code>AsyncLocalStorage</code>. Store is only provided within a
<code>run</code> method call.</p>
<h3><code>asyncLocalStorage.disable()</code><span><a class="mark" href="#async_hooks_asynclocalstorage_disable" id="async_hooks_asynclocalstorage_disable">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<p>This method disables the instance of <code>AsyncLocalStorage</code>. All subsequent calls
to <code>asyncLocalStorage.getStore()</code> will return <code>undefined</code> until
<code>asyncLocalStorage.run()</code> is called again.</p>
<p>When calling <code>asyncLocalStorage.disable()</code>, all current contexts linked to the
instance will be exited.</p>
<p>Calling <code>asyncLocalStorage.disable()</code> is required before the
<code>asyncLocalStorage</code> can be garbage collected. This does not apply to stores
provided by the <code>asyncLocalStorage</code>, as those objects are garbage collected
along with the corresponding async resources.</p>
<p>This method is to be used when the <code>asyncLocalStorage</code> is not in use anymore
in the current process.</p>
<h3><code>asyncLocalStorage.getStore()</code><span><a class="mark" href="#async_hooks_asynclocalstorage_getstore" id="async_hooks_asynclocalstorage_getstore">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>This method returns the current store.
If this method is called outside of an asynchronous context initialized by
calling <code>asyncLocalStorage.run</code>, it will return <code>undefined</code>.</p>
<h3><code>asyncLocalStorage.enterWith(store)</code><span><a class="mark" href="#async_hooks_asynclocalstorage_enterwith_store" id="async_hooks_asynclocalstorage_enterwith_store">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li><code>store</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Calling <code>asyncLocalStorage.enterWith(store)</code> will transition into the context
for the remainder of the current synchronous execution and will persist
through any following asynchronous calls.</p>
<p>Example:</p>
<pre><code class="language-js">const store = { id: 1 };
asyncLocalStorage.enterWith(store);
asyncLocalStorage.getStore(); // Returns the store object
someAsyncOperation(() => {
  asyncLocalStorage.getStore(); // Returns the same object
});
</code></pre>
<p>This transition will continue for the <em>entire</em> synchronous execution.
This means that if, for example, the context is entered within an event
handler subsequent event handlers will also run within that context unless
specifically bound to another context with an <code>AsyncResource</code>.</p>
<pre><code class="language-js">const store = { id: 1 };

emitter.on('my-event', () => {
  asyncLocalStorage.enterWith(store);
});
emitter.on('my-event', () => {
  asyncLocalStorage.getStore(); // Returns the same object
});

asyncLocalStorage.getStore(); // Returns undefined
emitter.emit('my-event');
asyncLocalStorage.getStore(); // Returns the same object
</code></pre>
<h3><code>asyncLocalStorage.run(store, callback[, ...args])</code><span><a class="mark" href="#async_hooks_asynclocalstorage_run_store_callback_args" id="async_hooks_asynclocalstorage_run_store_callback_args">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li><code>store</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>This methods runs a function synchronously within a context and return its
return value. The store is not accessible outside of the callback function or
the asynchronous operations created within the callback.</p>
<p>Optionally, arguments can be passed to the function. They will be passed to
the callback function.</p>
<p>If the callback function throws an error, it will be thrown by <code>run</code> too.
The stacktrace will not be impacted by this call and the context will
be exited.</p>
<p>Example:</p>
<pre><code class="language-js">const store = { id: 2 };
try {
  asyncLocalStorage.run(store, () => {
    asyncLocalStorage.getStore(); // Returns the store object
    throw new Error();
  });
} catch (e) {
  asyncLocalStorage.getStore(); // Returns undefined
  // The error will be caught here
}
</code></pre>
<h3><code>asyncLocalStorage.exit(callback[, ...args])</code><span><a class="mark" href="#async_hooks_asynclocalstorage_exit_callback_args" id="async_hooks_asynclocalstorage_exit_callback_args">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.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">&#x3C;Function></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>This methods runs a function synchronously outside of a context and return its
return value. The store is not accessible within the callback function or
the asynchronous operations created within the callback.</p>
<p>Optionally, arguments can be passed to the function. They will be passed to
the callback function.</p>
<p>If the callback function throws an error, it will be thrown by <code>exit</code> too.
The stacktrace will not be impacted by this call and
the context will be re-entered.</p>
<p>Example:</p>
<pre><code class="language-js">// Within a call to run
try {
  asyncLocalStorage.getStore(); // Returns the store object or value
  asyncLocalStorage.exit(() => {
    asyncLocalStorage.getStore(); // Returns undefined
    throw new Error();
  });
} catch (e) {
  asyncLocalStorage.getStore(); // Returns the same object or value
  // The error will be caught here
}
</code></pre>
<h3>Usage with <code>async/await</code><span><a class="mark" href="#async_hooks_usage_with_async_await" id="async_hooks_usage_with_async_await">#</a></span></h3>
<p>If, within an async function, only one <code>await</code> call is to run within a context,
the following pattern should be used:</p>
<pre><code class="language-js">async function fn() {
  await asyncLocalStorage.run(new Map(), () => {
    asyncLocalStorage.getStore().set('key', value);
    return foo(); // The return value of foo will be awaited
  });
}
</code></pre>
<p>In this example, the store is only available in the callback function and the
functions called by <code>foo</code>. Outside of <code>run</code>, calling <code>getStore</code> will return
<code>undefined</code>.</p>
<h3>Troubleshooting<span><a class="mark" href="#async_hooks_troubleshooting" id="async_hooks_troubleshooting">#</a></span></h3>
<p>In most cases your application or library code should have no issues with
<code>AsyncLocalStorage</code>. But in rare cases you may face situations when the
current store is lost in one of asynchronous operations. Then you should
consider the following options.</p>
<p>If your code is callback-based, it is enough to promisify it with
<a href="#util_util_promisify_original"><code>util.promisify()</code></a>, so it starts working with native promises.</p>
<p>If you need to keep using callback-based API, or your code assumes
a custom thenable implementation, you should use <a href="#async_hooks_class_asyncresource"><code>AsyncResource</code></a> class
to associate the asynchronous operation with the correct execution context.</p>
<h1>Buffer<span><a class="mark" href="#buffer_buffer" id="buffer_buffer">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>In Node.js, <code>Buffer</code> objects are used to represent binary data in the form
of a sequence of bytes. Many Node.js APIs, for example streams and file system
operations, support <code>Buffer</code>s, as interactions with the operating system or
other processes generally always happen in terms of binary data.</p>
<p>The <code>Buffer</code> class is a subclass of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> class that is built
into the JavaScript language. A number of additional methods are supported
that cover additional use cases. Node.js APIs accept plain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>s
wherever <code>Buffer</code>s are supported as well.</p>
<p>Instances of <code>Buffer</code>, and instances of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> in general,
are similar to arrays of integers from <code>0</code> to <code>255</code>, but correspond to
fixed-sized blocks of memory and cannot contain any other values.
The size of a <code>Buffer</code> is established when it is created and cannot be changed.</p>
<p>The <code>Buffer</code> class is within the global scope, making it unlikely that one
would need to ever use <code>require('buffer').Buffer</code>.</p>
<pre><code class="language-js">// Creates a zero-filled Buffer of length 10.
const buf1 = Buffer.alloc(10);

// Creates a Buffer of length 10,
// filled with bytes which all have the value `1`.
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 fill(), write(), or other functions that fill the Buffer's
// contents.
const buf3 = Buffer.allocUnsafe(10);

// Creates a Buffer containing the bytes [1, 2, 3].
const buf4 = Buffer.from([1, 2, 3]);

// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries
// are all truncated using `(value &#x26; 255)` to fit into the range 0–255.
const buf5 = Buffer.from([257, 257.5, -255, '1']);

// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':
// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)
// [116, 195, 169, 115, 116] (in decimal notation)
const buf6 = Buffer.from('tést');

// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const buf7 = Buffer.from('tést', 'latin1');
</code></pre>
<h2>Buffers and character encodings<span><a class="mark" href="#buffer_buffers_and_character_encodings" id="buffer_buffers_and_character_encodings">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.4.0</td>
<td><p>Introduced <code>latin1</code> as an alias for <code>binary</code>.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>Removed the deprecated <code>raw</code> and <code>raws</code> encodings.</p></td></tr>
</tbody></table>
</details>
</div>
<p>When converting between <code>Buffer</code>s and strings, a character encoding may be
specified. If no character encoding is specified, UTF-8 will be used as the
default.</p>
<pre><code class="language-js">const buf = Buffer.from('hello world', 'utf8');

console.log(buf.toString('hex'));
// Prints: 68656c6c6f20776f726c64
console.log(buf.toString('base64'));
// Prints: aGVsbG8gd29ybGQ=

console.log(Buffer.from('fhqwhgads', 'utf8'));
// Prints: &#x3C;Buffer 66 68 71 77 68 67 61 64 73>
console.log(Buffer.from('fhqwhgads', 'utf16le'));
// Prints: &#x3C;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 are the following:</p>
<ul>
<li>
<p><code>'utf8'</code>: Multi-byte encoded Unicode characters. Many web pages and other
document formats use <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. This is the default character encoding.
When decoding a <code>Buffer</code> into a string that does not exclusively contain
valid UTF-8 data, the Unicode replacement character <code>U+FFFD</code> � will be used
to represent those errors.</p>
</li>
<li>
<p><code>'utf16le'</code>: Multi-byte encoded Unicode characters. Unlike <code>'utf8'</code>, each
character in the string will be encoded using either 2 or 4 bytes.
Node.js only supports the <a href="https://en.wikipedia.org/wiki/Endianness">little-endian</a> variant of <a href="https://en.wikipedia.org/wiki/UTF-16">UTF-16</a>.</p>
</li>
<li>
<p><code>'latin1'</code>: Latin-1 stands for <a href="https://en.wikipedia.org/wiki/ISO-8859-1">ISO-8859-1</a>. This character encoding only
supports the Unicode characters from <code>U+0000</code> to <code>U+00FF</code>. Each character is
encoded using a single byte. Characters that do not fit into that range are
truncated and will be mapped to characters in that range.</p>
</li>
</ul>
<p>Converting a <code>Buffer</code> into a string using one of the above is referred to as
decoding, and converting a string into a <code>Buffer</code> is referred to as encoding.</p>
<p>Node.js also supports the following two binary-to-text encodings. For
binary-to-text encodings, the naming convention is reversed: Converting a
<code>Buffer</code> into a string is typically referred to as encoding, and converting a
string into a <code>Buffer</code> as decoding.</p>
<ul>
<li>
<p><code>'base64'</code>: <a href="https://en.wikipedia.org/wiki/Base64">Base64</a> 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">RFC 4648, Section 5</a>.</p>
</li>
<li>
<p><code>'hex'</code>: Encode each byte as two hexadecimal characters. Data truncation
may occur when decoding string that do exclusively contain valid hexadecimal
characters. See below for an example.</p>
</li>
</ul>
<p>The following legacy character encodings are also supported:</p>
<ul>
<li>
<p><code>'ascii'</code>: For 7-bit <a href="https://en.wikipedia.org/wiki/ASCII">ASCII</a> data only. When encoding a string into a
<code>Buffer</code>, this is equivalent to using <code>'latin1'</code>. When decoding a <code>Buffer</code>
into a string, using encoding this will additionally unset the highest bit of
each byte before decoding as <code>'latin1'</code>.
Generally, there should be no reason to use this encoding, as <code>'utf8'</code>
(or, if the data is known to always be ASCII-only, <code>'latin1'</code>) will be a
better choice when encoding or decoding ASCII-only text. It is only provided
for legacy compatibility.</p>
</li>
<li>
<p><code>'binary'</code>: Alias for <code>'latin1'</code>. See <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMString/Binary">binary strings</a> for more background
on this topic. The name of this encoding can be very misleading, as all of the
encodings listed here convert between strings and binary data. For converting
between strings and <code>Buffer</code>s, typically <code>'utf-8'</code> is the right choice.</p>
</li>
<li>
<p><code>'ucs2'</code>: Alias of <code>'utf16le'</code>. UCS-2 used to refer to a variant of UTF-16
that did not support characters that had code points larger than U+FFFF.
In Node.js, these code points are always supported.</p>
</li>
</ul>
<pre><code class="language-js">Buffer.from('1ag', 'hex');
// Prints &#x3C;Buffer 1a>, data truncated when first non-hexadecimal value
// ('g') encountered.

Buffer.from('1a7g', 'hex');
// Prints &#x3C;Buffer 1a>, data truncated when data ends in single digit ('7').

Buffer.from('1634', 'hex');
// Prints &#x3C;Buffer 16 34>, all data represented.
</code></pre>
<p>Modern Web browsers follow the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a> which aliases
both <code>'latin1'</code> and <code>'ISO-8859-1'</code> to <code>'win-1252'</code>. This means that while doing
something like <code>http.get()</code>, if the returned charset is one of those listed in
the WHATWG specification it is possible that the server actually returned
<code>'win-1252'</code>-encoded data, and using <code>'latin1'</code> encoding may incorrectly decode
the characters.</p>
<h2>Buffers and TypedArrays<span><a class="mark" href="#buffer_buffers_and_typedarrays" id="buffer_buffers_and_typedarrays">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v3.0.0</td>
<td><p>The <code>Buffer</code>s class now inherits from <code>Uint8Array</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<p><code>Buffer</code> instances are also <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> instances, which is the language’s
built-in class for working with binary data. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> in turn is a
subclass of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>. Therefore, all <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> methods are also
available on <code>Buffer</code>s. However, there are subtle incompatibilities between
the <code>Buffer</code> API and the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> API.</p>
<p>In particular:</p>
<ul>
<li>While <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice"><code>TypedArray#slice()</code></a> creates a copy of part of the <code>TypedArray</code>,
<a href="#buffer_buf_slice_start_end"><code>Buffer#slice()</code></a> creates a view over the existing <code>Buffer</code>
without copying. This behavior can be surprising, and only exists for legacy
compatibility. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray"><code>TypedArray#subarray()</code></a> can be used to achieve the behavior
of <a href="#buffer_buf_slice_start_end"><code>Buffer#slice()</code></a> on both <code>Buffer</code>s and other
<code>TypedArray</code>s.</li>
<li><a href="#buffer_buf_tostring_encoding_start_end"><code>buf.toString()</code></a> is incompatible with its <code>TypedArray</code> equivalent.</li>
<li>A number of methods, e.g. <a href="#buffer_buf_indexof_value_byteoffset_encoding"><code>buf.indexOf()</code></a>, support additional arguments.</li>
</ul>
<p>There are two ways 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>.</p>
<p>When passing a <code>Buffer</code> to a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> constructor, the <code>Buffer</code>’s
elements will be copied, interpreted as an array of integers, and not as a byte
array of the target type. For example,
<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>, rather than 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>
<p>In order to create a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> that shares its memory with the <code>Buffer</code>,
the underlying <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> can be passed to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>
constructor instead:</p>
<pre><code class="language-js">const buf = Buffer.from('hello', 'utf16le');
const uint16arr = new Uint16Array(
  buf.buffer, buf.byteOffset, buf.length / Uint16Array.BYTES_PER_ELEMENT);
</code></pre>
<p>It is also possible to create a new <code>Buffer</code> that shares the same allocated
memory as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instance by using the <code>TypedArray</code> object’s
<code>.buffer</code> property in the same way. <a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length"><code>Buffer.from()</code></a>
behaves like <code>new Uint8Array()</code> in this context.</p>
<pre><code class="language-js">const arr = new Uint16Array(2);

arr[0] = 5000;
arr[1] = 4000;

// Copies the contents of `arr`.
const buf1 = Buffer.from(arr);
// Shares memory with `arr`.
const buf2 = Buffer.from(arr.buffer);

console.log(buf1);
// Prints: &#x3C;Buffer 88 a0>
console.log(buf2);
// Prints: &#x3C;Buffer 88 13 a0 0f>

arr[1] = 6000;

console.log(buf1);
// Prints: &#x3C;Buffer 88 a0>
console.log(buf2);
// Prints: &#x3C;Buffer 88 13 70 17>
</code></pre>
<p>When creating a <code>Buffer</code> using a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>'s <code>.buffer</code>, it is
possible to use only a portion of the underlying <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> by passing in
<code>byteOffset</code> and <code>length</code> parameters.</p>
<pre><code class="language-js">const arr = new Uint16Array(20);
const buf = Buffer.from(arr.buffer, 0, 16);

console.log(buf.length);
// Prints: 16
</code></pre>
<p>The <code>Buffer.from()</code> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from"><code>TypedArray.from()</code></a> have different signatures and
implementations. Specifically, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> variants accept a second
argument that is a mapping function that is invoked on every element of the
typed array:</p>
<ul>
<li><code>TypedArray.from(source[, mapFn[, thisArg]])</code></li>
</ul>
<p>The <code>Buffer.from()</code> method, however, does not support the use of a mapping
function:</p>
<ul>
<li><a href="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a></li>
<li><a href="#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a></li>
<li><a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a></li>
<li><a href="#buffer_class_method_buffer_from_string_encoding"><code>Buffer.from(string[, encoding])</code></a></li>
</ul>
<h2>Buffers and iteration<span><a class="mark" href="#buffer_buffers_and_iteration" id="buffer_buffers_and_iteration">#</a></span></h2>
<p><code>Buffer</code> instances can be iterated over using <code>for..of</code> syntax:</p>
<pre><code class="language-js">const buf = Buffer.from([1, 2, 3]);

for (const b of buf) {
  console.log(b);
}
// Prints:
//   1
//   2
//   3
</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: <code>Buffer</code><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>Class Method: <code>Buffer.alloc(size[, fill[, encoding]])</code><span><a class="mark" href="#buffer_class_method_buffer_alloc_size_fill_encoding" id="buffer_class_method_buffer_alloc_size_fill_encoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Specifying an invalid string for <code>fill</code> triggers a thrown exception.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Specifying an invalid string for <code>fill</code> now results in a zero-filled buffer.</p></td></tr>
<tr><td>v5.10.0</td>
<td><p><span>Added in: v5.10.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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 zero-filled.</p>
<pre><code class="language-js">const buf = Buffer.alloc(5);

console.log(buf);
// Prints: &#x3C;Buffer 00 00 00 00 00>
</code></pre>
<p>If <code>size</code> is larger than
<a href="#buffer_buffer_constants_max_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#ERR_INVALID_OPT_VALUE"><code>ERR_INVALID_OPT_VALUE</code></a>
is thrown.</p>
<p>If <code>fill</code> is specified, the allocated <code>Buffer</code> will be initialized by calling
<a href="#buffer_buf_fill_value_offset_end_encoding"><code>buf.fill(fill)</code></a>.</p>
<pre><code class="language-js">const buf = Buffer.alloc(5, 'a');

console.log(buf);
// Prints: &#x3C;Buffer 61 61 61 61 61>
</code></pre>
<p>If both <code>fill</code> and <code>encoding</code> are specified, the allocated <code>Buffer</code> will be
initialized by calling <a href="#buffer_buf_fill_value_offset_end_encoding"><code>buf.fill(fill, encoding)</code></a>.</p>
<pre><code class="language-js">const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');

console.log(buf);
// Prints: &#x3C;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 measurably 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 never contain sensitive data from previous allocations, including
data that might not have been allocated for <code>Buffer</code>s.</p>
<p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p>
<h3>Class Method: <code>Buffer.allocUnsafe(size)</code><span><a class="mark" href="#buffer_class_method_buffer_allocunsafe_size" id="buffer_class_method_buffer_allocunsafe_size">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>Passing a negative <code>size</code> will now throw an error.</p></td></tr>
<tr><td>v5.10.0</td>
<td><p><span>Added in: v5.10.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The desired length of the new <code>Buffer</code>.</li>
</ul>
<p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If <code>size</code> is larger than
<a href="#buffer_buffer_constants_max_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#ERR_INVALID_OPT_VALUE"><code>ERR_INVALID_OPT_VALUE</code></a>
is thrown.</p>
<p>The underlying memory for <code>Buffer</code> instances created in this way is <em>not
initialized</em>. The contents of the newly created <code>Buffer</code> are unknown and
<em>may contain sensitive data</em>. Use <a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc()</code></a> instead to initialize
<code>Buffer</code> instances with zeroes.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(10);

console.log(buf);
// Prints (contents may vary): &#x3C;Buffer a0 8b 28 3f 01 00 00 00 50 32>

buf.fill(0);

console.log(buf);
// Prints: &#x3C;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>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>,
<a href="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</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: <code>Buffer.allocUnsafeSlow(size)</code><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">&#x3C;integer></a> The desired length of the new <code>Buffer</code>.</li>
</ul>
<p>Allocates a new <code>Buffer</code> of <code>size</code> bytes. If <code>size</code> is larger than
<a href="#buffer_buffer_constants_max_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#ERR_INVALID_OPT_VALUE"><code>ERR_INVALID_OPT_VALUE</code></a>
is thrown. A zero-length <code>Buffer</code> is created if <code>size</code> is 0.</p>
<p>The underlying memory for <code>Buffer</code> instances created in this way is <em>not
initialized</em>. The contents of the newly created <code>Buffer</code> are unknown and
<em>may contain sensitive data</em>. Use <a href="#buffer_buf_fill_value_offset_end_encoding"><code>buf.fill(0)</code></a> to initialize
such <code>Buffer</code> instances with zeroes.</p>
<p>When using <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> to allocate new <code>Buffer</code> instances,
allocations under 4KB are sliced from a single pre-allocated <code>Buffer</code>. This
allows applications to avoid the garbage collection overhead of creating many
individually allocated <code>Buffer</code> instances. This approach improves both
performance and memory usage by eliminating the need to track and clean up as
many individual <code>ArrayBuffer</code> objects.</p>
<p>However, in the case where a developer may need to retain a small chunk of
memory from a pool for an indeterminate amount of time, it may be appropriate
to create an un-pooled <code>Buffer</code> instance using <code>Buffer.allocUnsafeSlow()</code> and
then copying out the relevant bits.</p>
<pre><code class="language-js">// Need to keep around a few small chunks of memory.
const store = [];

socket.on('readable', () => {
  let data;
  while (null !== (data = readable.read())) {
    // Allocate for retained data.
    const sb = Buffer.allocUnsafeSlow(10);

    // Copy the data into the new allocation.
    data.copy(sb, 0, 0, 10);

    store.push(sb);
  }
});
</code></pre>
<p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p>
<h3>Class Method: <code>Buffer.byteLength(string[, encoding])</code><span><a class="mark" href="#buffer_class_method_buffer_bytelength_string_encoding" id="buffer_class_method_buffer_bytelength_string_encoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>Passing invalid input will now throw an error.</p></td></tr>
<tr><td>v5.10.0</td>
<td><p>The <code>string</code> parameter can now be any <code>TypedArray</code>, <code>DataView</code> or <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type">&#x3C;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">&#x3C;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">&#x3C;integer></a> The number of bytes contained within <code>string</code>.</li>
</ul>
<p>Returns the byte length of a string when encoded using <code>encoding</code>.
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>, which does not account
for the encoding that is used to convert the string into bytes.</p>
<p>For <code>'base64'</code> and <code>'hex'</code>, this function assumes valid input. For strings that
contain non-base64/hex-encoded data (e.g. whitespace), the return value might be
greater than the length of a <code>Buffer</code> created from the string.</p>
<pre><code class="language-js">const str = '\u00bd + \u00bc = \u00be';

console.log(`${str}: ${str.length} characters, ` +
            `${Buffer.byteLength(str, 'utf8')} bytes`);
// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes
</code></pre>
<p>When <code>string</code> is a <code>Buffer</code>/<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><code>DataView</code></a>/<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>/<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>/
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a>, the byte length as reported by <code>.byteLength</code>
is returned.</p>
<h3>Class Method: <code>Buffer.compare(buf1, buf2)</code><span><a class="mark" href="#buffer_class_method_buffer_compare_buf1_buf2" id="buffer_class_method_buffer_compare_buf1_buf2">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The arguments can now be <code>Uint8Array</code>s.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buf1</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
<li><code>buf2</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Either <code>-1</code>, <code>0</code>, or <code>1</code>, depending on the result of the
comparison. See <a href="#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend"><code>buf.compare()</code></a> for details.</li>
</ul>
<p>Compares <code>buf1</code> to <code>buf2</code>, typically for the purpose of sorting arrays of
<code>Buffer</code> instances. This is equivalent to calling
<a href="#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend"><code>buf1.compare(buf2)</code></a>.</p>
<pre><code class="language-js">const buf1 = Buffer.from('1234');
const buf2 = Buffer.from('0123');
const arr = [buf1, buf2];

console.log(arr.sort(Buffer.compare));
// Prints: [ &#x3C;Buffer 30 31 32 33>, &#x3C;Buffer 31 32 33 34> ]
// (This result is equal to: [buf2, buf1].)
</code></pre>
<h3>Class Method: <code>Buffer.concat(list[, totalLength])</code><span><a class="mark" href="#buffer_class_method_buffer_concat_list_totallength" id="buffer_class_method_buffer_concat_list_totallength">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The elements of <code>list</code> can now be <code>Uint8Array</code>s.</p></td></tr>
<tr><td>v0.7.11</td>
<td><p><span>Added in: v0.7.11</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>list</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array[]></a> List of <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>
instances to concatenate.</li>
<li><code>totalLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Total length of the <code>Buffer</code> instances in <code>list</code>
when concatenated.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;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> by adding their lengths.</p>
<p>If <code>totalLength</code> is provided, it is coerced to an unsigned integer. If the
combined length of the <code>Buffer</code>s in <code>list</code> exceeds <code>totalLength</code>, the result is
truncated to <code>totalLength</code>.</p>
<pre><code class="language-js">// Create a single `Buffer` from a list of three `Buffer` instances.

const buf1 = Buffer.alloc(10);
const buf2 = Buffer.alloc(14);
const buf3 = Buffer.alloc(18);
const totalLength = buf1.length + buf2.length + buf3.length;

console.log(totalLength);
// Prints: 42

const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);

console.log(bufA);
// Prints: &#x3C;Buffer 00 00 00 00 ...>
console.log(bufA.length);
// Prints: 42
</code></pre>
<h3>Class Method: <code>Buffer.from(array)</code><span><a class="mark" href="#buffer_class_method_buffer_from_array" id="buffer_class_method_buffer_from_array">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li><code>array</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer[]></a></li>
</ul>
<p>Allocates a new <code>Buffer</code> using an <code>array</code> of bytes in the range <code>0</code> – <code>255</code>.
Array entries outside that range will be truncated to fit into it.</p>
<pre><code class="language-js">// Creates a new Buffer containing the 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> or another type
appropriate for <code>Buffer.from()</code> variants.</p>
<p><code>Buffer.from(array)</code> and <a href="#buffer_class_method_buffer_from_string_encoding"><code>Buffer.from(string)</code></a> may also use the internal
<code>Buffer</code> pool like <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> does.</p>
<h3>Class Method: <code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code><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">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type">&#x3C;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>, for example 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">&#x3C;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">&#x3C;integer></a> Number of bytes to expose.
<strong>Default:</strong> <code>arrayBuffer.byteLength - byteOffset</code>.</li>
</ul>
<p>This creates a view of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> without copying the underlying
memory. For example, when passed a reference to the <code>.buffer</code> property of a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instance, the newly created <code>Buffer</code> will share the same
allocated memory as the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>.</p>
<pre><code class="language-js">const arr = new Uint16Array(2);

arr[0] = 5000;
arr[1] = 4000;

// Shares memory with `arr`.
const buf = Buffer.from(arr.buffer);

console.log(buf);
// Prints: &#x3C;Buffer 88 13 a0 0f>

// Changing the original Uint16Array changes the Buffer also.
arr[1] = 6000;

console.log(buf);
// Prints: &#x3C;Buffer 88 13 70 17>
</code></pre>
<p>The optional <code>byteOffset</code> and <code>length</code> arguments specify a memory range within
the <code>arrayBuffer</code> that will be shared by the <code>Buffer</code>.</p>
<pre><code class="language-js">const ab = new ArrayBuffer(10);
const buf = Buffer.from(ab, 0, 2);

console.log(buf.length);
// Prints: 2
</code></pre>
<p>A <code>TypeError</code> will be thrown if <code>arrayBuffer</code> is not an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> or another type appropriate for <code>Buffer.from()</code>
variants.</p>
<h3>Class Method: <code>Buffer.from(buffer)</code><span><a class="mark" href="#buffer_class_method_buffer_from_buffer" id="buffer_class_method_buffer_from_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> An existing <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> from
which to copy data.</li>
</ul>
<p>Copies the passed <code>buffer</code> data onto a new <code>Buffer</code> instance.</p>
<pre><code class="language-js">const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);

buf1[0] = 0x61;

console.log(buf1.toString());
// Prints: auffer
console.log(buf2.toString());
// Prints: buffer
</code></pre>
<p>A <code>TypeError</code> will be thrown if <code>buffer</code> is not a <code>Buffer</code> or another type
appropriate for <code>Buffer.from()</code> variants.</p>
<h3>Class Method: <code>Buffer.from(object[, offsetOrEncoding[, length]])</code><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">&#x3C;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">&#x3C;integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> A byte-offset or encoding.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> A length.</li>
</ul>
<p>For objects whose <code>valueOf()</code> function returns a value not strictly equal to
<code>object</code>, returns <code>Buffer.from(object.valueOf(), offsetOrEncoding, length)</code>.</p>
<pre><code class="language-js">const buf = Buffer.from(new String('this is a test'));
// Prints: &#x3C;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]('string'), offsetOrEncoding)</code>.</p>
<pre><code class="language-js">class Foo {
  [Symbol.toPrimitive]() {
    return 'this is a test';
  }
}

const buf = Buffer.from(new Foo(), 'utf8');
// Prints: &#x3C;Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74>
</code></pre>
<p>A <code>TypeError</code> will be thrown if <code>object</code> does not have the mentioned methods or
is not of another type appropriate for <code>Buffer.from()</code> variants.</p>
<h3>Class Method: <code>Buffer.from(string[, encoding])</code><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">&#x3C;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">&#x3C;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 to be used when converting <code>string</code> into bytes.</p>
<pre><code class="language-js">const buf1 = Buffer.from('this is a tést');
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');

console.log(buf1.toString());
// Prints: this is a tést
console.log(buf2.toString());
// Prints: this is a tést
console.log(buf1.toString('latin1'));
// Prints: this is a tést
</code></pre>
<p>A <code>TypeError</code> will be thrown if <code>string</code> is not a string or another type
appropriate for <code>Buffer.from()</code> variants.</p>
<h3>Class Method: <code>Buffer.isBuffer(obj)</code><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">&#x3C;Object></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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: <code>Buffer.isEncoding(encoding)</code><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">&#x3C;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">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if <code>encoding</code> is the name of a supported character encoding,
or <code>false</code> otherwise.</p>
<pre><code class="language-js">console.log(Buffer.isEncoding('utf-8'));
// Prints: true

console.log(Buffer.isEncoding('hex'));
// Prints: true

console.log(Buffer.isEncoding('utf/8'));
// Prints: false

console.log(Buffer.isEncoding(''));
// Prints: false
</code></pre>
<h3>Class Property: <code>Buffer.poolSize</code><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">&#x3C;integer></a> <strong>Default:</strong> <code>8192</code></li>
</ul>
<p>This is the size (in bytes) of pre-allocated internal <code>Buffer</code> instances used
for pooling. This value may be modified.</p>
<h3><code>buf[index]</code><span><a class="mark" href="#buffer_buf_index" id="buffer_buf_index">#</a></span></h3>
<div class="api_metadata">

</div>
<ul>
<li><code>index</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<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>. In other words, <code>buf[index]</code> returns
<code>undefined</code> when <code>index</code> is negative or <code>>= buf.length</code>, and
<code>buf[index] = value</code> does not modify the buffer if <code>index</code> is negative or
<code>>= buf.length</code>.</p>
<pre><code class="language-js">// Copy an ASCII string into a `Buffer` one byte at a time.
// (This only works for ASCII-only strings. In general, one should use
// `Buffer.from()` to perform this conversion.)

const str = 'Node.js';
const buf = Buffer.allocUnsafe(str.length);

for (let i = 0; i &#x3C; str.length; i++) {
  buf[i] = str.charCodeAt(i);
}

console.log(buf.toString('utf8'));
// Prints: Node.js
</code></pre>
<h3><code>buf.buffer</code><span><a class="mark" href="#buffer_buf_buffer" id="buffer_buf_buffer">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> The underlying <code>ArrayBuffer</code> object based on
which this <code>Buffer</code> object is created.</li>
</ul>
<p>This <code>ArrayBuffer</code> is not guaranteed to correspond exactly to the original
<code>Buffer</code>. See the notes on <code>buf.byteOffset</code> for details.</p>
<pre><code class="language-js">const arrayBuffer = new ArrayBuffer(16);
const buffer = Buffer.from(arrayBuffer);

console.log(buffer.buffer === arrayBuffer);
// Prints: true
</code></pre>
<h3><code>buf.byteOffset</code><span><a class="mark" href="#buffer_buf_byteoffset" id="buffer_buf_byteoffset">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The <code>byteOffset</code> on the underlying <code>ArrayBuffer</code> object based on
which this <code>Buffer</code> object is created.</li>
</ul>
<p>When setting <code>byteOffset</code> in <code>Buffer.from(ArrayBuffer, byteOffset, length)</code>,
or sometimes when allocating a buffer smaller than <code>Buffer.poolSize</code>, the
buffer doesn't start from a zero offset on the underlying <code>ArrayBuffer</code>.</p>
<p>This can cause problems when accessing the underlying <code>ArrayBuffer</code> directly
using <code>buf.buffer</code>, as other parts of the <code>ArrayBuffer</code> may be unrelated
to the <code>buf</code> object itself.</p>
<p>A common issue when creating a <code>TypedArray</code> object that shares its memory with
a <code>Buffer</code> is that in this case one needs to specify the <code>byteOffset</code> correctly:</p>
<pre><code class="language-js">// Create a buffer smaller than `Buffer.poolSize`.
const nodeBuffer = new Buffer.from([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

// When casting the Node.js Buffer to an Int8Array, use the byteOffset
// to refer only to the part of `nodeBuffer.buffer` that contains the memory
// for `nodeBuffer`.
new Int8Array(nodeBuffer.buffer, nodeBuffer.byteOffset, nodeBuffer.length);
</code></pre>
<h3><code>buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])</code><span><a class="mark" href="#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend" id="buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>target</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v5.11.0</td>
<td><p>Additional parameters for specifying offsets are supported now.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>target</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> A <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> with which to
compare <code>buf</code>.</li>
<li><code>targetStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> The offset within <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">&#x3C;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">&#x3C;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">&#x3C;integer></a></li>
</ul>
<p>Compares <code>buf</code> with <code>target</code> and returns a number indicating whether <code>buf</code>
comes before, after, or is the same as <code>target</code> in sort order.
Comparison is based on the actual sequence of bytes in each <code>Buffer</code>.</p>
<ul>
<li><code>0</code> is returned if <code>target</code> is the same as <code>buf</code></li>
<li><code>1</code> is returned if <code>target</code> should come <em>before</em> <code>buf</code> when sorted.</li>
<li><code>-1</code> is returned if <code>target</code> should come <em>after</em> <code>buf</code> when sorted.</li>
</ul>
<pre><code class="language-js">const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('BCD');
const buf3 = Buffer.from('ABCD');

console.log(buf1.compare(buf1));
// Prints: 0
console.log(buf1.compare(buf2));
// Prints: -1
console.log(buf1.compare(buf3));
// Prints: -1
console.log(buf2.compare(buf1));
// Prints: 1
console.log(buf2.compare(buf3));
// Prints: 1
console.log([buf1, buf2, buf3].sort(Buffer.compare));
// Prints: [ &#x3C;Buffer 41 42 43>, &#x3C;Buffer 41 42 43 44>, &#x3C;Buffer 42 43 44> ]
// (This result is equal to: [buf1, buf3, buf2].)
</code></pre>
<p>The optional <code>targetStart</code>, <code>targetEnd</code>, <code>sourceStart</code>, and <code>sourceEnd</code>
arguments can be used to limit the comparison to specific ranges within <code>target</code>
and <code>buf</code> respectively.</p>
<pre><code class="language-js">const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);

console.log(buf1.compare(buf2, 5, 9, 0, 4));
// Prints: 0
console.log(buf1.compare(buf2, 0, 6, 4));
// Prints: -1
console.log(buf1.compare(buf2, 5, 6, 5));
// Prints: 1
</code></pre>
<p><a href="#ERR_OUT_OF_RANGE"><code>ERR_OUT_OF_RANGE</code></a> is thrown if <code>targetStart &#x3C; 0</code>, <code>sourceStart &#x3C; 0</code>,
<code>targetEnd > target.byteLength</code>, or <code>sourceEnd > source.byteLength</code>.</p>
<h3><code>buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])</code><span><a class="mark" href="#buffer_buf_copy_target_targetstart_sourcestart_sourceend" id="buffer_buf_copy_target_targetstart_sourcestart_sourceend">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>target</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;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">&#x3C;integer></a> The offset within <code>target</code> at which to begin
writing. <strong>Default:</strong> <code>0</code>.</li>
<li><code>sourceStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The offset within <code>buf</code> from which to begin copying.
<strong>Default:</strong> <code>0</code>.</li>
<li><code>sourceEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set"><code>TypedArray#set()</code></a> performs the same operation, and is available for all
TypedArrays, including Node.js <code>Buffer</code>s, although it takes different
function arguments.</p>
<pre><code class="language-js">// Create two `Buffer` instances.
const buf1 = Buffer.allocUnsafe(26);
const buf2 = Buffer.allocUnsafe(26).fill('!');

for (let i = 0; i &#x3C; 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);
// This is equivalent to:
// buf2.set(buf1.subarray(16, 20), 8);

console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
</code></pre>
<pre><code class="language-js">// Create a `Buffer` and copy data from one region to an overlapping region
// within the same `Buffer`.

const buf = Buffer.allocUnsafe(26);

for (let i = 0; i &#x3C; 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><code>buf.entries()</code><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">&#x3C;Iterator></a></li>
</ul>
<p>Creates and returns an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterator</a> of <code>[index, byte]</code> pairs from the contents
of <code>buf</code>.</p>
<pre><code class="language-js">// Log the entire contents of a `Buffer`.

const buf = Buffer.from('buffer');

for (const pair of buf.entries()) {
  console.log(pair);
}
// Prints:
//   [0, 98]
//   [1, 117]
//   [2, 102]
//   [3, 102]
//   [4, 101]
//   [5, 114]
</code></pre>
<h3><code>buf.equals(otherBuffer)</code><span><a class="mark" href="#buffer_buf_equals_otherbuffer" id="buffer_buf_equals_otherbuffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The arguments can now be <code>Uint8Array</code>s.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>otherBuffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> A <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> with which to
compare <code>buf</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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. Equivalent to
<a href="#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend"><code>buf.compare(otherBuffer) === 0</code></a>.</p>
<pre><code class="language-js">const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('414243', 'hex');
const buf3 = Buffer.from('ABCD');

console.log(buf1.equals(buf2));
// Prints: true
console.log(buf1.equals(buf3));
// Prints: false
</code></pre>
<h3><code>buf.fill(value[, offset[, end]][, encoding])</code><span><a class="mark" href="#buffer_buf_fill_value_offset_end_encoding" id="buffer_buf_fill_value_offset_end_encoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Throws <code>ERR_OUT_OF_RANGE</code> instead of <code>ERR_INDEX_OUT_OF_RANGE</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Negative <code>end</code> values throw an <code>ERR_INDEX_OUT_OF_RANGE</code> error.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Attempting to fill a non-zero length buffer with a zero length buffer triggers a thrown exception.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Specifying an invalid string for <code>value</code> triggers a thrown exception.</p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>encoding</code> parameter is supported now.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The value with which to fill <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;string></a> The encoding for <code>value</code> if <code>value</code> is a string.
<strong>Default:</strong> <code>'utf8'</code>.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A reference to <code>buf</code>.</li>
</ul>
<p>Fills <code>buf</code> with the specified <code>value</code>. If the <code>offset</code> and <code>end</code> are not given,
the entire <code>buf</code> will be filled:</p>
<pre><code class="language-js">// Fill a `Buffer` with the ASCII character 'h'.

const b = Buffer.allocUnsafe(50).fill('h');

console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
</code></pre>
<p><code>value</code> is coerced to a <code>uint32</code> value if it is not a string, <code>Buffer</code>, or
integer. If the resulting integer is greater than <code>255</code> (decimal), <code>buf</code> will be
filled with <code>value &#x26; 255</code>.</p>
<p>If the final write of a <code>fill()</code> operation falls on a multi-byte character,
then only the bytes of that character that fit into <code>buf</code> are written:</p>
<pre><code class="language-js">// Fill a `Buffer` with character that takes up two bytes in UTF-8.

console.log(Buffer.allocUnsafe(5).fill('\u0222'));
// Prints: &#x3C;Buffer c8 a2 c8 a2 c8>
</code></pre>
<p>If <code>value</code> contains invalid characters, it is truncated; if no valid
fill data remains, an exception is thrown:</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(5);

console.log(buf.fill('a'));
// Prints: &#x3C;Buffer 61 61 61 61 61>
console.log(buf.fill('aazz', 'hex'));
// Prints: &#x3C;Buffer aa aa aa aa aa>
console.log(buf.fill('zz', 'hex'));
// Throws an exception.
</code></pre>
<h3><code>buf.includes(value[, byteOffset][, encoding])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Where to begin searching in <code>buf</code>. If negative, then
offset is calculated from the end of <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">&#x3C;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">&#x3C;boolean></a> <code>true</code> if <code>value</code> was found in <code>buf</code>, <code>false</code> otherwise.</li>
</ul>
<p>Equivalent to <a href="#buffer_buf_indexof_value_byteoffset_encoding"><code>buf.indexOf() !== -1</code></a>.</p>
<pre><code class="language-js">const buf = Buffer.from('this is a buffer');

console.log(buf.includes('this'));
// Prints: true
console.log(buf.includes('is'));
// Prints: true
console.log(buf.includes(Buffer.from('a buffer')));
// Prints: true
console.log(buf.includes(97));
// Prints: true (97 is the decimal ASCII value for 'a')
console.log(buf.includes(Buffer.from('a buffer example')));
// Prints: false
console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));
// Prints: true
console.log(buf.includes('this', 4));
// Prints: false
</code></pre>
<h3><code>buf.indexOf(value[, byteOffset][, encoding])</code><span><a class="mark" href="#buffer_buf_indexof_value_byteoffset_encoding" id="buffer_buf_indexof_value_byteoffset_encoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>value</code> can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v5.7.0, v4.4.0</td>
<td><p>When <code>encoding</code> is being passed, the <code>byteOffset</code> parameter is no longer required.</p></td></tr>
<tr><td>v1.5.0</td>
<td><p><span>Added in: v1.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Where to begin searching in <code>buf</code>. If negative, then
offset is calculated from the end of <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">&#x3C;string></a> If <code>value</code> is a string, this is the encoding used to
determine the binary representation of the string that will be searched for in
<code>buf</code>. <strong>Default:</strong> <code>'utf8'</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The index of the first occurrence of <code>value</code> in <code>buf</code>, or
<code>-1</code> if <code>buf</code> does not contain <code>value</code>.</li>
</ul>
<p>If <code>value</code> is:</p>
<ul>
<li>a string, <code>value</code> is interpreted according to the character encoding in
<code>encoding</code>.</li>
<li>a <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>, <code>value</code> will be used in its entirety.
To compare a partial <code>Buffer</code>, use <a href="#buffer_buf_slice_start_end"><code>buf.slice()</code></a>.</li>
<li>a number, <code>value</code> will be interpreted as an unsigned 8-bit integer
value between <code>0</code> and <code>255</code>.</li>
</ul>
<pre><code class="language-js">const buf = Buffer.from('this is a buffer');

console.log(buf.indexOf('this'));
// Prints: 0
console.log(buf.indexOf('is'));
// Prints: 2
console.log(buf.indexOf(Buffer.from('a buffer')));
// Prints: 8
console.log(buf.indexOf(97));
// Prints: 8 (97 is the decimal ASCII value for 'a')
console.log(buf.indexOf(Buffer.from('a buffer example')));
// Prints: -1
console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));
// Prints: 8

const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');

console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le'));
// Prints: 4
console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le'));
// Prints: 6
</code></pre>
<p>If <code>value</code> is not a string, number, or <code>Buffer</code>, this method will throw a
<code>TypeError</code>. If <code>value</code> is a number, it will be coerced to a valid byte value,
an integer between 0 and 255.</p>
<p>If <code>byteOffset</code> is not a number, it will be coerced to a number. If the result
of coercion is <code>NaN</code> or <code>0</code>, then the entire buffer will be searched. This
behavior matches <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf"><code>String#indexOf()</code></a>.</p>
<pre><code class="language-js">const b = Buffer.from('abcdef');

// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.indexOf(99.9));
console.log(b.indexOf(256 + 99));

// Passing a byteOffset that coerces to NaN or 0.
// Prints: 1, searching the whole buffer.
console.log(b.indexOf('b', undefined));
console.log(b.indexOf('b', {}));
console.log(b.indexOf('b', null));
console.log(b.indexOf('b', []));
</code></pre>
<p>If <code>value</code> is an empty string or empty <code>Buffer</code> and <code>byteOffset</code> is less
than <code>buf.length</code>, <code>byteOffset</code> will be returned. If <code>value</code> is empty and
<code>byteOffset</code> is at least <code>buf.length</code>, <code>buf.length</code> will be returned.</p>
<h3><code>buf.keys()</code><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">&#x3C;Iterator></a></li>
</ul>
<p>Creates and returns an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterator</a> of <code>buf</code> keys (indices).</p>
<pre><code class="language-js">const buf = Buffer.from('buffer');

for (const key of buf.keys()) {
  console.log(key);
}
// Prints:
//   0
//   1
//   2
//   3
//   4
//   5
</code></pre>
<h3><code>buf.lastIndexOf(value[, byteOffset][, encoding])</code><span><a class="mark" href="#buffer_buf_lastindexof_value_byteoffset_encoding" id="buffer_buf_lastindexof_value_byteoffset_encoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>value</code> can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Added in: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Where to begin searching in <code>buf</code>. If negative, then
offset is calculated from the end of <code>buf</code>. <strong>Default:</strong>
<code>buf.length - 1</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If <code>value</code> is a string, this is the encoding used to
determine the binary representation of the string that will be searched for in
<code>buf</code>. <strong>Default:</strong> <code>'utf8'</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The index of the last occurrence of <code>value</code> in <code>buf</code>, or
<code>-1</code> if <code>buf</code> does not contain <code>value</code>.</li>
</ul>
<p>Identical to <a href="#buffer_buf_indexof_value_byteoffset_encoding"><code>buf.indexOf()</code></a>, except the last occurrence of <code>value</code> is found
rather than the first occurrence.</p>
<pre><code class="language-js">const buf = Buffer.from('this buffer is a buffer');

console.log(buf.lastIndexOf('this'));
// Prints: 0
console.log(buf.lastIndexOf('buffer'));
// Prints: 17
console.log(buf.lastIndexOf(Buffer.from('buffer')));
// Prints: 17
console.log(buf.lastIndexOf(97));
// Prints: 15 (97 is the decimal ASCII value for 'a')
console.log(buf.lastIndexOf(Buffer.from('yolo')));
// Prints: -1
console.log(buf.lastIndexOf('buffer', 5));
// Prints: 5
console.log(buf.lastIndexOf('buffer', 4));
// Prints: -1

const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le');

console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le'));
// Prints: 6
console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le'));
// Prints: 4
</code></pre>
<p>If <code>value</code> is not a string, number, or <code>Buffer</code>, this method will throw a
<code>TypeError</code>. If <code>value</code> is a number, it will be coerced to a valid byte value,
an integer between 0 and 255.</p>
<p>If <code>byteOffset</code> is not a number, it will be coerced to a number. Any arguments
that coerce to <code>NaN</code>, like <code>{}</code> or <code>undefined</code>, will search the whole buffer.
This behavior matches <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf"><code>String#lastIndexOf()</code></a>.</p>
<pre><code class="language-js">const b = Buffer.from('abcdef');

// Passing a value that's a number, but not a valid byte.
// Prints: 2, equivalent to searching for 99 or 'c'.
console.log(b.lastIndexOf(99.9));
console.log(b.lastIndexOf(256 + 99));

// Passing a byteOffset that coerces to NaN.
// Prints: 1, searching the whole buffer.
console.log(b.lastIndexOf('b', undefined));
console.log(b.lastIndexOf('b', {}));

// Passing a byteOffset that coerces to 0.
// Prints: -1, equivalent to passing 0.
console.log(b.lastIndexOf('b', null));
console.log(b.lastIndexOf('b', []));
</code></pre>
<p>If <code>value</code> is an empty string or empty <code>Buffer</code>, <code>byteOffset</code> will be returned.</p>
<h3><code>buf.length</code><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">&#x3C;integer></a></li>
</ul>
<p>Returns the number of bytes in <code>buf</code>.</p>
<pre><code class="language-js">// Create a `Buffer` and write a shorter string to it using UTF-8.

const buf = Buffer.alloc(1234);

console.log(buf.length);
// Prints: 1234

buf.write('some string', 0, 'utf8');

console.log(buf.length);
// Prints: 1234
</code></pre>
<h3><code>buf.parent</code><span><a class="mark" href="#buffer_buf_parent" id="buffer_buf_parent">#</a></span></h3>
<div class="api_metadata">
<span>Deprecated since: v8.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_buf_buffer"><code>buf.buffer</code></a> instead.</div><p></p>
<p>The <code>buf.parent</code> property is a deprecated alias for <code>buf.buffer</code>.</p>
<h3><code>buf.readBigInt64BE([offset])</code><span><a class="mark" href="#buffer_buf_readbigint64be_offset" id="buffer_buf_readbigint64be_offset">#</a></span></h3>
<h3><code>buf.readBigInt64LE([offset])</code><span><a class="mark" href="#buffer_buf_readbigint64le_offset" id="buffer_buf_readbigint64le_offset">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.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">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy: <code>0 &#x3C;= offset &#x3C;= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>Reads a signed 64-bit integer from <code>buf</code> at the specified <code>offset</code> with
the specified <a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>readBigInt64BE()</code> reads as big endian,
<code>readBigInt64LE()</code> reads as little endian).</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<h3><code>buf.readBigUInt64BE([offset])</code><span><a class="mark" href="#buffer_buf_readbiguint64be_offset" id="buffer_buf_readbiguint64be_offset">#</a></span></h3>
<h3><code>buf.readBigUInt64LE([offset])</code><span><a class="mark" href="#buffer_buf_readbiguint64le_offset" id="buffer_buf_readbiguint64le_offset">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.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">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy: <code>0 &#x3C;= offset &#x3C;= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>Reads an unsigned 64-bit integer from <code>buf</code> at the specified <code>offset</code> with
the specified <a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>readBigUInt64BE()</code> reads as big endian,
<code>readBigUInt64LE()</code> reads as little endian).</p>
<pre><code class="language-js">const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]);

console.log(buf.readBigUInt64BE(0));
// Prints: 4294967295n

console.log(buf.readBigUInt64LE(0));
// Prints: 18446744069414584320n
</code></pre>
<h3><code>buf.readDoubleBE([offset])</code><span><a class="mark" href="#buffer_buf_readdoublebe_offset" id="buffer_buf_readdoublebe_offset">#</a></span></h3>
<h3><code>buf.readDoubleLE([offset])</code><span><a class="mark" href="#buffer_buf_readdoublele_offset" id="buffer_buf_readdoublele_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Reads a 64-bit double from <code>buf</code> at the specified <code>offset</code> with the specified
<a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>readDoubleBE()</code> reads as big endian, <code>readDoubleLE()</code> reads as
little endian).</p>
<pre><code class="language-js">const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);

console.log(buf.readDoubleBE(0));
// Prints: 8.20788039913184e-304
console.log(buf.readDoubleLE(0));
// Prints: 5.447603722011605e-270
console.log(buf.readDoubleLE(1));
// Throws ERR_OUT_OF_RANGE.
</code></pre>
<h3><code>buf.readFloatBE([offset])</code><span><a class="mark" href="#buffer_buf_readfloatbe_offset" id="buffer_buf_readfloatbe_offset">#</a></span></h3>
<h3><code>buf.readFloatLE([offset])</code><span><a class="mark" href="#buffer_buf_readfloatle_offset" id="buffer_buf_readfloatle_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Reads a 32-bit float from <code>buf</code> at the specified <code>offset</code> with the specified
<a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>readFloatBE()</code> reads as big endian, <code>readFloatLE()</code> reads as
little endian).</p>
<pre><code class="language-js">const buf = Buffer.from([1, 2, 3, 4]);

console.log(buf.readFloatBE(0));
// Prints: 2.387939260590663e-38
console.log(buf.readFloatLE(0));
// Prints: 1.539989614439558e-36
console.log(buf.readFloatLE(1));
// Throws ERR_OUT_OF_RANGE.
</code></pre>
<h3><code>buf.readInt8([offset])</code><span><a class="mark" href="#buffer_buf_readint8_offset" id="buffer_buf_readint8_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 1</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Reads a signed 8-bit integer from <code>buf</code> at the specified <code>offset</code>.</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<pre><code class="language-js">const buf = Buffer.from([-1, 5]);

console.log(buf.readInt8(0));
// Prints: -1
console.log(buf.readInt8(1));
// Prints: 5
console.log(buf.readInt8(2));
// Throws ERR_OUT_OF_RANGE.
</code></pre>
<h3><code>buf.readInt16BE([offset])</code><span><a class="mark" href="#buffer_buf_readint16be_offset" id="buffer_buf_readint16be_offset">#</a></span></h3>
<h3><code>buf.readInt16LE([offset])</code><span><a class="mark" href="#buffer_buf_readint16le_offset" id="buffer_buf_readint16le_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Reads a signed 16-bit integer from <code>buf</code> at the specified <code>offset</code> with
the specified <a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>readInt16BE()</code> reads as big endian,
<code>readInt16LE()</code> reads as little endian).</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<pre><code class="language-js">const buf = Buffer.from([0, 5]);

console.log(buf.readInt16BE(0));
// Prints: 5
console.log(buf.readInt16LE(0));
// Prints: 1280
console.log(buf.readInt16LE(1));
// Throws ERR_OUT_OF_RANGE.
</code></pre>
<h3><code>buf.readInt32BE([offset])</code><span><a class="mark" href="#buffer_buf_readint32be_offset" id="buffer_buf_readint32be_offset">#</a></span></h3>
<h3><code>buf.readInt32LE([offset])</code><span><a class="mark" href="#buffer_buf_readint32le_offset" id="buffer_buf_readint32le_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Reads a signed 32-bit integer from <code>buf</code> at the specified <code>offset</code> with
the specified <a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>readInt32BE()</code> reads as big endian,
<code>readInt32LE()</code> reads as little endian).</p>
<p>Integers read from a <code>Buffer</code> are interpreted as two's complement signed values.</p>
<pre><code class="language-js">const buf = Buffer.from([0, 0, 0, 5]);

console.log(buf.readInt32BE(0));
// Prints: 5
console.log(buf.readInt32LE(0));
// Prints: 83886080
console.log(buf.readInt32LE(1));
// Throws ERR_OUT_OF_RANGE.
</code></pre>
<h3><code>buf.readIntBE(offset, byteLength)</code><span><a class="mark" href="#buffer_buf_readintbe_offset_bytelength" id="buffer_buf_readintbe_offset_bytelength">#</a></span></h3>
<h3><code>buf.readIntLE(offset, byteLength)</code><span><a class="mark" href="#buffer_buf_readintle_offset_bytelength" id="buffer_buf_readintle_offset_bytelength">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 &#x3C;= offset &#x3C;= 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">&#x3C;integer></a> Number of bytes to read. Must satisfy
<code>0 &#x3C; byteLength &#x3C;= 6</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Reads <code>byteLength</code> number of bytes from <code>buf</code> at the specified <code>offset</code>
and interprets the result as a two's complement signed value. Supports up to 48
bits of accuracy.</p>
<pre><code class="language-js">const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);

console.log(buf.readIntLE(0, 6).toString(16));
// Prints: -546f87a9cbee
console.log(buf.readIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.
console.log(buf.readIntBE(1, 0).toString(16));
// Throws ERR_OUT_OF_RANGE.
</code></pre>
<h3><code>buf.readUInt8([offset])</code><span><a class="mark" href="#buffer_buf_readuint8_offset" id="buffer_buf_readuint8_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 1</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Reads an unsigned 8-bit integer from <code>buf</code> at the specified <code>offset</code>.</p>
<pre><code class="language-js">const buf = Buffer.from([1, -2]);

console.log(buf.readUInt8(0));
// Prints: 1
console.log(buf.readUInt8(1));
// Prints: 254
console.log(buf.readUInt8(2));
// Throws ERR_OUT_OF_RANGE.
</code></pre>
<h3><code>buf.readUInt16BE([offset])</code><span><a class="mark" href="#buffer_buf_readuint16be_offset" id="buffer_buf_readuint16be_offset">#</a></span></h3>
<h3><code>buf.readUInt16LE([offset])</code><span><a class="mark" href="#buffer_buf_readuint16le_offset" id="buffer_buf_readuint16le_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Reads an unsigned 16-bit integer from <code>buf</code> at the specified <code>offset</code> with
the specified <a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>readUInt16BE()</code> reads as big endian, <code>readUInt16LE()</code>
reads as little endian).</p>
<pre><code class="language-js">const buf = Buffer.from([0x12, 0x34, 0x56]);

console.log(buf.readUInt16BE(0).toString(16));
// Prints: 1234
console.log(buf.readUInt16LE(0).toString(16));
// Prints: 3412
console.log(buf.readUInt16BE(1).toString(16));
// Prints: 3456
console.log(buf.readUInt16LE(1).toString(16));
// Prints: 5634
console.log(buf.readUInt16LE(2).toString(16));
// Throws ERR_OUT_OF_RANGE.
</code></pre>
<h3><code>buf.readUInt32BE([offset])</code><span><a class="mark" href="#buffer_buf_readuint32be_offset" id="buffer_buf_readuint32be_offset">#</a></span></h3>
<h3><code>buf.readUInt32LE([offset])</code><span><a class="mark" href="#buffer_buf_readuint32le_offset" id="buffer_buf_readuint32le_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Reads an unsigned 32-bit integer from <code>buf</code> at the specified <code>offset</code> with
the specified <a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>readUInt32BE()</code> reads as big endian,
<code>readUInt32LE()</code> reads as little endian).</p>
<pre><code class="language-js">const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);

console.log(buf.readUInt32BE(0).toString(16));
// Prints: 12345678
console.log(buf.readUInt32LE(0).toString(16));
// Prints: 78563412
console.log(buf.readUInt32LE(1).toString(16));
// Throws ERR_OUT_OF_RANGE.
</code></pre>
<h3><code>buf.readUIntBE(offset, byteLength)</code><span><a class="mark" href="#buffer_buf_readuintbe_offset_bytelength" id="buffer_buf_readuintbe_offset_bytelength">#</a></span></h3>
<h3><code>buf.readUIntLE(offset, byteLength)</code><span><a class="mark" href="#buffer_buf_readuintle_offset_bytelength" id="buffer_buf_readuintle_offset_bytelength">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to read. Must
satisfy <code>0 &#x3C;= offset &#x3C;= 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">&#x3C;integer></a> Number of bytes to read. Must satisfy
<code>0 &#x3C; byteLength &#x3C;= 6</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Reads <code>byteLength</code> number of bytes from <code>buf</code> at the specified <code>offset</code>
and interprets the result as an unsigned integer. Supports up to 48
bits of accuracy.</p>
<pre><code class="language-js">const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);

console.log(buf.readUIntBE(0, 6).toString(16));
// Prints: 1234567890ab
console.log(buf.readUIntLE(0, 6).toString(16));
// Prints: ab9078563412
console.log(buf.readUIntBE(1, 6).toString(16));
// Throws ERR_OUT_OF_RANGE.
</code></pre>
<h3><code>buf.subarray([start[, end]])</code><span><a class="mark" href="#buffer_buf_subarray_start_end" id="buffer_buf_subarray_start_end">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Where the new <code>Buffer</code> will end (not inclusive).
<strong>Default:</strong> <a href="#buffer_buf_length"><code>buf.length</code></a>.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;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>This method is inherited from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray"><code>TypedArray#subarray()</code></a>.</p>
<p>Modifying the new <code>Buffer</code> slice will modify the memory in the original <code>Buffer</code>
because the allocated memory of the two objects overlap.</p>
<pre><code class="language-js">// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
// from the original `Buffer`.

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i &#x3C; 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

const buf2 = buf1.subarray(0, 3);

console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: abc

buf1[0] = 33;

console.log(buf2.toString('ascii', 0, buf2.length));
// Prints: !bc
</code></pre>
<p>Specifying negative indexes causes the slice to be generated relative to the
end of <code>buf</code> rather than the beginning.</p>
<pre><code class="language-js">const buf = Buffer.from('buffer');

console.log(buf.subarray(-6, -1).toString());
// Prints: buffe
// (Equivalent to buf.subarray(0, 5).)

console.log(buf.subarray(-6, -2).toString());
// Prints: buff
// (Equivalent to buf.subarray(0, 4).)

console.log(buf.subarray(-5, -2).toString());
// Prints: uff
// (Equivalent to buf.subarray(1, 4).)
</code></pre>
<h3><code>buf.slice([start[, end]])</code><span><a class="mark" href="#buffer_buf_slice_start_end" id="buffer_buf_slice_start_end">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.1.0, v6.9.2</td>
<td><p>Coercing the offsets to integers now handles values outside the 32-bit integer range properly.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>All offsets are now coerced to integers before doing any calculations with them.</p></td></tr>
<tr><td>v0.3.0</td>
<td><p><span>Added in: v0.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Where the new <code>Buffer</code> will end (not inclusive).
<strong>Default:</strong> <a href="#buffer_buf_length"><code>buf.length</code></a>.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;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>This is the same behavior as <code>buf.subarray()</code>.</p>
<p>This method is not compatible with the <code>Uint8Array.prototype.slice()</code>,
which is a superclass of <code>Buffer</code>. To copy the slice, use
<code>Uint8Array.prototype.slice()</code>.</p>
<pre><code class="language-js">const buf = Buffer.from('buffer');

const copiedBuf = Uint8Array.prototype.slice.call(buf);
copiedBuf[0]++;
console.log(copiedBuf.toString());
// Prints: cuffer

console.log(buf.toString());
// Prints: buffer
</code></pre>
<h3><code>buf.swap16()</code><span><a class="mark" href="#buffer_buf_swap16" id="buffer_buf_swap16">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A reference to <code>buf</code>.</li>
</ul>
<p>Interprets <code>buf</code> as an array of unsigned 16-bit integers and swaps the
byte order <em>in-place</em>. Throws <a href="#ERR_INVALID_BUFFER_SIZE"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#buffer_buf_length"><code>buf.length</code></a>
is not a multiple of 2.</p>
<pre><code class="language-js">const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);

console.log(buf1);
// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08>

buf1.swap16();

console.log(buf1);
// Prints: &#x3C;Buffer 02 01 04 03 06 05 08 07>

const buf2 = Buffer.from([0x1, 0x2, 0x3]);

buf2.swap16();
// Throws ERR_INVALID_BUFFER_SIZE.
</code></pre>
<p>One convenient use of <code>buf.swap16()</code> is to perform a fast in-place conversion
between UTF-16 little-endian and UTF-16 big-endian:</p>
<pre><code class="language-js">const buf = Buffer.from('This is little-endian UTF-16', 'utf16le');
buf.swap16(); // Convert to big-endian UTF-16 text.
</code></pre>
<h3><code>buf.swap32()</code><span><a class="mark" href="#buffer_buf_swap32" id="buffer_buf_swap32">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A reference to <code>buf</code>.</li>
</ul>
<p>Interprets <code>buf</code> as an array of unsigned 32-bit integers and swaps the
byte order <em>in-place</em>. Throws <a href="#ERR_INVALID_BUFFER_SIZE"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#buffer_buf_length"><code>buf.length</code></a>
is not a multiple of 4.</p>
<pre><code class="language-js">const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);

console.log(buf1);
// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08>

buf1.swap32();

console.log(buf1);
// Prints: &#x3C;Buffer 04 03 02 01 08 07 06 05>

const buf2 = Buffer.from([0x1, 0x2, 0x3]);

buf2.swap32();
// Throws ERR_INVALID_BUFFER_SIZE.
</code></pre>
<h3><code>buf.swap64()</code><span><a class="mark" href="#buffer_buf_swap64" id="buffer_buf_swap64">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.3.0</span>
</div>
<ul>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A reference to <code>buf</code>.</li>
</ul>
<p>Interprets <code>buf</code> as an array of 64-bit numbers and swaps byte order <em>in-place</em>.
Throws <a href="#ERR_INVALID_BUFFER_SIZE"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#buffer_buf_length"><code>buf.length</code></a> is not a multiple of 8.</p>
<pre><code class="language-js">const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);

console.log(buf1);
// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08>

buf1.swap64();

console.log(buf1);
// Prints: &#x3C;Buffer 08 07 06 05 04 03 02 01>

const buf2 = Buffer.from([0x1, 0x2, 0x3]);

buf2.swap64();
// Throws ERR_INVALID_BUFFER_SIZE.
</code></pre>
<h3><code>buf.toJSON()</code><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">&#x3C;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>
<p><code>Buffer.from()</code> accepts objects in the format returned from this method.
In particular, <code>Buffer.from(buf.toJSON())</code> works like <code>Buffer.from(buf)</code>.</p>
<pre><code class="language-js">const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
const json = JSON.stringify(buf);

console.log(json);
// Prints: {"type":"Buffer","data":[1,2,3,4,5]}

const copy = JSON.parse(json, (key, value) => {
  return value &#x26;&#x26; value.type === 'Buffer' ?
    Buffer.from(value) :
    value;
});

console.log(copy);
// Prints: &#x3C;Buffer 01 02 03 04 05>
</code></pre>
<h3><code>buf.toString([encoding[, start[, end]]])</code><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">&#x3C;string></a> The character encoding to use. <strong>Default:</strong> <code>'utf8'</code>.</li>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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>If <code>encoding</code> is <code>'utf8'</code> and a byte sequence in the input is not valid UTF-8,
then each invalid byte is replaced with the replacement character <code>U+FFFD</code>.</p>
<p>The maximum length of a string instance (in UTF-16 code units) is available
as <a href="#buffer_buffer_constants_max_string_length"><code>buffer.constants.MAX_STRING_LENGTH</code></a>.</p>
<pre><code class="language-js">const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i &#x3C; 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

console.log(buf1.toString('utf8'));
// Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 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><code>buf.values()</code><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">&#x3C;Iterator></a></li>
</ul>
<p>Creates and returns an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterator</a> for <code>buf</code> values (bytes). This function is
called automatically when a <code>Buffer</code> is used in a <code>for..of</code> statement.</p>
<pre><code class="language-js">const buf = Buffer.from('buffer');

for (const value of buf.values()) {
  console.log(value);
}
// Prints:
//   98
//   117
//   102
//   102
//   101
//   114

for (const value of buf) {
  console.log(value);
}
// Prints:
//   98
//   117
//   102
//   102
//   101
//   114
</code></pre>
<h3><code>buf.write(string[, offset[, length]][, encoding])</code><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">&#x3C;string></a> String to write to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Maximum number of bytes to write (written bytes will not
exceed <code>buf.length - offset</code>). <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">&#x3C;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">&#x3C;integer></a> Number of bytes written.</li>
</ul>
<p>Writes <code>string</code> to <code>buf</code> at <code>offset</code> according to the character encoding in
<code>encoding</code>. The <code>length</code> parameter is the number of bytes to write. If <code>buf</code> did
not contain enough space to fit the entire string, only part of <code>string</code> will be
written. However, partially encoded characters will not be written.</p>
<pre><code class="language-js">const buf = Buffer.alloc(256);

const len = buf.write('\u00bd + \u00bc = \u00be', 0);

console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
// Prints: 12 bytes: ½ + ¼ = ¾

const buffer = Buffer.alloc(10);

const length = buffer.write('abcd', 8);

console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`);
// Prints: 2 bytes : ab
</code></pre>
<h3><code>buf.writeBigInt64BE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writebigint64be_value_offset" id="buffer_buf_writebigint64be_value_offset">#</a></span></h3>
<h3><code>buf.writeBigInt64LE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writebigint64le_value_offset" id="buffer_buf_writebigint64le_value_offset">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy: <code>0 &#x3C;= offset &#x3C;= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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 the specified
<a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>writeBigInt64BE()</code> writes as big endian, <code>writeBigInt64LE()</code>
writes as little endian).</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(8);

buf.writeBigInt64BE(0x0102030405060708n, 0);

console.log(buf);
// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08>
</code></pre>
<h3><code>buf.writeBigUInt64BE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writebiguint64be_value_offset" id="buffer_buf_writebiguint64be_value_offset">#</a></span></h3>
<h3><code>buf.writeBigUInt64LE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writebiguint64le_value_offset" id="buffer_buf_writebiguint64le_value_offset">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a> Number to be written to <code>buf</code>.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy: <code>0 &#x3C;= offset &#x3C;= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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 <a href="https://en.wikipedia.org/wiki/Endianness">endianness</a>
(<code>writeBigUInt64BE()</code> writes as big endian, <code>writeBigUInt64LE()</code> writes as
little endian).</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(8);

buf.writeBigUInt64LE(0xdecafafecacefaden, 0);

console.log(buf);
// Prints: &#x3C;Buffer de fa ce ca fe fa ca de>
</code></pre>
<h3><code>buf.writeDoubleBE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writedoublebe_value_offset" id="buffer_buf_writedoublebe_value_offset">#</a></span></h3>
<h3><code>buf.writeDoubleLE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writedoublele_value_offset" id="buffer_buf_writedoublele_value_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 8</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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 the specified
<a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>writeDoubleBE()</code> writes as big endian, <code>writeDoubleLE()</code> writes
as little endian). <code>value</code> must be a JavaScript number. Behavior is undefined
when <code>value</code> is anything other than a JavaScript number.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(8);

buf.writeDoubleBE(123.456, 0);

console.log(buf);
// Prints: &#x3C;Buffer 40 5e dd 2f 1a 9f be 77>

buf.writeDoubleLE(123.456, 0);

console.log(buf);
// Prints: &#x3C;Buffer 77 be 9f 1a 2f dd 5e 40>
</code></pre>
<h3><code>buf.writeFloatBE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writefloatbe_value_offset" id="buffer_buf_writefloatbe_value_offset">#</a></span></h3>
<h3><code>buf.writeFloatLE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writefloatle_value_offset" id="buffer_buf_writefloatle_value_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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 <a href="https://en.wikipedia.org/wiki/Endianness">endianness</a>
(<code>writeFloatBE()</code> writes as big endian, <code>writeFloatLE()</code> writes as little
endian). <code>value</code> must be a JavaScript number. Behavior is undefined when
<code>value</code> is anything other than a JavaScript number.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(4);

buf.writeFloatBE(0xcafebabe, 0);

console.log(buf);
// Prints: &#x3C;Buffer 4f 4a fe bb>

buf.writeFloatLE(0xcafebabe, 0);

console.log(buf);
// Prints: &#x3C;Buffer bb fe 4a 4f>
</code></pre>
<h3><code>buf.writeInt8(value[, offset])</code><span><a class="mark" href="#buffer_buf_writeint8_value_offset" id="buffer_buf_writeint8_value_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 1</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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> must be a valid
signed 8-bit integer. Behavior is undefined when <code>value</code> is anything other than
a signed 8-bit integer.</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(2);

buf.writeInt8(2, 0);
buf.writeInt8(-2, 1);

console.log(buf);
// Prints: &#x3C;Buffer 02 fe>
</code></pre>
<h3><code>buf.writeInt16BE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writeint16be_value_offset" id="buffer_buf_writeint16be_value_offset">#</a></span></h3>
<h3><code>buf.writeInt16LE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writeint16le_value_offset" id="buffer_buf_writeint16le_value_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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 the specified
<a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>writeInt16BE()</code> writes as big endian, <code>writeInt16LE()</code> writes
as little endian). <code>value</code> must be a valid signed 16-bit integer. Behavior is
undefined when <code>value</code> is anything other than a signed 16-bit integer.</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(4);

buf.writeInt16BE(0x0102, 0);
buf.writeInt16LE(0x0304, 2);

console.log(buf);
// Prints: &#x3C;Buffer 01 02 04 03>
</code></pre>
<h3><code>buf.writeInt32BE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writeint32be_value_offset" id="buffer_buf_writeint32be_value_offset">#</a></span></h3>
<h3><code>buf.writeInt32LE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writeint32le_value_offset" id="buffer_buf_writeint32le_value_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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 the specified
<a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>writeInt32BE()</code> writes aS big endian, <code>writeInt32LE()</code> writes
as little endian). <code>value</code> must be a valid signed 32-bit integer. Behavior is
undefined when <code>value</code> is anything other than a signed 32-bit integer.</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(8);

buf.writeInt32BE(0x01020304, 0);
buf.writeInt32LE(0x05060708, 4);

console.log(buf);
// Prints: &#x3C;Buffer 01 02 03 04 08 07 06 05>
</code></pre>
<h3><code>buf.writeIntBE(value, offset, byteLength)</code><span><a class="mark" href="#buffer_buf_writeintbe_value_offset_bytelength" id="buffer_buf_writeintbe_value_offset_bytelength">#</a></span></h3>
<h3><code>buf.writeIntLE(value, offset, byteLength)</code><span><a class="mark" href="#buffer_buf_writeintle_value_offset_bytelength" id="buffer_buf_writeintle_value_offset_bytelength">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 &#x3C;= offset &#x3C;= 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">&#x3C;integer></a> Number of bytes to write. Must satisfy
<code>0 &#x3C; byteLength &#x3C;= 6</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>byteLength</code> bytes of <code>value</code> to <code>buf</code> at the specified <code>offset</code>.
Supports up to 48 bits of accuracy. Behavior is undefined when <code>value</code> is
anything other than a signed integer.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(6);

buf.writeIntBE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: &#x3C;Buffer 12 34 56 78 90 ab>

buf.writeIntLE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: &#x3C;Buffer ab 90 78 56 34 12>
</code></pre>
<h3><code>buf.writeUInt8(value[, offset])</code><span><a class="mark" href="#buffer_buf_writeuint8_value_offset" id="buffer_buf_writeuint8_value_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 1</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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> must be a
valid unsigned 8-bit integer. Behavior is undefined when <code>value</code> is anything
other than an unsigned 8-bit integer.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(4);

buf.writeUInt8(0x3, 0);
buf.writeUInt8(0x4, 1);
buf.writeUInt8(0x23, 2);
buf.writeUInt8(0x42, 3);

console.log(buf);
// Prints: &#x3C;Buffer 03 04 23 42>
</code></pre>
<h3><code>buf.writeUInt16BE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writeuint16be_value_offset" id="buffer_buf_writeuint16be_value_offset">#</a></span></h3>
<h3><code>buf.writeUInt16LE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writeuint16le_value_offset" id="buffer_buf_writeuint16le_value_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 2</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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 the specified
<a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>writeUInt16BE()</code> writes as big endian, <code>writeUInt16LE()</code> writes
as little endian). <code>value</code> must be a valid unsigned 16-bit integer. Behavior is
undefined when <code>value</code> is anything other than an unsigned 16-bit integer.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(4);

buf.writeUInt16BE(0xdead, 0);
buf.writeUInt16BE(0xbeef, 2);

console.log(buf);
// Prints: &#x3C;Buffer de ad be ef>

buf.writeUInt16LE(0xdead, 0);
buf.writeUInt16LE(0xbeef, 2);

console.log(buf);
// Prints: &#x3C;Buffer ad de ef be>
</code></pre>
<h3><code>buf.writeUInt32BE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writeuint32be_value_offset" id="buffer_buf_writeuint32be_value_offset">#</a></span></h3>
<h3><code>buf.writeUInt32LE(value[, offset])</code><span><a class="mark" href="#buffer_buf_writeuint32le_value_offset" id="buffer_buf_writeuint32le_value_offset">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 &#x3C;= offset &#x3C;= buf.length - 4</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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 the specified
<a href="https://en.wikipedia.org/wiki/Endianness">endianness</a> (<code>writeUInt32BE()</code> writes as big endian, <code>writeUInt32LE()</code> writes
as little endian). <code>value</code> must be a valid unsigned 32-bit integer. Behavior is
undefined when <code>value</code> is anything other than an unsigned 32-bit integer.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(4);

buf.writeUInt32BE(0xfeedface, 0);

console.log(buf);
// Prints: &#x3C;Buffer fe ed fa ce>

buf.writeUInt32LE(0xfeedface, 0);

console.log(buf);
// Prints: &#x3C;Buffer ce fa ed fe>
</code></pre>
<h3><code>buf.writeUIntBE(value, offset, byteLength)</code><span><a class="mark" href="#buffer_buf_writeuintbe_value_offset_bytelength" id="buffer_buf_writeuintbe_value_offset_bytelength">#</a></span></h3>
<h3><code>buf.writeUIntLE(value, offset, byteLength)</code><span><a class="mark" href="#buffer_buf_writeuintle_value_offset_bytelength" id="buffer_buf_writeuintle_value_offset_bytelength">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Removed <code>noAssert</code> and no implicit coercion of the offset and <code>byteLength</code> to <code>uint32</code> anymore.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;integer></a> Number of bytes to skip before starting to write. Must
satisfy <code>0 &#x3C;= offset &#x3C;= 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">&#x3C;integer></a> Number of bytes to write. Must satisfy
<code>0 &#x3C; byteLength &#x3C;= 6</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <code>offset</code> plus the number of bytes written.</li>
</ul>
<p>Writes <code>byteLength</code> bytes of <code>value</code> to <code>buf</code> at the specified <code>offset</code>.
Supports up to 48 bits of accuracy. Behavior is undefined when <code>value</code> is
anything other than an unsigned integer.</p>
<pre><code class="language-js">const buf = Buffer.allocUnsafe(6);

buf.writeUIntBE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: &#x3C;Buffer 12 34 56 78 90 ab>

buf.writeUIntLE(0x1234567890ab, 0, 6);

console.log(buf);
// Prints: &#x3C;Buffer ab 90 78 56 34 12>
</code></pre>
<h3><code>new Buffer(array)</code><span><a class="mark" href="#buffer_new_buffer_array" id="buffer_new_buffer_array">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr>
<tr><td>v7.2.1</td>
<td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Calling this constructor emits a deprecation warning now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Deprecated since: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a> instead.</div><p></p>
<ul>
<li><code>array</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer[]></a> An array of bytes to copy from.</li>
</ul>
<p>See <a href="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a>.</p>
<h3><code>new Buffer(arrayBuffer[, byteOffset[, length]])</code><span><a class="mark" href="#buffer_new_buffer_arraybuffer_byteoffset_length" id="buffer_new_buffer_arraybuffer_byteoffset_length">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr>
<tr><td>v7.2.1</td>
<td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Calling this constructor emits a deprecation warning now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>byteOffset</code> and <code>length</code> parameters are supported now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Deprecated since: v6.0.0</span></p></td></tr>
<tr><td>v3.0.0</td>
<td><p><span>Added in: v3.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use
<a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a>
instead.</div><p></p>
<ul>
<li><code>arrayBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type">&#x3C;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">&#x3C;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">&#x3C;integer></a> Number of bytes to expose.
<strong>Default:</strong> <code>arrayBuffer.byteLength - byteOffset</code>.</li>
</ul>
<p>See
<a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a>.</p>
<h3><code>new Buffer(buffer)</code><span><a class="mark" href="#buffer_new_buffer_buffer" id="buffer_new_buffer_buffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr>
<tr><td>v7.2.1</td>
<td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Calling this constructor emits a deprecation warning now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Deprecated since: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a> instead.</div><p></p>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> An existing <code>Buffer</code> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> from
which to copy data.</li>
</ul>
<p>See <a href="#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a>.</p>
<h3><code>new Buffer(size)</code><span><a class="mark" href="#buffer_new_buffer_size" id="buffer_new_buffer_size">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>new Buffer(size)</code> will return zero-filled memory by default.</p></td></tr>
<tr><td>v7.2.1</td>
<td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Calling this constructor emits a deprecation warning now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Deprecated since: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc()</code></a> instead (also see
<a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a>).</div><p></p>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The desired length of the new <code>Buffer</code>.</li>
</ul>
<p>See <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>. This variant of the
constructor is equivalent to <a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc()</code></a>.</p>
<h3><code>new Buffer(string[, encoding])</code><span><a class="mark" href="#buffer_new_buffer_string_encoding" id="buffer_new_buffer_string_encoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Calling this constructor emits a deprecation warning when run from code outside the <code>node_modules</code> directory.</p></td></tr>
<tr><td>v7.2.1</td>
<td><p>Calling this constructor no longer emits a deprecation warning.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Calling this constructor emits a deprecation warning now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Deprecated since: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated:
Use <a href="#buffer_class_method_buffer_from_string_encoding"><code>Buffer.from(string[, encoding])</code></a> instead.</div><p></p>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> The encoding of <code>string</code>. <strong>Default:</strong> <code>'utf8'</code>.</li>
</ul>
<p>See <a href="#buffer_class_method_buffer_from_string_encoding"><code>Buffer.from(string[, encoding])</code></a>.</p>
<h2><code>buffer.INSPECT_MAX_BYTES</code><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">&#x3C;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>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><code>buffer.kMaxLength</code><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">&#x3C;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>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><code>buffer.transcode(source, fromEnc, toEnc)</code><span><a class="mark" href="#buffer_buffer_transcode_source_fromenc_toenc" id="buffer_buffer_transcode_source_fromenc_toenc">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>source</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v7.1.0</td>
<td><p><span>Added in: v7.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>source</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;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">&#x3C;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">&#x3C;string></a> To target encoding.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Re-encodes the given <code>Buffer</code> or <code>Uint8Array</code> instance from one character
encoding to another. Returns a new <code>Buffer</code> instance.</p>
<p>Throws if the <code>fromEnc</code> or <code>toEnc</code> specify invalid character encodings or if
conversion from <code>fromEnc</code> to <code>toEnc</code> is not permitted.</p>
<p>Encodings supported by <code>buffer.transcode()</code> are: <code>'ascii'</code>, <code>'utf8'</code>,
<code>'utf16le'</code>, <code>'ucs2'</code>, <code>'latin1'</code>, and <code>'binary'</code>.</p>
<p>The transcoding process will use substitution characters if a given byte
sequence cannot be adequately represented in the target encoding. For instance:</p>
<pre><code class="language-js">const buffer = require('buffer');

const newBuf = buffer.transcode(Buffer.from('€'), 'utf8', 'ascii');
console.log(newBuf.toString('ascii'));
// Prints: '?'
</code></pre>
<p>Because the Euro (<code>€</code>) sign is not representable in US-ASCII, it is replaced
with <code>?</code> in the transcoded <code>Buffer</code>.</p>
<p>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: <code>SlowBuffer</code><span><a class="mark" href="#buffer_class_slowbuffer" id="buffer_class_slowbuffer">#</a></span></h2>
<div class="api_metadata">
<span>Deprecated since: v6.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow()</code></a> instead.</div><p></p>
<p>See <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow()</code></a>. This was never a class in the sense that
the constructor always returned a <code>Buffer</code> instance, rather than a <code>SlowBuffer</code>
instance.</p>
<h3><code>new SlowBuffer(size)</code><span><a class="mark" href="#buffer_new_slowbuffer_size" id="buffer_new_slowbuffer_size">#</a></span></h3>
<div class="api_metadata">
<span>Deprecated since: v6.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow()</code></a> instead.</div><p></p>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The desired length of the new <code>SlowBuffer</code>.</li>
</ul>
<p>See <a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow()</code></a>.</p>
<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><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><code>buffer.constants.MAX_LENGTH</code><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">&#x3C;integer></a> The largest size allowed for a single <code>Buffer</code> instance.</li>
</ul>
<p>On 32-bit architectures, this value currently is <code>(2^30)-1</code> (~1GB).
On 64-bit architectures, this value currently 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><code>buffer.constants.MAX_STRING_LENGTH</code><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">&#x3C;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>
<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> before reading data from the <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>. Since Node.js 8.0.0, <code>Buffer(num)</code> and <code>new Buffer(num)</code> 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>For example, if an attacker can cause an application to receive a number where
a string is expected, the application may call <code>new Buffer(100)</code>
instead of <code>new Buffer("100")</code>, leading it to allocate a 100 byte buffer instead
of allocating a 3 byte buffer with content <code>"100"</code>. This is commonly possible
using JSON API calls. Since JSON distinguishes between numeric and string types,
it allows injection of numbers where a naively written application that does not
validate its input sufficiently might expect to always receive a string.
Before Node.js 8.0.0, the 100 byte buffer might contain
arbitrary pre-existing in-memory data, so may be used to expose in-memory
secrets to a remote attacker. Since Node.js 8.0.0, exposure of memory cannot
occur because the data is zero-filled. However, other attacks are still
possible, such as causing very large buffers to be allocated by the server,
leading to performance degradation or crashing on memory exhaustion.</p>
<p>To make the creation of <code>Buffer</code> instances more reliable and less error-prone,
the various forms of the <code>new Buffer()</code> constructor have been <strong>deprecated</strong>
and replaced by separate <code>Buffer.from()</code>, <a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc()</code></a>, and
<a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> methods.</p>
<p><em>Developers should migrate all existing uses of the <code>new Buffer()</code> constructors
to one of these new APIs.</em></p>
<ul>
<li><a href="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a> returns a new <code>Buffer</code> that <em>contains a copy</em> of the
provided octets.</li>
<li><a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a>
returns a new <code>Buffer</code> that <em>shares the same allocated memory</em> as the given
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>.</li>
<li><a href="#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a> returns a new <code>Buffer</code> that <em>contains a copy</em> of the
contents of the given <code>Buffer</code>.</li>
<li><a href="#buffer_class_method_buffer_from_string_encoding"><code>Buffer.from(string[, encoding])</code></a> returns a new
<code>Buffer</code> that <em>contains a copy</em> of the provided string.</li>
<li><a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc(size[, fill[, encoding]])</code></a> returns a new
initialized <code>Buffer</code> of the specified size. This method is slower than
<a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe(size)</code></a> but guarantees that newly
created <code>Buffer</code> instances never contain old data that is potentially
sensitive. A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</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> and
<a href="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</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. Without the option, buffers created with <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> are not zero-filled.
Use of this flag can have a measurable negative impact on performance. Use the
<code>--zero-fill-buffers</code> option only when necessary to enforce that newly allocated
<code>Buffer</code> instances cannot contain old data that is potentially sensitive.</p>
<pre><code class="language-console">$ node --zero-fill-buffers
> Buffer.allocUnsafe(5);
&#x3C;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>
<h1>C++ addons<span><a class="mark" href="#addons_c_addons" id="addons_c_addons">#</a></span></h1>


<p>Addons are dynamically-linked shared objects written in C++. The
<a href="#modules_require_id"><code>require()</code></a> function can load Addons as ordinary Node.js modules.
Addons provide an interface between JavaScript and C/C++ libraries.</p>
<p>There are three options for implementing Addons: N-API, nan, or direct
use of internal V8, libuv and Node.js libraries. Unless there is a need for
direct access to functionality which is not exposed by N-API, use N-API.
Refer to <a href="n-api.html">C/C++ Addons with N-API</a> for more information on N-API.</p>
<p>When not using N-API, implementing Addons is complicated,
involving knowledge of several components and APIs:</p>
<ul>
<li>
<p>V8: the C++ library Node.js 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 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 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_libraries_included_with_node_js">Linking to libraries included with Node.js</a> for additional information.</p>
</li>
</ul>
<p>All of the following examples are available for <a href="https://github.com/nodejs/node-addon-examples">download</a> and may
be used as the starting-point for an Addon.</p>
<h2>Hello world<span><a class="mark" href="#addons_hello_world" id="addons_hello_world">#</a></span></h2>
<p>This "Hello world" example is a simple Addon, written in C++, that is the
equivalent of the following JavaScript code:</p>
<pre><code class="language-js">module.exports.hello = () => 'world';
</code></pre>
<p>First, create the file <code>hello.cc</code>:</p>
<pre><code class="language-cpp">// hello.cc
#include &#x3C;node.h>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Object;
using v8::String;
using v8::Value;

void Method(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(
      isolate, "world", NewStringType::kNormal).ToLocalChecked());
}

void Initialize(Local&#x3C;Object> exports) {
  NODE_SET_METHOD(exports, "hello", Method);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)

}  // namespace demo
</code></pre>
<p>All Node.js Addons must export an initialization function following
the pattern:</p>
<pre><code class="language-cpp">void Initialize(Local&#x3C;Object> exports);
NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
</code></pre>
<p>There is no semi-colon after <code>NODE_MODULE</code> as it's not a function (see
<code>node.h</code>).</p>
<p>The <code>module_name</code> must match the filename of the final binary (excluding
the <code>.node</code> suffix).</p>
<p>In the <code>hello.cc</code> example, then, the initialization function is <code>Initialize</code>
and the addon module name is <code>addon</code>.</p>
<p>When building addons with <code>node-gyp</code>, using the macro <code>NODE_GYP_MODULE_NAME</code> as
the first parameter of <code>NODE_MODULE()</code> will ensure that the name of the final
binary will be passed to <code>NODE_MODULE()</code>.</p>
<h3>Context-aware addons<span><a class="mark" href="#addons_context_aware_addons" id="addons_context_aware_addons">#</a></span></h3>
<p>There are environments in which Node.js addons may need to be loaded multiple
times in multiple contexts. For example, the <a href="https://electronjs.org/">Electron</a> runtime runs multiple
instances of Node.js in a single process. Each instance will have its own
<code>require()</code> cache, and thus each instance will need a native addon to behave
correctly when loaded via <code>require()</code>. From the addon's perspective, this means
that it must support multiple initializations.</p>
<p>A context-aware addon can be constructed by using the macro
<code>NODE_MODULE_INITIALIZER</code>, which expands to the name of a function which Node.js
will expect to find when it loads an addon. An addon can thus be initialized as
in the following example:</p>
<pre><code class="language-cpp">using namespace v8;

extern "C" NODE_MODULE_EXPORT void
NODE_MODULE_INITIALIZER(Local&#x3C;Object> exports,
                        Local&#x3C;Value> module,
                        Local&#x3C;Context> context) {
  /* Perform addon initialization steps here. */
}
</code></pre>
<p>Another option is to use the macro <code>NODE_MODULE_INIT()</code>, which will also
construct a context-aware addon. Unlike <code>NODE_MODULE()</code>, which is used to
construct an addon around a given addon initializer function,
<code>NODE_MODULE_INIT()</code> serves as the declaration of such an initializer to be
followed by a function body.</p>
<p>The following three variables may be used inside the function body following an
invocation of <code>NODE_MODULE_INIT()</code>:</p>
<ul>
<li><code>Local&#x3C;Object> exports</code>,</li>
<li><code>Local&#x3C;Value> module</code>, and</li>
<li><code>Local&#x3C;Context> context</code></li>
</ul>
<p>The choice to build a context-aware addon carries with it the responsibility of
carefully managing global static data. Since the addon may be loaded multiple
times, potentially even from different threads, any global static data stored
in the addon must be properly protected, and must not contain any persistent
references to JavaScript objects. The reason for this is that JavaScript
objects are only valid in one context, and will likely cause a crash when
accessed from the wrong context or from a different thread than the one on which
they were created.</p>
<p>The context-aware addon can be structured to avoid global static data by
performing the following steps:</p>
<ul>
<li>
<p>Define a class which will hold per-addon-instance data and which has a static
member of the form</p>
<pre><code class="language-cpp">static void DeleteInstance(void* data) {
  // Cast `data` to an instance of the class and delete it.
}
</code></pre>
</li>
<li>Heap-allocate an instance of this class in the addon initializer. This can be
accomplished using the <code>new</code> keyword.</li>
<li>Call <code>node::AddEnvironmentCleanupHook()</code>, passing it the above-created
instance and a pointer to <code>DeleteInstance()</code>. This will ensure the instance is
deleted when the environment is torn down.</li>
<li>Store the instance of the class in a <code>v8::External</code>, and</li>
<li>Pass the <code>v8::External</code> to all methods exposed to JavaScript by passing it
to <code>v8::FunctionTemplate::New()</code> or <code>v8::Function::New()</code> which creates the
native-backed JavaScript functions. The third parameter of
<code>v8::FunctionTemplate::New()</code> or <code>v8::Function::New()</code>  accepts the
<code>v8::External</code> and makes it available in the native callback using the
<code>v8::FunctionCallbackInfo::Data()</code> method.</li>
</ul>
<p>This will ensure that the per-addon-instance data reaches each binding that can
be called from JavaScript. The per-addon-instance data must also be passed into
any asynchronous callbacks the addon may create.</p>
<p>The following example illustrates the implementation of a context-aware addon:</p>
<pre><code class="language-cpp">#include &#x3C;node.h>

using namespace v8;

class AddonData {
 public:
  explicit AddonData(Isolate* isolate):
      call_count(0) {
    // Ensure this per-addon-instance data is deleted at environment cleanup.
    node::AddEnvironmentCleanupHook(isolate, DeleteInstance, this);
  }

  // Per-addon data.
  int call_count;

  static void DeleteInstance(void* data) {
    delete static_cast&#x3C;AddonData*>(data);
  }
};

static void Method(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; info) {
  // Retrieve the per-addon-instance data.
  AddonData* data =
      reinterpret_cast&#x3C;AddonData*>(info.Data().As&#x3C;External>()->Value());
  data->call_count++;
  info.GetReturnValue().Set((double)data->call_count);
}

// Initialize this addon to be context-aware.
NODE_MODULE_INIT(/* exports, module, context */) {
  Isolate* isolate = context->GetIsolate();

  // Create a new instance of `AddonData` for this instance of the addon and
  // tie its life cycle to that of the Node.js environment.
  AddonData* data = new AddonData(isolate);

  // Wrap the data in a `v8::External` so we can pass it to the method we
  // expose.
  Local&#x3C;External> external = External::New(isolate, data);

  // Expose the method `Method` to JavaScript, and make sure it receives the
  // per-addon-instance data we created above by passing `external` as the
  // third parameter to the `FunctionTemplate` constructor.
  exports->Set(context,
               String::NewFromUtf8(isolate, "method", NewStringType::kNormal)
                  .ToLocalChecked(),
               FunctionTemplate::New(isolate, Method, external)
                  ->GetFunction(context).ToLocalChecked()).FromJust();
}
</code></pre>
<h4>Worker support<span><a class="mark" href="#addons_worker_support" id="addons_worker_support">#</a></span></h4>
<p>In order to be loaded from multiple Node.js environments,
such as a main thread and a Worker thread, an add-on needs to either:</p>
<ul>
<li>Be an N-API addon, or</li>
<li>Be declared as context-aware using <code>NODE_MODULE_INIT()</code> as described above</li>
</ul>
<p>In order to support <a href="#worker_threads_class_worker"><code>Worker</code></a> threads, addons need to clean up any resources
they may have allocated when such a thread exists. This can be achieved through
the usage of the <code>AddEnvironmentCleanupHook()</code> function:</p>
<pre><code class="language-cpp">void AddEnvironmentCleanupHook(v8::Isolate* isolate,
                               void (*fun)(void* arg),
                               void* arg);
</code></pre>
<p>This function adds a hook that will run before a given Node.js instance shuts
down. If necessary, such hooks can be removed using
<code>RemoveEnvironmentCleanupHook()</code> before they are run, which has the same
signature. Callbacks are run in last-in first-out order.</p>
<p>The following <code>addon.cc</code> uses <code>AddEnvironmentCleanupHook</code>:</p>
<pre><code class="language-cpp">// addon.cc
#include &#x3C;assert.h>
#include &#x3C;stdlib.h>
#include &#x3C;node.h>

using node::AddEnvironmentCleanupHook;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;

// Note: In a real-world application, do not rely on static/global data.
static char cookie[] = "yum yum";
static int cleanup_cb1_called = 0;
static int cleanup_cb2_called = 0;

static void cleanup_cb1(void* arg) {
  Isolate* isolate = static_cast&#x3C;Isolate*>(arg);
  HandleScope scope(isolate);
  Local&#x3C;Object> obj = Object::New(isolate);
  assert(!obj.IsEmpty());  // assert VM is still alive
  assert(obj->IsObject());
  cleanup_cb1_called++;
}

static void cleanup_cb2(void* arg) {
  assert(arg == static_cast&#x3C;void*>(cookie));
  cleanup_cb2_called++;
}

static void sanity_check(void*) {
  assert(cleanup_cb1_called == 1);
  assert(cleanup_cb2_called == 1);
}

// Initialize this addon to be context-aware.
NODE_MODULE_INIT(/* exports, module, context */) {
  Isolate* isolate = context->GetIsolate();

  AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);
  AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);
  AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);
}
</code></pre>
<p>Test in JavaScript by running:</p>
<pre><code class="language-js">// test.js
require('./build/Release/addon');
</code></pre>
<h3>Building<span><a class="mark" href="#addons_building" id="addons_building">#</a></span></h3>
<p>Once the source code has been written, it must be compiled into the binary
<code>addon.node</code> file. To do so, create a file called <code>binding.gyp</code> in the
top-level of the project describing the build configuration of the module
using a JSON-like format. This file is used by <a href="https://github.com/nodejs/node-gyp">node-gyp</a>, a tool written
specifically to compile Node.js Addons.</p>
<pre><code class="language-json">{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "hello.cc" ]
    }
  ]
}
</code></pre>
<p>A version of the <code>node-gyp</code> utility is bundled and distributed with
Node.js as part of <code>npm</code>. This version is not made directly available for
developers to use and is intended only to support the ability to use the
<code>npm install</code> command to compile and install Addons. Developers who wish to
use <code>node-gyp</code> directly can install it using the command
<code>npm install -g node-gyp</code>. See the <code>node-gyp</code> <a href="https://github.com/nodejs/node-gyp#installation">installation instructions</a> for
more information, including platform-specific requirements.</p>
<p>Once the <code>binding.gyp</code> file has been created, use <code>node-gyp configure</code> to
generate the appropriate project build files for the current platform. This
will generate either a <code>Makefile</code> (on Unix platforms) or a <code>vcxproj</code> file
(on Windows) in the <code>build/</code> directory.</p>
<p>Next, invoke the <code>node-gyp build</code> command to generate the compiled <code>addon.node</code>
file. This will be put into the <code>build/Release/</code> directory.</p>
<p>When using <code>npm install</code> to install a Node.js Addon, npm uses its own bundled
version of <code>node-gyp</code> to perform this same set of actions, generating a
compiled version of the Addon for the user's platform on demand.</p>
<p>Once built, the binary Addon can be used from within Node.js by pointing
<a href="#modules_require_id"><code>require()</code></a> to the built <code>addon.node</code> module:</p>
<pre><code class="language-js">// hello.js
const addon = require('./build/Release/addon');

console.log(addon.hello());
// Prints: 'world'
</code></pre>
<p>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>While the <code>bindings</code> package implementation is more sophisticated in how it
locates Addon modules, it is essentially using a <code>try…catch</code> pattern similar to:</p>
<pre><code class="language-js">try {
  return require('./build/Release/addon.node');
} catch (err) {
  return require('./build/Debug/addon.node');
}
</code></pre>
<h3>Linking to libraries included with Node.js<span><a class="mark" href="#addons_linking_to_libraries_included_with_node_js" id="addons_linking_to_libraries_included_with_node_js">#</a></span></h3>
<p>Node.js uses 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 &#x3C;...></code> statements (e.g. <code>#include &#x3C;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 <code>require()</code><span><a class="mark" href="#addons_loading_addons_using_require" id="addons_loading_addons_using_require">#</a></span></h3>
<p>The filename extension of the compiled Addon binary is <code>.node</code> (as opposed
to <code>.dll</code> or <code>.so</code>). The <a href="#modules_require_id"><code>require()</code></a> function is written to look for
files with the <code>.node</code> file extension and initialize those as dynamically-linked
libraries.</p>
<p>When calling <a href="#modules_require_id"><code>require()</code></a>, the <code>.node</code> extension can usually be
omitted and Node.js will still find and initialize the Addon. One caveat,
however, is that Node.js will first attempt to locate and load modules or
JavaScript files that happen to share the same base name. For instance, if
there is a file <code>addon.js</code> in the same directory as the binary <code>addon.node</code>,
then <a href="#modules_require_id"><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. 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 to ensure stability of the V8 APIs.</p>
<p>The <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a> (or <code>nan</code>) provide a set of tools that
Addon developers are recommended to use to keep compatibility between past and
future releases of V8 and Node.js. See the <code>nan</code> <a href="https://github.com/nodejs/nan/tree/master/examples/">examples</a> for an
illustration of how it can be used.</p>
<h2>N-API<span><a class="mark" href="#addons_n_api" id="addons_n_api">#</a></span></h2>
<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>N-API is an API for building native Addons. It is independent from
the underlying JavaScript runtime (e.g. V8) and is maintained as part of
Node.js itself. This API will be Application Binary Interface (ABI) stable
across versions of Node.js. It is intended to insulate Addons from
changes in the underlying JavaScript engine and allow modules
compiled for one version to run on later versions of Node.js without
recompilation. Addons are built/packaged with the same approach/tools
outlined in this document (node-gyp, etc.). The only difference is the
set of APIs that are used by the native code. Instead of using the V8
or <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a> APIs, the functions available
in the N-API are used.</p>
<p>Creating and maintaining an addon that benefits from the ABI stability
provided by N-API carries with it certain
<a href="#n_api_implications_of_abi_stability">implementation considerations</a>.</p>
<p>To use N-API in the above "Hello world" example, replace the content of
<code>hello.cc</code> with the following. All other instructions remain the same.</p>
<pre><code class="language-cpp">// hello.cc using N-API
#include &#x3C;node_api.h>

namespace demo {

napi_value Method(napi_env env, napi_callback_info args) {
  napi_value greeting;
  napi_status status;

  status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &#x26;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, &#x26;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
<a href="n-api.html">C/C++ Addons with 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&#x27;s%20Guide">Embedder's Guide</a> for an
explanation of several concepts used such as handles, scopes, function
templates, etc.</p>
<p>Each of these examples using the following <code>binding.gyp</code> file:</p>
<pre><code class="language-json">{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "addon.cc" ]
    }
  ]
}
</code></pre>
<p>In cases where there is more than one <code>.cc</code> file, simply add the additional
filename to the <code>sources</code> array:</p>
<pre><code class="language-json">"sources": ["addon.cc", "myexample.cc"]
</code></pre>
<p>Once the <code>binding.gyp</code> file is ready, the example Addons can be configured and
built using <code>node-gyp</code>:</p>
<pre><code class="language-console">$ node-gyp configure build
</code></pre>
<h3>Function arguments<span><a class="mark" href="#addons_function_arguments" id="addons_function_arguments">#</a></span></h3>
<p>Addons will typically expose objects and functions that can be accessed from
JavaScript running within Node.js. When functions are invoked from JavaScript,
the input arguments and return value must be mapped to and from the C/C++
code.</p>
<p>The following example illustrates how to read function arguments passed from
JavaScript and how to return a result:</p>
<pre><code class="language-cpp">// addon.cc
#include &#x3C;node.h>

namespace demo {

using v8::Exception;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

// This is the implementation of the "add" method
// Input arguments are passed using the
// const FunctionCallbackInfo&#x3C;Value>&#x26; args struct
void Add(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();

  // Check the number of arguments passed.
  if (args.Length() &#x3C; 2) {
    // Throw an Error that is passed back to JavaScript
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate,
                            "Wrong number of arguments",
                            NewStringType::kNormal).ToLocalChecked()));
    return;
  }

  // Check the argument types
  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate,
                            "Wrong arguments",
                            NewStringType::kNormal).ToLocalChecked()));
    return;
  }

  // Perform the operation
  double value =
      args[0].As&#x3C;Number>()->Value() + args[1].As&#x3C;Number>()->Value();
  Local&#x3C;Number> num = Number::New(isolate, value);

  // Set the return value (using the passed in
  // FunctionCallbackInfo&#x3C;Value>&#x26;)
  args.GetReturnValue().Set(num);
}

void Init(Local&#x3C;Object> exports) {
  NODE_SET_METHOD(exports, "add", Add);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Init)

}  // namespace demo
</code></pre>
<p>Once compiled, the example Addon can be required and used from within Node.js:</p>
<pre><code class="language-js">// test.js
const addon = require('./build/Release/addon');

console.log('This should be eight:', addon.add(3, 5));
</code></pre>
<h3>Callbacks<span><a class="mark" href="#addons_callbacks" id="addons_callbacks">#</a></span></h3>
<p>It is common practice within Addons to pass JavaScript functions to a C++
function and execute them from there. The following example illustrates how
to invoke such callbacks:</p>
<pre><code class="language-cpp">// addon.cc
#include &#x3C;node.h>

namespace demo {

using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Null;
using v8::Object;
using v8::String;
using v8::Value;

void RunCallback(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();
  Local&#x3C;Context> context = isolate->GetCurrentContext();
  Local&#x3C;Function> cb = Local&#x3C;Function>::Cast(args[0]);
  const unsigned argc = 1;
  Local&#x3C;Value> argv[argc] = {
      String::NewFromUtf8(isolate,
                          "hello world",
                          NewStringType::kNormal).ToLocalChecked() };
  cb->Call(context, Null(isolate), argc, argv).ToLocalChecked();
}

void Init(Local&#x3C;Object> exports, Local&#x3C;Object> module) {
  NODE_SET_METHOD(module, "exports", RunCallback);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Init)

}  // namespace demo
</code></pre>
<p>This example uses a two-argument form of <code>Init()</code> that receives the full
<code>module</code> object as the second argument. This allows the Addon to completely
overwrite <code>exports</code> with a single function instead of adding the function as a
property of <code>exports</code>.</p>
<p>To test it, run the following JavaScript:</p>
<pre><code class="language-js">// test.js
const addon = require('./build/Release/addon');

addon((msg) => {
  console.log(msg);
// Prints: 'hello world'
});
</code></pre>
<p>In this example, the callback function is invoked synchronously.</p>
<h3>Object factory<span><a class="mark" href="#addons_object_factory" id="addons_object_factory">#</a></span></h3>
<p>Addons can create and return new objects from within a C++ function as
illustrated in the following example. An object is created and returned with a
property <code>msg</code> that echoes the string passed to <code>createObject()</code>:</p>
<pre><code class="language-cpp">// addon.cc
#include &#x3C;node.h>

namespace demo {

using v8::Context;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Object;
using v8::String;
using v8::Value;

void CreateObject(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();
  Local&#x3C;Context> context = isolate->GetCurrentContext();

  Local&#x3C;Object> obj = Object::New(isolate);
  obj->Set(context,
           String::NewFromUtf8(isolate,
                               "msg",
                               NewStringType::kNormal).ToLocalChecked(),
                               args[0]->ToString(context).ToLocalChecked())
           .FromJust();

  args.GetReturnValue().Set(obj);
}

void Init(Local&#x3C;Object> exports, Local&#x3C;Object> module) {
  NODE_SET_METHOD(module, "exports", CreateObject);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Init)

}  // namespace demo
</code></pre>
<p>To test it in JavaScript:</p>
<pre><code class="language-js">// test.js
const addon = require('./build/Release/addon');

const obj1 = addon('hello');
const obj2 = addon('world');
console.log(obj1.msg, obj2.msg);
// Prints: 'hello world'
</code></pre>
<h3>Function factory<span><a class="mark" href="#addons_function_factory" id="addons_function_factory">#</a></span></h3>
<p>Another common scenario is creating JavaScript functions that wrap C++
functions and returning those back to JavaScript:</p>
<pre><code class="language-cpp">// addon.cc
#include &#x3C;node.h>

namespace demo {

using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Object;
using v8::String;
using v8::Value;

void MyFunction(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(
      isolate, "hello world", NewStringType::kNormal).ToLocalChecked());
}

void CreateFunction(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();

  Local&#x3C;Context> context = isolate->GetCurrentContext();
  Local&#x3C;FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
  Local&#x3C;Function> fn = tpl->GetFunction(context).ToLocalChecked();

  // omit this to make it anonymous
  fn->SetName(String::NewFromUtf8(
      isolate, "theFunction", NewStringType::kNormal).ToLocalChecked());

  args.GetReturnValue().Set(fn);
}

void Init(Local&#x3C;Object> exports, Local&#x3C;Object> module) {
  NODE_SET_METHOD(module, "exports", CreateFunction);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Init)

}  // namespace demo
</code></pre>
<p>To test:</p>
<pre><code class="language-js">// test.js
const addon = require('./build/Release/addon');

const fn = addon();
console.log(fn());
// Prints: 'hello world'
</code></pre>
<h3>Wrapping C++ objects<span><a class="mark" href="#addons_wrapping_c_objects" id="addons_wrapping_c_objects">#</a></span></h3>
<p>It is also possible to wrap C++ objects/classes in a way that allows new
instances to be created using the JavaScript <code>new</code> operator:</p>
<pre><code class="language-cpp">// addon.cc
#include &#x3C;node.h>
#include "myobject.h"

namespace demo {

using v8::Local;
using v8::Object;

void InitAll(Local&#x3C;Object> exports) {
  MyObject::Init(exports);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)

}  // namespace demo
</code></pre>
<p>Then, in <code>myobject.h</code>, the wrapper class inherits from <code>node::ObjectWrap</code>:</p>
<pre><code class="language-cpp">// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include &#x3C;node.h>
#include &#x3C;node_object_wrap.h>

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init(v8::Local&#x3C;v8::Object> exports);

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args);
  static void PlusOne(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args);

  double value_;
};

}  // namespace demo

#endif
</code></pre>
<p>In <code>myobject.cc</code>, implement the various methods that are to be exposed.
Below, the method <code>plusOne()</code> is exposed by adding it to the constructor's
prototype:</p>
<pre><code class="language-cpp">// myobject.cc
#include "myobject.h"

namespace demo {

using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Number;
using v8::Object;
using v8::ObjectTemplate;
using v8::String;
using v8::Value;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init(Local&#x3C;Object> exports) {
  Isolate* isolate = exports->GetIsolate();
  Local&#x3C;Context> context = isolate->GetCurrentContext();

  Local&#x3C;ObjectTemplate> addon_data_tpl = ObjectTemplate::New(isolate);
  addon_data_tpl->SetInternalFieldCount(1);  // 1 field for the MyObject::New()
  Local&#x3C;Object> addon_data =
      addon_data_tpl->NewInstance(context).ToLocalChecked();

  // Prepare constructor template
  Local&#x3C;FunctionTemplate> tpl = FunctionTemplate::New(isolate, New, addon_data);
  tpl->SetClassName(String::NewFromUtf8(
      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  // Prototype
  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);

  Local&#x3C;Function> constructor = tpl->GetFunction(context).ToLocalChecked();
  addon_data->SetInternalField(0, constructor);
  exports->Set(context, String::NewFromUtf8(
      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked(),
               constructor).FromJust();
}

void MyObject::New(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();
  Local&#x3C;Context> context = isolate->GetCurrentContext();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ?
        0 : args[0]->NumberValue(context).FromMaybe(0);
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local&#x3C;Value> argv[argc] = { args[0] };
    Local&#x3C;Function> cons =
        args.Data().As&#x3C;Object>()->GetInternalField(0).As&#x3C;Function>();
    Local&#x3C;Object> result =
        cons->NewInstance(context, argc, argv).ToLocalChecked();
    args.GetReturnValue().Set(result);
  }
}

void MyObject::PlusOne(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();

  MyObject* obj = ObjectWrap::Unwrap&#x3C;MyObject>(args.Holder());
  obj->value_ += 1;

  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}

}  // namespace demo
</code></pre>
<p>To build this example, the <code>myobject.cc</code> file must be added to the
<code>binding.gyp</code>:</p>
<pre><code class="language-json">{
  "targets": [
    {
      "target_name": "addon",
      "sources": [
        "addon.cc",
        "myobject.cc"
      ]
    }
  ]
}
</code></pre>
<p>Test it with:</p>
<pre><code class="language-js">// test.js
const addon = require('./build/Release/addon');

const obj = new addon.MyObject(10);
console.log(obj.plusOne());
// Prints: 11
console.log(obj.plusOne());
// Prints: 12
console.log(obj.plusOne());
// Prints: 13
</code></pre>
<p>The destructor for a wrapper object will run when the object is
garbage-collected. For destructor testing, there are command-line flags that
can be used to make it possible to force garbage collection. These flags are
provided by the underlying V8 JavaScript engine. They are subject to change
or removal at any time. They are not documented by Node.js or V8, and they
should never be used outside of testing.</p>
<h3>Factory of wrapped objects<span><a class="mark" href="#addons_factory_of_wrapped_objects" id="addons_factory_of_wrapped_objects">#</a></span></h3>
<p>Alternatively, it is possible to use a factory pattern to avoid explicitly
creating object instances using the JavaScript <code>new</code> operator:</p>
<pre><code class="language-js">const obj = addon.createObject();
// instead of:
// const obj = new addon.Object();
</code></pre>
<p>First, the <code>createObject()</code> method is implemented in <code>addon.cc</code>:</p>
<pre><code class="language-cpp">// addon.cc
#include &#x3C;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&#x3C;Value>&#x26; args) {
  MyObject::NewInstance(args);
}

void InitAll(Local&#x3C;Object> exports, Local&#x3C;Object> module) {
  MyObject::Init(exports->GetIsolate());

  NODE_SET_METHOD(module, "exports", CreateObject);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)

}  // namespace demo
</code></pre>
<p>In <code>myobject.h</code>, the static method <code>NewInstance()</code> is added to handle
instantiating the object. This method takes the place of using <code>new</code> in
JavaScript:</p>
<pre><code class="language-cpp">// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include &#x3C;node.h>
#include &#x3C;node_object_wrap.h>

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init(v8::Isolate* isolate);
  static void NewInstance(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args);

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args);
  static void PlusOne(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args);
  static v8::Global&#x3C;v8::Function> constructor;
  double value_;
};

}  // namespace demo

#endif
</code></pre>
<p>The implementation in <code>myobject.cc</code> is similar to the previous example:</p>
<pre><code class="language-cpp">// myobject.cc
#include &#x3C;node.h>
#include "myobject.h"

namespace demo {

using node::AddEnvironmentCleanupHook;
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Global;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

// Warning! This is not thread-safe, this addon cannot be used for worker
// threads.
Global&#x3C;Function> MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init(Isolate* isolate) {
  // Prepare constructor template
  Local&#x3C;FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(
      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  // Prototype
  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);

  Local&#x3C;Context> context = isolate->GetCurrentContext();
  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());

  AddEnvironmentCleanupHook(isolate, [](void*) {
    constructor.Reset();
  }, nullptr);
}

void MyObject::New(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();
  Local&#x3C;Context> context = isolate->GetCurrentContext();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ?
        0 : args[0]->NumberValue(context).FromMaybe(0);
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local&#x3C;Value> argv[argc] = { args[0] };
    Local&#x3C;Function> cons = Local&#x3C;Function>::New(isolate, constructor);
    Local&#x3C;Object> instance =
        cons->NewInstance(context, argc, argv).ToLocalChecked();
    args.GetReturnValue().Set(instance);
  }
}

void MyObject::NewInstance(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();

  const unsigned argc = 1;
  Local&#x3C;Value> argv[argc] = { args[0] };
  Local&#x3C;Function> cons = Local&#x3C;Function>::New(isolate, constructor);
  Local&#x3C;Context> context = isolate->GetCurrentContext();
  Local&#x3C;Object> instance =
      cons->NewInstance(context, argc, argv).ToLocalChecked();

  args.GetReturnValue().Set(instance);
}

void MyObject::PlusOne(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();

  MyObject* obj = ObjectWrap::Unwrap&#x3C;MyObject>(args.Holder());
  obj->value_ += 1;

  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}

}  // namespace demo
</code></pre>
<p>Once again, to build this example, the <code>myobject.cc</code> file must be added to the
<code>binding.gyp</code>:</p>
<pre><code class="language-json">{
  "targets": [
    {
      "target_name": "addon",
      "sources": [
        "addon.cc",
        "myobject.cc"
      ]
    }
  ]
}
</code></pre>
<p>Test it with:</p>
<pre><code class="language-js">// test.js
const createObject = require('./build/Release/addon');

const obj = createObject(10);
console.log(obj.plusOne());
// Prints: 11
console.log(obj.plusOne());
// Prints: 12
console.log(obj.plusOne());
// Prints: 13

const obj2 = createObject(20);
console.log(obj2.plusOne());
// Prints: 21
console.log(obj2.plusOne());
// Prints: 22
console.log(obj2.plusOne());
// Prints: 23
</code></pre>
<h3>Passing wrapped objects around<span><a class="mark" href="#addons_passing_wrapped_objects_around" id="addons_passing_wrapped_objects_around">#</a></span></h3>
<p>In addition to wrapping and returning C++ objects, it is possible to pass
wrapped objects around by unwrapping them with the Node.js helper function
<code>node::ObjectWrap::Unwrap</code>. The following examples shows a function <code>add()</code>
that can take two <code>MyObject</code> objects as input arguments:</p>
<pre><code class="language-cpp">// addon.cc
#include &#x3C;node.h>
#include &#x3C;node_object_wrap.h>
#include "myobject.h"

namespace demo {

using v8::Context;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

void CreateObject(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  MyObject::NewInstance(args);
}

void Add(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();
  Local&#x3C;Context> context = isolate->GetCurrentContext();

  MyObject* obj1 = node::ObjectWrap::Unwrap&#x3C;MyObject>(
      args[0]->ToObject(context).ToLocalChecked());
  MyObject* obj2 = node::ObjectWrap::Unwrap&#x3C;MyObject>(
      args[1]->ToObject(context).ToLocalChecked());

  double sum = obj1->value() + obj2->value();
  args.GetReturnValue().Set(Number::New(isolate, sum));
}

void InitAll(Local&#x3C;Object> exports) {
  MyObject::Init(exports->GetIsolate());

  NODE_SET_METHOD(exports, "createObject", CreateObject);
  NODE_SET_METHOD(exports, "add", Add);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)

}  // namespace demo
</code></pre>
<p>In <code>myobject.h</code>, a new public method is added to allow access to private values
after unwrapping the object.</p>
<pre><code class="language-cpp">// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include &#x3C;node.h>
#include &#x3C;node_object_wrap.h>

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init(v8::Isolate* isolate);
  static void NewInstance(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args);
  inline double value() const { return value_; }

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args);
  static v8::Global&#x3C;v8::Function> constructor;
  double value_;
};

}  // namespace demo

#endif
</code></pre>
<p>The implementation of <code>myobject.cc</code> is similar to before:</p>
<pre><code class="language-cpp">// myobject.cc
#include &#x3C;node.h>
#include "myobject.h"

namespace demo {

using node::AddEnvironmentCleanupHook;
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Global;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Object;
using v8::String;
using v8::Value;

// Warning! This is not thread-safe, this addon cannot be used for worker
// threads.
Global&#x3C;Function> MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init(Isolate* isolate) {
  // Prepare constructor template
  Local&#x3C;FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(
      isolate, "MyObject", NewStringType::kNormal).ToLocalChecked());
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  Local&#x3C;Context> context = isolate->GetCurrentContext();
  constructor.Reset(isolate, tpl->GetFunction(context).ToLocalChecked());

  AddEnvironmentCleanupHook(isolate, [](void*) {
    constructor.Reset();
  }, nullptr);
}

void MyObject::New(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();
  Local&#x3C;Context> context = isolate->GetCurrentContext();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ?
        0 : args[0]->NumberValue(context).FromMaybe(0);
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local&#x3C;Value> argv[argc] = { args[0] };
    Local&#x3C;Function> cons = Local&#x3C;Function>::New(isolate, constructor);
    Local&#x3C;Object> instance =
        cons->NewInstance(context, argc, argv).ToLocalChecked();
    args.GetReturnValue().Set(instance);
  }
}

void MyObject::NewInstance(const FunctionCallbackInfo&#x3C;Value>&#x26; args) {
  Isolate* isolate = args.GetIsolate();

  const unsigned argc = 1;
  Local&#x3C;Value> argv[argc] = { args[0] };
  Local&#x3C;Function> cons = Local&#x3C;Function>::New(isolate, constructor);
  Local&#x3C;Context> context = isolate->GetCurrentContext();
  Local&#x3C;Object> instance =
      cons->NewInstance(context, argc, argv).ToLocalChecked();

  args.GetReturnValue().Set(instance);
}

}  // namespace demo
</code></pre>
<p>Test it with:</p>
<pre><code class="language-js">// test.js
const addon = require('./build/Release/addon');

const obj1 = addon.createObject(10);
const obj2 = addon.createObject(20);
const result = addon.add(obj1, obj2);

console.log(result);
// Prints: 30
</code></pre>
<h1>N-API<span><a class="mark" href="#n_api_n_api" id="n_api_n_api">#</a></span></h1>


<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>N-API (pronounced N as in the letter, followed by API)
is an API for building native Addons. It is independent from
the underlying JavaScript runtime (for example, V8) and is maintained as part of
Node.js itself. This API will be Application Binary Interface (ABI) stable
across versions of Node.js. It is intended to insulate Addons from
changes in the underlying JavaScript engine and allow modules
compiled for one major version to run on later major versions of Node.js without
recompilation. The <a href="https://nodejs.org/en/docs/guides/abi-stability/">ABI Stability</a> guide provides a more in-depth explanation.</p>
<p>Addons are built/packaged with the same approach/tools outlined in the section
titled <a href="addons.html">C++ Addons</a>. The only difference is the set of APIs that are used by
the native code. Instead of using the V8 or <a href="https://github.com/nodejs/nan">Native Abstractions for Node.js</a>
APIs, the functions available in the N-API are used.</p>
<p>APIs exposed by N-API are generally used to create and manipulate
JavaScript values. Concepts and operations generally map to ideas specified
in the ECMA-262 Language Specification. The APIs have the following
properties:</p>
<ul>
<li>All N-API calls return a status code of type <code>napi_status</code>. This
status indicates whether the API call succeeded or failed.</li>
<li>The API's return value is passed via an out parameter.</li>
<li>All JavaScript values are abstracted behind an opaque type named
<code>napi_value</code>.</li>
<li>In case of an error status code, additional information can be obtained
using <code>napi_get_last_error_info</code>. More information can be found in the error
handling section <a href="#n_api_error_handling">Error handling</a>.</li>
</ul>
<p>The N-API is a C API that ensures ABI stability across Node.js versions
and different compiler levels. A C++ API can be easier to use.
To support using C++, the project maintains a
C++ wrapper module called <a href="https://github.com/nodejs/node-addon-api">node-addon-api</a>.
This wrapper provides an inlineable C++ API. Binaries built
with <code>node-addon-api</code> will depend on the symbols for the N-API C-based
functions exported by Node.js. <code>node-addon-api</code> is a more
efficient way to write code that calls N-API. Take, for example, the
following <code>node-addon-api</code> code. The first section shows the
<code>node-addon-api</code> code and the second section shows what actually gets
used in the addon.</p>
<pre><code class="language-cpp">Object obj = Object::New(env);
obj["foo"] = String::New(env, "bar");
</code></pre>
<pre><code class="language-cpp">napi_status status;
napi_value object, string;
status = napi_create_object(env, &#x26;object);
if (status != napi_ok) {
  napi_throw_error(env, ...);
  return;
}

status = napi_create_string_utf8(env, "bar", NAPI_AUTO_LENGTH, &#x26;string);
if (status != napi_ok) {
  napi_throw_error(env, ...);
  return;
}

status = napi_set_named_property(env, object, "foo", string);
if (status != napi_ok) {
  napi_throw_error(env, ...);
  return;
}
</code></pre>
<p>The end result is that the addon only uses the exported C APIs. As a result,
it still gets the benefits of the ABI stability provided by the C API.</p>
<p>When using <code>node-addon-api</code> instead of the C APIs, start with the API <a href="https://github.com/nodejs/node-addon-api#api-documentation">docs</a>
for <code>node-addon-api</code>.</p>
<h2>Implications of ABI stability<span><a class="mark" href="#n_api_implications_of_abi_stability" id="n_api_implications_of_abi_stability">#</a></span></h2>
<p>Although N-API provides an ABI stability guarantee, other parts of Node.js do
not, and any external libraries used from the addon may not. In particular,
none of the following APIs provide an ABI stability guarantee across major
versions:</p>
<ul>
<li>
<p>the Node.js C++ APIs available via any of</p>
<pre><code class="language-cpp">#include &#x3C;node.h>
#include &#x3C;node_buffer.h>
#include &#x3C;node_version.h>
#include &#x3C;node_object_wrap.h>
</code></pre>
</li>
<li>
<p>the libuv APIs which are also included with Node.js and available via</p>
<pre><code class="language-cpp">#include &#x3C;uv.h>
</code></pre>
</li>
<li>
<p>the V8 API available via</p>
<pre><code class="language-cpp">#include &#x3C;v8.h>
</code></pre>
</li>
</ul>
<p>Thus, for an addon to remain ABI-compatible across Node.js major versions, it
must make use exclusively of N-API by restricting itself to using</p>
<pre><code class="language-c">#include &#x3C;node_api.h>
</code></pre>
<p>and by checking, for all external libraries that it uses, that the external
library makes ABI stability guarantees similar to N-API.</p>
<h2>Building<span><a class="mark" href="#n_api_building" id="n_api_building">#</a></span></h2>
<p>Unlike modules written in JavaScript, developing and deploying Node.js
native addons using N-API requires an additional set of tools. Besides the
basic tools required to develop for Node.js, the native addon developer
requires a toolchain that can compile C and C++ code into a binary. In
addition, depending upon how the native addon is deployed, the <em>user</em> of
the native addon will also need to have a C/C++ toolchain installed.</p>
<p>For Linux developers, the necessary C/C++ toolchain packages are readily
available. <a href="https://gcc.gnu.org">GCC</a> is widely used in the Node.js community to build and
test across a variety of plarforms. For many developers, the <a href="https://llvm.org">LLVM</a>
compiler infrastructure is also a good choice.</p>
<p>For Mac developers, <a href="https://developer.apple.com/xcode/">Xcode</a> offers all the required compiler tools.
However, it is not necessary to install the entire Xcode IDE. The following
command installs the necessary toolchain:</p>
<pre><code class="language-bash">xcode-select --install
</code></pre>
<p>For Windows developers, <a href="https://visualstudio.microsoft.com">Visual Studio</a> offers all the required compiler
tools. However, it is not necessary to install the entire Visual Studio
IDE. The following command installs the necessary toolchain:</p>
<pre><code class="language-bash">npm install --global --production windows-build-tools
</code></pre>
<p>The sections below describe the additional tools available for developing
and deploying Node.js native addons.</p>
<h3>Build tools<span><a class="mark" href="#n_api_build_tools" id="n_api_build_tools">#</a></span></h3>
<p>Both the tools listed here require that <em>users</em> of the native
addon have a C/C++ toolchain installed in order to successfully install
the native addon.</p>
<h4>node-gyp<span><a class="mark" href="#n_api_node_gyp" id="n_api_node_gyp">#</a></span></h4>
<p><a href="https://github.com/nodejs/node-gyp">node-gyp</a> is a build system based on Google's <a href="https://gyp.gsrc.io">GYP</a> tool and comes
bundled with npm. GYP, and therefore node-gyp, requires that Python be
installed.</p>
<p>Historically, node-gyp has been the tool of choice for building native
addons. It has widespread adoption and documentation. However, some
developers have run into limitations in node-gyp.</p>
<h4>CMake.js<span><a class="mark" href="#n_api_cmake_js" id="n_api_cmake_js">#</a></span></h4>
<p><a href="https://github.com/cmake-js/cmake-js">CMake.js</a> is an alternative build system based on <a href="https://cmake.org">CMake</a>.</p>
<p>CMake.js is a good choice for projects that already use CMake or for
developers affected by limitations in node-gyp.</p>
<h3>Uploading precompiled binaries<span><a class="mark" href="#n_api_uploading_precompiled_binaries" id="n_api_uploading_precompiled_binaries">#</a></span></h3>
<p>The three tools listed here permit native addon developers and maintainers
to create and upload binaries to public or private servers. These tools are
typically integrated with CI/CD build systems like <a href="https://travis-ci.org">Travis CI</a> and
<a href="https://www.appveyor.com">AppVeyor</a> to build and upload binaries for a variety of platforms and
architectures. These binaries are then available for download by users who
do not need to have a C/C++ toolchain installed.</p>
<h4>node-pre-gyp<span><a class="mark" href="#n_api_node_pre_gyp" id="n_api_node_pre_gyp">#</a></span></h4>
<p><a href="https://github.com/mapbox/node-pre-gyp">node-pre-gyp</a> is a tool based on node-gyp that adds the ability to
upload binaries to a server of the developer's choice. node-pre-gyp has
particularly good support for uploading binaries to Amazon S3.</p>
<h4>prebuild<span><a class="mark" href="#n_api_prebuild" id="n_api_prebuild">#</a></span></h4>
<p><a href="https://github.com/prebuild/prebuild">prebuild</a> is a tool that supports builds using either node-gyp or
CMake.js. Unlike node-pre-gyp which supports a variety of servers, prebuild
uploads binaries only to <a href="https://help.github.com/en/github/administering-a-repository/about-releases">GitHub releases</a>. prebuild is a good choice for
GitHub projects using CMake.js.</p>
<h4>prebuildify<span><a class="mark" href="#n_api_prebuildify" id="n_api_prebuildify">#</a></span></h4>
<p><a href="https://github.com/prebuild/prebuildify">prebuildify</a> is a tool based on node-gyp. The advantage of prebuildify is
that the built binaries are bundled with the native module when it's
uploaded to npm. The binaries are downloaded from npm and are immediately
available to the module user when the native module is installed.</p>
<h2>Usage<span><a class="mark" href="#n_api_usage" id="n_api_usage">#</a></span></h2>
<p>In order to use the N-API functions, include the file <a href="https://github.com/nodejs/node/blob/master/src/node_api.h"><code>node_api.h</code></a> which is
located in the src directory in the node development tree:</p>
<pre><code class="language-c">#include &#x3C;node_api.h>
</code></pre>
<p>This will opt into the default <code>NAPI_VERSION</code> for the given release of Node.js.
In order to ensure compatibility with specific versions of N-API, the version
can be specified explicitly when including the header:</p>
<pre><code class="language-c">#define NAPI_VERSION 3
#include &#x3C;node_api.h>
</code></pre>
<p>This restricts the N-API surface to just the functionality that was available in
the specified (and earlier) versions.</p>
<p>Some of the N-API surface is considered experimental and requires explicit
opt-in to access those APIs:</p>
<pre><code class="language-c">#define NAPI_EXPERIMENTAL
#include &#x3C;node_api.h>
</code></pre>
<p>In this case the entire API surface, including any experimental APIs, will be
available to the module code.</p>
<h2>N-API version matrix<span><a class="mark" href="#n_api_n_api_version_matrix" id="n_api_n_api_version_matrix">#</a></span></h2>
<p>N-API versions are additive and versioned independently from Node.js.
Version 4 is an extension to version 3 in that it has all of the APIs
from version 3 with some additions. This means that it is not necessary
to recompile for new versions of Node.js which are
listed as supporting a later version.</p>






















































































<table><thead><tr><th></th><th>1</th><th>2</th><th>3</th><th>4</th><th>5</th><th>6</th></tr></thead><tbody><tr><td>v6.x</td><td></td><td></td><td>v6.14.2*</td><td></td><td></td><td></td></tr><tr><td>v8.x</td><td>v8.0.0*</td><td>v8.10.0*</td><td>v8.11.2</td><td>v8.16.0</td><td></td><td></td></tr><tr><td>v9.x</td><td>v9.0.0*</td><td>v9.3.0*</td><td>v9.11.0*</td><td></td><td></td><td></td></tr><tr><td>v10.x</td><td>v10.0.0</td><td>v10.0.0</td><td>v10.0.0</td><td>v10.16.0</td><td>v10.17.0</td><td>v10.20.0</td></tr><tr><td>v11.x</td><td>v11.0.0</td><td>v11.0.0</td><td>v11.0.0</td><td>v11.8.0</td><td></td><td></td></tr><tr><td>v12.x</td><td>v12.0.0</td><td>v12.0.0</td><td>v12.0.0</td><td>v12.0.0</td><td>v12.11.0</td><td>v12.17.0</td></tr><tr><td>v13.x</td><td>v13.0.0</td><td>v13.0.0</td><td>v13.0.0</td><td>v13.0.0</td><td>v13.0.0</td><td></td></tr><tr><td>v14.x</td><td>v14.0.0</td><td>v14.0.0</td><td>v14.0.0</td><td>v14.0.0</td><td>v14.0.0</td><td>v14.0.0</td></tr></tbody></table>
<p>* Indicates that the N-API version was released as experimental</p>
<p>The N-APIs associated strictly with accessing ECMAScript features from native
code can be found separately in <code>js_native_api.h</code> and <code>js_native_api_types.h</code>.
The APIs defined in these headers are included in <code>node_api.h</code> and
<code>node_api_types.h</code>. The headers are structured in this way in order to allow
implementations of N-API outside of Node.js. For those implementations the
Node.js specific APIs may not be applicable.</p>
<p>The Node.js-specific parts of an addon can be separated from the code that
exposes the actual functionality to the JavaScript environment so that the
latter may be used with multiple implementations of N-API. In the example below,
<code>addon.c</code> and <code>addon.h</code> refer only to <code>js_native_api.h</code>. This ensures that
<code>addon.c</code> can be reused to compile against either the Node.js implementation of
N-API or any implementation of N-API outside of Node.js.</p>
<p><code>addon_node.c</code> is a separate file that contains the Node.js specific entry point
to the addon and which instantiates the addon by calling into <code>addon.c</code> when the
addon is loaded into a Node.js environment.</p>
<pre><code class="language-c">// addon.h
#ifndef _ADDON_H_
#define _ADDON_H_
#include &#x3C;js_native_api.h>
napi_value create_addon(napi_env env);
#endif  // _ADDON_H_
</code></pre>
<pre><code class="language-c">// addon.c
#include "addon.h"

#define NAPI_CALL(env, call)                                      \
  do {                                                            \
    napi_status status = (call);                                  \
    if (status != napi_ok) {                                      \
      const napi_extended_error_info* error_info = NULL;          \
      napi_get_last_error_info((env), &#x26;error_info);               \
      bool is_pending;                                            \
      napi_is_exception_pending((env), &#x26;is_pending);              \
      if (!is_pending) {                                          \
        const char* message = (error_info->error_message == NULL) \
            ? "empty error message"                               \
            : error_info->error_message;                          \
        napi_throw_error((env), NULL, message);                   \
        return NULL;                                              \
      }                                                           \
    }                                                             \
  } while(0)

static napi_value
DoSomethingUseful(napi_env env, napi_callback_info info) {
  // Do something useful.
  return NULL;
}

napi_value create_addon(napi_env env) {
  napi_value result;
  NAPI_CALL(env, napi_create_object(env, &#x26;result));

  napi_value exported_function;
  NAPI_CALL(env, napi_create_function(env,
                                      "doSomethingUseful",
                                      NAPI_AUTO_LENGTH,
                                      DoSomethingUseful,
                                      NULL,
                                      &#x26;exported_function));

  NAPI_CALL(env, napi_set_named_property(env,
                                         result,
                                         "doSomethingUseful",
                                         exported_function));

  return result;
}
</code></pre>
<pre><code class="language-c">// addon_node.c
#include &#x3C;node_api.h>
#include "addon.h"

NAPI_MODULE_INIT() {
  // This function body is expected to return a `napi_value`.
  // The variables `napi_env env` and `napi_value exports` may be used within
  // the body, as they are provided by the definition of `NAPI_MODULE_INIT()`.
  return create_addon(env);
}
</code></pre>
<h2>Environment life cycle APIs<span><a class="mark" href="#n_api_environment_life_cycle_apis" id="n_api_environment_life_cycle_apis">#</a></span></h2>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p><a href="https://tc39.es/ecma262/#sec-agents">Section 8.7</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a> defines the concept
of an "Agent" as a self-contained environment in which JavaScript code runs.
Multiple such Agents may be started and terminated either concurrently or in
sequence by the process.</p>
<p>A Node.js environment corresponds to an ECMAScript Agent. In the main process,
an environment is created at startup, and additional environments can be created
on separate threads to serve as <a href="https://nodejs.org/api/worker_threads.html">worker threads</a>. When Node.js is embedded in
another application, the main thread of the application may also construct and
destroy a Node.js environment multiple times during the life cycle of the
application process such that each Node.js environment created by the
application may, in turn, during its life cycle create and destroy additional
environments as worker threads.</p>
<p>From the perspective of a native addon this means that the bindings it provides
may be called multiple times, from multiple contexts, and even concurrently from
multiple threads.</p>
<p>Native addons may need to allocate global state of which they make use during
their entire life cycle such that the state must be unique to each instance of
the addon.</p>
<p>To this end, N-API provides a way to allocate data such that its life cycle is
tied to the life cycle of the Agent.</p>
<h3>napi_set_instance_data<span><a class="mark" href="#n_api_napi_set_instance_data" id="n_api_napi_set_instance_data">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.8.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status napi_set_instance_data(napi_env env,
                                   void* data,
                                   napi_finalize finalize_cb,
                                   void* finalize_hint);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] data</code>: The data item to make available to bindings of this instance.</li>
<li><code>[in] finalize_cb</code>: The function to call when the environment is being torn
down. The function receives <code>data</code> so that it might free it.</li>
<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
collection.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API associates <code>data</code> with the currently running Agent. <code>data</code> can later
be retrieved using <code>napi_get_instance_data()</code>. Any existing data associated with
the currently running Agent which was set by means of a previous call to
<code>napi_set_instance_data()</code> will be overwritten. If a <code>finalize_cb</code> was provided
by the previous call, it will not be called.</p>
<h3>napi_get_instance_data<span><a class="mark" href="#n_api_napi_get_instance_data" id="n_api_napi_get_instance_data">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.8.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status napi_get_instance_data(napi_env env,
                                   void** data);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[out] data</code>: The data item that was previously associated with the currently
running Agent by a call to <code>napi_set_instance_data()</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API retrieves data that was previously associated with the currently
running Agent via <code>napi_set_instance_data()</code>. If no data is set, the call will
succeed and <code>data</code> will be set to <code>NULL</code>.</p>
<h2>Basic N-API data types<span><a class="mark" href="#n_api_basic_n_api_data_types" id="n_api_basic_n_api_data_types">#</a></span></h2>
<p>N-API exposes the following fundamental datatypes as abstractions that are
consumed by the various APIs. These APIs should be treated as opaque,
introspectable only with other N-API calls.</p>
<h3>napi_status<span><a class="mark" href="#n_api_napi_status" id="n_api_napi_status">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Integral status code indicating the success or failure of a N-API call.
Currently, the following status codes are supported.</p>
<pre><code class="language-c">typedef enum {
  napi_ok,
  napi_invalid_arg,
  napi_object_expected,
  napi_string_expected,
  napi_name_expected,
  napi_function_expected,
  napi_number_expected,
  napi_boolean_expected,
  napi_array_expected,
  napi_generic_failure,
  napi_pending_exception,
  napi_cancelled,
  napi_escape_called_twice,
  napi_handle_scope_mismatch,
  napi_callback_scope_mismatch,
  napi_queue_full,
  napi_closing,
  napi_bigint_expected,
  napi_date_expected,
  napi_arraybuffer_expected,
  napi_detachable_arraybuffer_expected,
} napi_status;
</code></pre>
<p>If additional information is required upon an API returning a failed status,
it can be obtained by calling <code>napi_get_last_error_info</code>.</p>
<h3>napi_extended_error_info<span><a class="mark" href="#n_api_napi_extended_error_info" id="n_api_napi_extended_error_info">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">typedef struct {
  const char* error_message;
  void* engine_reserved;
  uint32_t engine_error_code;
  napi_status error_code;
} napi_extended_error_info;
</code></pre>
<ul>
<li><code>error_message</code>: UTF8-encoded string containing a VM-neutral description of
the error.</li>
<li><code>engine_reserved</code>: Reserved for VM-specific error details. This is currently
not implemented for any VM.</li>
<li><code>engine_error_code</code>: VM-specific error code. This is currently
not implemented for any VM.</li>
<li><code>error_code</code>: The N-API status code that originated with the last error.</li>
</ul>
<p>See the <a href="#n_api_error_handling">Error handling</a> section for additional information.</p>
<h3>napi_env<span><a class="mark" href="#n_api_napi_env" id="n_api_napi_env">#</a></span></h3>
<p><code>napi_env</code> is used to represent a context that the underlying N-API
implementation can use to persist VM-specific state. This structure is passed
to native functions when they're invoked, and it must be passed back when
making N-API calls. Specifically, the same <code>napi_env</code> that was passed in when
the initial native function was called must be passed to any subsequent
nested N-API calls. Caching the <code>napi_env</code> for the purpose of general reuse,
and passing the <code>napi_env</code> between instances of the same addon running on
different <a href="#worker_threads_class_worker"><code>Worker</code></a> threads is not allowed. The <code>napi_env</code> becomes invalid
when an instance of a native addon is unloaded. Notification of this event is
delivered through the callbacks given to <a href="#n_api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a> and
<a href="#n_api_napi_set_instance_data"><code>napi_set_instance_data</code></a>.</p>
<h3>napi_value<span><a class="mark" href="#n_api_napi_value" id="n_api_napi_value">#</a></span></h3>
<p>This is an opaque pointer that is used to represent a JavaScript value.</p>
<h3>napi_threadsafe_function<span><a class="mark" href="#n_api_napi_threadsafe_function" id="n_api_napi_threadsafe_function">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<p>This is an opaque pointer that represents a JavaScript function which can be
called asynchronously from multiple threads via
<code>napi_call_threadsafe_function()</code>.</p>
<h3>napi_threadsafe_function_release_mode<span><a class="mark" href="#n_api_napi_threadsafe_function_release_mode" id="n_api_napi_threadsafe_function_release_mode">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<p>A value to be given to <code>napi_release_threadsafe_function()</code> to indicate whether
the thread-safe function is to be closed immediately (<code>napi_tsfn_abort</code>) or
merely released (<code>napi_tsfn_release</code>) and thus available for subsequent use via
<code>napi_acquire_threadsafe_function()</code> and <code>napi_call_threadsafe_function()</code>.</p>
<pre><code class="language-c">typedef enum {
  napi_tsfn_release,
  napi_tsfn_abort
} napi_threadsafe_function_release_mode;
</code></pre>
<h3>napi_threadsafe_function_call_mode<span><a class="mark" href="#n_api_napi_threadsafe_function_call_mode" id="n_api_napi_threadsafe_function_call_mode">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<p>A value to be given to <code>napi_call_threadsafe_function()</code> to indicate whether
the call should block whenever the queue associated with the thread-safe
function is full.</p>
<pre><code class="language-c">typedef enum {
  napi_tsfn_nonblocking,
  napi_tsfn_blocking
} napi_threadsafe_function_call_mode;
</code></pre>
<h3>N-API memory management types<span><a class="mark" href="#n_api_n_api_memory_management_types" id="n_api_n_api_memory_management_types">#</a></span></h3>
<h4>napi_handle_scope<span><a class="mark" href="#n_api_napi_handle_scope" id="n_api_napi_handle_scope">#</a></span></h4>
<p>This is an abstraction used to control and modify the lifetime of objects
created within a particular scope. In general, N-API values are created within
the context of a handle scope. When a native method is called from
JavaScript, a default handle scope will exist. If the user does not explicitly
create a new handle scope, N-API values will be created in the default handle
scope. For any invocations of code outside the execution of a native method
(for instance, during a libuv callback invocation), the module is required to
create a scope before invoking any functions that can result in the creation
of JavaScript values.</p>
<p>Handle scopes are created using <a href="#n_api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and are destroyed
using <a href="#n_api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a>. Closing the scope can indicate to the GC
that all <code>napi_value</code>s created during the lifetime of the handle scope are no
longer referenced from the current stack frame.</p>
<p>For more details, review the <a href="#n_api_object_lifetime_management">Object lifetime management</a>.</p>
<h4>napi_escapable_handle_scope<span><a class="mark" href="#n_api_napi_escapable_handle_scope" id="n_api_napi_escapable_handle_scope">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<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>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<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>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<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>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Function pointer type for user-provided native functions which are to be
exposed to JavaScript via N-API. Callback functions should satisfy the
following signature:</p>
<pre><code class="language-c">typedef napi_value (*napi_callback)(napi_env, napi_callback_info);
</code></pre>
<h4>napi_finalize<span><a class="mark" href="#n_api_napi_finalize" id="n_api_napi_finalize">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Function pointer type for add-on provided functions that allow the user to be
notified when externally-owned data is ready to be cleaned up because the
object with which it was associated with, has been garbage-collected. The user
must provide a function satisfying the following signature which would get
called upon the object's collection. Currently, <code>napi_finalize</code> can be used for
finding out when objects that have external data are collected.</p>
<pre><code class="language-c">typedef void (*napi_finalize)(napi_env env,
                              void* finalize_data,
                              void* finalize_hint);
</code></pre>
<h4>napi_async_execute_callback<span><a class="mark" href="#n_api_napi_async_execute_callback" id="n_api_napi_async_execute_callback">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Function pointer used with functions that support asynchronous
operations. Callback functions must satisfy the following signature:</p>
<pre><code class="language-c">typedef void (*napi_async_execute_callback)(napi_env env, void* data);
</code></pre>
<p>Implementations of this function must avoid making N-API calls
that execute JavaScript or interact with
JavaScript objects. N-API
calls should be in the <code>napi_async_complete_callback</code> instead.
Do not use the <code>napi_env</code> parameter as it will likely
result in execution of JavaScript.</p>
<h4>napi_async_complete_callback<span><a class="mark" href="#n_api_napi_async_complete_callback" id="n_api_napi_async_complete_callback">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<p>Function pointer used with functions that support asynchronous
operations. Callback functions must satisfy the following signature:</p>
<pre><code class="language-c">typedef void (*napi_async_complete_callback)(napi_env env,
                                             napi_status status,
                                             void* data);
</code></pre>
<h4>napi_threadsafe_function_call_js<span><a class="mark" href="#n_api_napi_threadsafe_function_call_js" id="n_api_napi_threadsafe_function_call_js">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<p>Function pointer used with asynchronous thread-safe function calls. The callback
will be called on the main thread. Its purpose is to use a data item arriving
via the queue from one of the secondary threads to construct the parameters
necessary for a call into JavaScript, usually via <code>napi_call_function</code>, and then
make the call into JavaScript.</p>
<p>The data arriving from the secondary thread via the queue is given in the <code>data</code>
parameter and the JavaScript function to call is given in the <code>js_callback</code>
parameter.</p>
<p>N-API sets up the environment prior to calling this callback, so it is
sufficient to call the JavaScript function via <code>napi_call_function</code> rather than
via <code>napi_make_callback</code>.</p>
<p>Callback functions must satisfy the following signature:</p>
<pre><code class="language-c">typedef void (*napi_threadsafe_function_call_js)(napi_env env,
                                                 napi_value js_callback,
                                                 void* context,
                                                 void* data);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment to use for API calls, or <code>NULL</code> if the thread-safe
function is being torn down and <code>data</code> may need to be freed.</li>
<li><code>[in] js_callback</code>: The JavaScript function to call, or <code>NULL</code> if the
thread-safe function is being torn down and <code>data</code> may need to be freed. It
may also be <code>NULL</code> if the thread-safe function was created without
<code>js_callback</code>.</li>
<li><code>[in] context</code>: The optional data with which the thread-safe function was
created.</li>
<li><code>[in] data</code>: Data created by the secondary thread. It is the responsibility of
the callback to convert this native data to JavaScript values (with N-API
functions) that can be passed as parameters when <code>js_callback</code> is invoked.
This pointer is managed entirely by the threads and this callback. Thus this
callback should free the data.</li>
</ul>
<h2>Error handling<span><a class="mark" href="#n_api_error_handling" id="n_api_error_handling">#</a></span></h2>
<p>N-API uses both return values and JavaScript exceptions for error handling.
The following sections explain the approach for each case.</p>
<h3>Return values<span><a class="mark" href="#n_api_return_values" id="n_api_return_values">#</a></span></h3>
<p>All of the N-API functions share the same error handling pattern. The
return type of all API functions is <code>napi_status</code>.</p>
<p>The return value will be <code>napi_ok</code> if the request was successful and
no uncaught JavaScript exception was thrown. If an error occurred AND
an exception was thrown, the <code>napi_status</code> value for the error
will be returned. If an exception was thrown, and no error occurred,
<code>napi_pending_exception</code> will be returned.</p>
<p>In cases where a return value other than <code>napi_ok</code> or
<code>napi_pending_exception</code> is returned, <a href="#n_api_napi_is_exception_pending"><code>napi_is_exception_pending</code></a>
must be called to check if an exception is pending.
See the section on exceptions for more details.</p>
<p>The full set of possible <code>napi_status</code> values is defined
in <code>napi_api_types.h</code>.</p>
<p>The <code>napi_status</code> return value provides a VM-independent representation of
the error which occurred. In some cases it is useful to be able to get
more detailed information, including a string representing the error as well as
VM (engine)-specific information.</p>
<p>In order to retrieve this information <a href="#n_api_napi_get_last_error_info"><code>napi_get_last_error_info</code></a>
is provided which returns a <code>napi_extended_error_info</code> structure.
The format of the <code>napi_extended_error_info</code> structure is as follows:</p>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">typedef struct napi_extended_error_info {
  const char* error_message;
  void* engine_reserved;
  uint32_t engine_error_code;
  napi_status error_code;
};
</code></pre>
<ul>
<li><code>error_message</code>: Textual representation of the error that occurred.</li>
<li><code>engine_reserved</code>: Opaque handle reserved for engine use only.</li>
<li><code>engine_error_code</code>: VM specific error code.</li>
<li><code>error_code</code>: n-api status code for the last error.</li>
</ul>
<p><a href="#n_api_napi_get_last_error_info"><code>napi_get_last_error_info</code></a> returns the information for the last
N-API call that was made.</p>
<p>Do not rely on the content or format of any of the extended information as it
is not subject to SemVer and may change at any time. It is intended only for
logging purposes.</p>
<h4>napi_get_last_error_info<span><a class="mark" href="#n_api_napi_get_last_error_info" id="n_api_napi_get_last_error_info">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status
napi_get_last_error_info(napi_env env,
                         const napi_extended_error_info** result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: The <code>napi_extended_error_info</code> structure with more
information about the error.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API retrieves a <code>napi_extended_error_info</code> structure with information
about the last error that occurred.</p>
<p>The content of the <code>napi_extended_error_info</code> returned is only valid up until
an n-api function is called on the same <code>env</code>.</p>
<p>Do not rely on the content or format of any of the extended information as it
is not subject to SemVer and may change at any time. It is intended only for
logging purposes.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h3>Exceptions<span><a class="mark" href="#n_api_exceptions" id="n_api_exceptions">#</a></span></h3>
<p>Any N-API function call may result in a pending JavaScript exception. This is
the case for any of the API functions, even those that may not cause the
execution of JavaScript.</p>
<p>If the <code>napi_status</code> returned by a function is <code>napi_ok</code> then no
exception is pending and no additional action is required. If the
<code>napi_status</code> returned is anything other than <code>napi_ok</code> or
<code>napi_pending_exception</code>, in order to try to recover and continue
instead of simply returning immediately, <a href="#n_api_napi_is_exception_pending"><code>napi_is_exception_pending</code></a>
must be called in order to determine if an exception is pending or not.</p>
<p>In many cases when an N-API function is called and an exception is
already pending, the function will return immediately with a
<code>napi_status</code> of <code>napi_pending_exception</code>. However, this is not the case
for all functions. N-API allows a subset of the functions to be
called to allow for some minimal cleanup before returning to JavaScript.
In that case, <code>napi_status</code> will reflect the status for the function. It
will not reflect previous pending exceptions. To avoid confusion, check
the error status after every function call.</p>
<p>When an exception is pending one of two approaches can be employed.</p>
<p>The first approach is to do any appropriate cleanup and then return so that
execution will return to JavaScript. As part of the transition back to
JavaScript, the exception will be thrown at the point in the JavaScript
code where the native method was invoked. The behavior of most N-API calls
is unspecified while an exception is pending, and many will simply return
<code>napi_pending_exception</code>, so do as little as possible and then return to
JavaScript where the exception can be handled.</p>
<p>The second approach is to try to handle the exception. There will be cases
where the native code can catch the exception, take the appropriate action,
and then continue. This is only recommended in specific cases
where it is known that the exception can be safely handled. In these
cases <a href="#n_api_napi_get_and_clear_last_exception"><code>napi_get_and_clear_last_exception</code></a> can be used to get and
clear the exception. On success, result will contain the handle to
the last JavaScript <code>Object</code> thrown. If it is determined, after
retrieving the exception, the exception cannot be handled after all
it can be re-thrown it with <a href="#n_api_napi_throw"><code>napi_throw</code></a> where error is the
JavaScript <code>Error</code> object to be thrown.</p>
<p>The following utility functions are also available in case native code
needs to throw an exception or determine if a <code>napi_value</code> is an instance
of a JavaScript <code>Error</code> object: <a href="#n_api_napi_throw_error"><code>napi_throw_error</code></a>,
<a href="#n_api_napi_throw_type_error"><code>napi_throw_type_error</code></a>, <a href="#n_api_napi_throw_range_error"><code>napi_throw_range_error</code></a> and
<a href="#n_api_napi_is_error"><code>napi_is_error</code></a>.</p>
<p>The following utility functions are also available in case native
code needs to create an <code>Error</code> object: <a href="#n_api_napi_create_error"><code>napi_create_error</code></a>,
<a href="#n_api_napi_create_type_error"><code>napi_create_type_error</code></a>, and <a href="#n_api_napi_create_range_error"><code>napi_create_range_error</code></a>,
where result is the <code>napi_value</code> that refers to the newly created
JavaScript <code>Error</code> object.</p>
<p>The Node.js project is adding error codes to all of the errors
generated internally. The goal is for applications to use these
error codes for all error checking. The associated error messages
will remain, but will only be meant to be used for logging and
display with the expectation that the message can change without
SemVer applying. In order to support this model with N-API, both
in internal functionality and for module specific functionality
(as its good practice), the <code>throw_</code> and <code>create_</code> functions
take an optional code parameter which is the string for the code
to be added to the error object. If the optional parameter is <code>NULL</code>
then no code will be associated with the error. If a code is provided,
the name associated with the error is also updated to be:</p>
<pre><code class="language-text">originalName [code]
</code></pre>
<p>where <code>originalName</code> is the original name associated with the error
and <code>code</code> is the code that was provided. For example, if the code
is <code>'ERR_ERROR_1'</code> and a <code>TypeError</code> is being created the name will be:</p>
<pre><code class="language-text">TypeError [ERR_ERROR_1]
</code></pre>
<h4>napi_throw<span><a class="mark" href="#n_api_napi_throw" id="n_api_napi_throw">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_throw(napi_env env, napi_value error);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] error</code>: The JavaScript value to be thrown.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API throws the JavaScript value provided.</p>
<h4>napi_throw_error<span><a class="mark" href="#n_api_napi_throw_error" id="n_api_napi_throw_error">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_throw_error(napi_env env,
                                         const char* code,
                                         const char* msg);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional error code to be set on the error.</li>
<li><code>[in] msg</code>: C string representing the text to be associated with the error.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API throws a JavaScript <code>Error</code> with the text provided.</p>
<h4>napi_throw_type_error<span><a class="mark" href="#n_api_napi_throw_type_error" id="n_api_napi_throw_type_error">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_throw_type_error(napi_env env,
                                              const char* code,
                                              const char* msg);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional error code to be set on the error.</li>
<li><code>[in] msg</code>: C string representing the text to be associated with the error.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API throws a JavaScript <code>TypeError</code> with the text provided.</p>
<h4>napi_throw_range_error<span><a class="mark" href="#n_api_napi_throw_range_error" id="n_api_napi_throw_range_error">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_throw_range_error(napi_env env,
                                               const char* code,
                                               const char* msg);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional error code to be set on the error.</li>
<li><code>[in] msg</code>: C string representing the text to be associated with the error.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API throws a JavaScript <code>RangeError</code> with the text provided.</p>
<h4>napi_is_error<span><a class="mark" href="#n_api_napi_is_error" id="n_api_napi_is_error">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_is_error(napi_env env,
                                      napi_value value,
                                      bool* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The <code>napi_value</code> to be checked.</li>
<li><code>[out] result</code>: Boolean value that is set to true if <code>napi_value</code> represents
an error, false otherwise.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API queries a <code>napi_value</code> to check if it represents an error object.</p>
<h4>napi_create_error<span><a class="mark" href="#n_api_napi_create_error" id="n_api_napi_create_error">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_create_error(napi_env env,
                                          napi_value code,
                                          napi_value msg,
                                          napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be
associated with the error.</li>
<li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>String</code> to be used as
the message for the <code>Error</code>.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns a JavaScript <code>Error</code> with the text provided.</p>
<h4>napi_create_type_error<span><a class="mark" href="#n_api_napi_create_type_error" id="n_api_napi_create_type_error">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_create_type_error(napi_env env,
                                               napi_value code,
                                               napi_value msg,
                                               napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be
associated with the error.</li>
<li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>String</code> to be used as
the message for the <code>Error</code>.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns a JavaScript <code>TypeError</code> with the text provided.</p>
<h4>napi_create_range_error<span><a class="mark" href="#n_api_napi_create_range_error" id="n_api_napi_create_range_error">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_create_range_error(napi_env env,
                                                napi_value code,
                                                napi_value msg,
                                                napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] code</code>: Optional <code>napi_value</code> with the string for the error code to be
associated with the error.</li>
<li><code>[in] msg</code>: <code>napi_value</code> that references a JavaScript <code>String</code> to be used as
the message for the <code>Error</code>.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the error created.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns a JavaScript <code>RangeError</code> with the text provided.</p>
<h4>napi_get_and_clear_last_exception<span><a class="mark" href="#n_api_napi_get_and_clear_last_exception" id="n_api_napi_get_and_clear_last_exception">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_and_clear_last_exception(napi_env env,
                                              napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: The exception if one is pending, <code>NULL</code> otherwise.</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>
<h4>napi_is_exception_pending<span><a class="mark" href="#n_api_napi_is_exception_pending" id="n_api_napi_is_exception_pending">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_is_exception_pending(napi_env env, bool* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: Boolean value that is set to true if an exception is pending.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h4>napi_fatal_exception<span><a class="mark" href="#n_api_napi_fatal_exception" id="n_api_napi_fatal_exception">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.10.0</span>
<span>N-API version: 3</span>
</div>
<pre><code class="language-c">napi_status napi_fatal_exception(napi_env env, napi_value err);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] err</code>: The error that is passed to <code>'uncaughtException'</code>.</li>
</ul>
<p>Trigger an <code>'uncaughtException'</code> in JavaScript. Useful if an async
callback throws an exception with no way to recover.</p>
<h3>Fatal errors<span><a class="mark" href="#n_api_fatal_errors" id="n_api_fatal_errors">#</a></span></h3>
<p>In the event of an unrecoverable error in a native module, a fatal error can be
thrown to immediately terminate the process.</p>
<h4>napi_fatal_error<span><a class="mark" href="#n_api_napi_fatal_error" id="n_api_napi_fatal_error">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_NO_RETURN void napi_fatal_error(const char* location,
                                                 size_t location_len,
                                                 const char* message,
                                                 size_t message_len);
</code></pre>
<ul>
<li><code>[in] location</code>: Optional location at which the error occurred.</li>
<li><code>[in] location_len</code>: The length of the location in bytes, or
<code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li>
<li><code>[in] message</code>: The message associated with the error.</li>
<li><code>[in] message_len</code>: The length of the message in bytes, or <code>NAPI_AUTO_LENGTH</code>
if it is null-terminated.</li>
</ul>
<p>The function call does not return, the process will be terminated.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h2>Object lifetime management<span><a class="mark" href="#n_api_object_lifetime_management" id="n_api_object_lifetime_management">#</a></span></h2>
<p>As N-API calls are made, handles to objects in the heap for the underlying
VM may be returned as <code>napi_values</code>. These handles must hold the
objects 'live' until they are no longer required by the native code,
otherwise the objects could be collected before the native code was
finished using them.</p>
<p>As object handles are returned they are associated with a
'scope'. The lifespan for the default scope is tied to the lifespan
of the native method call. The result is that, by default, handles
remain valid and the objects associated with these handles will be
held live for the lifespan of the native method call.</p>
<p>In many cases, however, it is necessary that the handles remain valid for
either a shorter or longer lifespan than that of the native method.
The sections which follow describe the N-API functions that can be used
to change the handle lifespan from the default.</p>
<h3>Making handle lifespan shorter than that of the native method<span><a class="mark" href="#n_api_making_handle_lifespan_shorter_than_that_of_the_native_method" id="n_api_making_handle_lifespan_shorter_than_that_of_the_native_method">#</a></span></h3>
<p>It is often necessary to make the lifespan of handles shorter than
the lifespan of a native method. For example, consider a native method
that has a loop which iterates through the elements in a large array:</p>
<pre><code class="language-c">for (int i = 0; i &#x3C; 1000000; i++) {
  napi_value result;
  napi_status status = napi_get_element(env, object, i, &#x26;result);
  if (status != napi_ok) {
    break;
  }
  // do something with element
}
</code></pre>
<p>This would result in a large number of handles being created, consuming
substantial resources. In addition, even though the native code could only
use the most recent handle, all of the associated objects would also be
kept alive since they all share the same scope.</p>
<p>To handle this case, N-API provides the ability to establish a new 'scope' to
which newly created handles will be associated. Once those handles
are no longer required, the scope can be 'closed' and any handles associated
with the scope are invalidated. The methods available to open/close scopes are
<a href="#n_api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and <a href="#n_api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a>.</p>
<p>N-API only supports a single nested hierarchy of scopes. There is only one
active scope at any time, and all new handles will be associated with that
scope while it is active. Scopes must be closed in the reverse order from
which they are opened. In addition, all scopes created within a native method
must be closed before returning from that method.</p>
<p>Taking the earlier example, adding calls to <a href="#n_api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and
<a href="#n_api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a> would ensure that at most a single handle
is valid throughout the execution of the loop:</p>
<pre><code class="language-c">for (int i = 0; i &#x3C; 1000000; i++) {
  napi_handle_scope scope;
  napi_status status = napi_open_handle_scope(env, &#x26;scope);
  if (status != napi_ok) {
    break;
  }
  napi_value result;
  status = napi_get_element(env, object, i, &#x26;result);
  if (status != napi_ok) {
    break;
  }
  // do something with element
  status = napi_close_handle_scope(env, scope);
  if (status != napi_ok) {
    break;
  }
}
</code></pre>
<p>When nesting scopes, there are cases where a handle from an
inner scope needs to live beyond the lifespan of that scope. N-API supports an
'escapable scope' in order to support this case. An escapable scope
allows one handle to be 'promoted' so that it 'escapes' the
current scope and the lifespan of the handle changes from the current
scope to that of the outer scope.</p>
<p>The methods available to open/close escapable scopes are
<a href="#n_api_napi_open_escapable_handle_scope"><code>napi_open_escapable_handle_scope</code></a> and
<a href="#n_api_napi_close_escapable_handle_scope"><code>napi_close_escapable_handle_scope</code></a>.</p>
<p>The request to promote a handle is made through <a href="#n_api_napi_escape_handle"><code>napi_escape_handle</code></a> which
can only be called once.</p>
<h4>napi_open_handle_scope<span><a class="mark" href="#n_api_napi_open_handle_scope" id="n_api_napi_open_handle_scope">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_open_handle_scope(napi_env env,
                                               napi_handle_scope* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the new scope.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API opens a new scope.</p>
<h4>napi_close_handle_scope<span><a class="mark" href="#n_api_napi_close_handle_scope" id="n_api_napi_close_handle_scope">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_close_handle_scope(napi_env env,
                                                napi_handle_scope scope);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] scope</code>: <code>napi_value</code> representing the scope to be closed.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API closes the scope passed in. Scopes must be closed in the
reverse order from which they were created.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h4>napi_open_escapable_handle_scope<span><a class="mark" href="#n_api_napi_open_escapable_handle_scope" id="n_api_napi_open_escapable_handle_scope">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
    napi_open_escapable_handle_scope(napi_env env,
                                     napi_handle_scope* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the new scope.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API opens a new scope from which one object can be promoted
to the outer scope.</p>
<h4>napi_close_escapable_handle_scope<span><a class="mark" href="#n_api_napi_close_escapable_handle_scope" id="n_api_napi_close_escapable_handle_scope">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
    napi_close_escapable_handle_scope(napi_env env,
                                      napi_handle_scope scope);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] scope</code>: <code>napi_value</code> representing the scope to be closed.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API closes the scope passed in. Scopes must be closed in the
reverse order from which they were created.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h4>napi_escape_handle<span><a class="mark" href="#n_api_napi_escape_handle" id="n_api_napi_escape_handle">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_escape_handle(napi_env env,
                               napi_escapable_handle_scope scope,
                               napi_value escapee,
                               napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] scope</code>: <code>napi_value</code> representing the current scope.</li>
<li><code>[in] escapee</code>: <code>napi_value</code> representing the JavaScript <code>Object</code> to be
escaped.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the handle to the escaped <code>Object</code>
in the outer scope.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API promotes the handle to the JavaScript object so that it is valid
for the lifetime of the outer scope. It can only be called once per scope.
If it is called more than once an error will be returned.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h3>References to objects with a lifespan longer than that of the native method<span><a class="mark" href="#n_api_references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method" id="n_api_references_to_objects_with_a_lifespan_longer_than_that_of_the_native_method">#</a></span></h3>
<p>In some cases an addon will need to be able to create and reference objects
with a lifespan longer than that of a single native method invocation. For
example, to create a constructor and later use that constructor
in a request to creates instances, it must be possible to reference
the constructor object across many different instance creation requests. This
would not be possible with a normal handle returned as a <code>napi_value</code> as
described in the earlier section. The lifespan of a normal handle is
managed by scopes and all scopes must be closed before the end of a native
method.</p>
<p>N-API provides methods to create persistent references to an object.
Each persistent reference has an associated count with a value of 0
or higher. The count determines if the reference will keep
the corresponding object live. References with a count of 0 do not
prevent the object from being collected and are often called 'weak'
references. Any count greater than 0 will prevent the object
from being collected.</p>
<p>References can be created with an initial reference count. The count can
then be modified through <a href="#n_api_napi_reference_ref"><code>napi_reference_ref</code></a> and
<a href="#n_api_napi_reference_unref"><code>napi_reference_unref</code></a>. If an object is collected while the count
for a reference is 0, all subsequent calls to
get the object associated with the reference <a href="#n_api_napi_get_reference_value"><code>napi_get_reference_value</code></a>
will return <code>NULL</code> for the returned <code>napi_value</code>. An attempt to call
<a href="#n_api_napi_reference_ref"><code>napi_reference_ref</code></a> for a reference whose object has been collected
will result in an error.</p>
<p>References must be deleted once they are no longer required by the addon. When
a reference is deleted it will no longer prevent the corresponding object from
being collected. Failure to delete a persistent reference will result in
a 'memory leak' with both the native memory for the persistent reference and
the corresponding object on the heap being retained forever.</p>
<p>There can be multiple persistent references created which refer to the same
object, each of which will either keep the object live or not based on its
individual count.</p>
<h4>napi_create_reference<span><a class="mark" href="#n_api_napi_create_reference" id="n_api_napi_create_reference">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_create_reference(napi_env env,
                                              napi_value value,
                                              uint32_t initial_refcount,
                                              napi_ref* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing the <code>Object</code> to which we want a
reference.</li>
<li><code>[in] initial_refcount</code>: Initial reference count for the new reference.</li>
<li><code>[out] result</code>: <code>napi_ref</code> pointing to the new reference.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API create a new reference with the specified reference count
to the <code>Object</code> passed in.</p>
<h4>napi_delete_reference<span><a class="mark" href="#n_api_napi_delete_reference" id="n_api_napi_delete_reference">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_delete_reference(napi_env env, napi_ref ref);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] ref</code>: <code>napi_ref</code> to be deleted.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API deletes the reference passed in.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h4>napi_reference_ref<span><a class="mark" href="#n_api_napi_reference_ref" id="n_api_napi_reference_ref">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_reference_ref(napi_env env,
                                           napi_ref ref,
                                           uint32_t* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] ref</code>: <code>napi_ref</code> for which the reference count will be incremented.</li>
<li><code>[out] result</code>: The new reference count.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API increments the reference count for the reference
passed in and returns the resulting reference count.</p>
<h4>napi_reference_unref<span><a class="mark" href="#n_api_napi_reference_unref" id="n_api_napi_reference_unref">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_reference_unref(napi_env env,
                                             napi_ref ref,
                                             uint32_t* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] ref</code>: <code>napi_ref</code> for which the reference count will be decremented.</li>
<li><code>[out] result</code>: The new reference count.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API decrements the reference count for the reference
passed in and returns the resulting reference count.</p>
<h4>napi_get_reference_value<span><a class="mark" href="#n_api_napi_get_reference_value" id="n_api_napi_get_reference_value">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_get_reference_value(napi_env env,
                                                 napi_ref ref,
                                                 napi_value* result);
</code></pre>
<p>the <code>napi_value passed</code> in or out of these methods is a handle to the
object to which the reference is related.</p>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] ref</code>: <code>napi_ref</code> for which we requesting the corresponding <code>Object</code>.</li>
<li><code>[out] result</code>: The <code>napi_value</code> for the <code>Object</code> referenced by the
<code>napi_ref</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>If still valid, this API returns the <code>napi_value</code> representing the
JavaScript <code>Object</code> associated with the <code>napi_ref</code>. Otherwise, result
will be <code>NULL</code>.</p>
<h3>Cleanup on exit of the current Node.js instance<span><a class="mark" href="#n_api_cleanup_on_exit_of_the_current_node_js_instance" id="n_api_cleanup_on_exit_of_the_current_node_js_instance">#</a></span></h3>
<p>While a Node.js process typically releases all its resources when exiting,
embedders of Node.js, or future Worker support, may require addons to register
clean-up hooks that will be run once the current Node.js instance exits.</p>
<p>N-API provides functions for registering and un-registering such callbacks.
When those callbacks are run, all resources that are being held by the addon
should be freed up.</p>
<h4>napi_add_env_cleanup_hook<span><a class="mark" href="#n_api_napi_add_env_cleanup_hook" id="n_api_napi_add_env_cleanup_hook">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.2.0</span>
<span>N-API version: 3</span>
</div>
<pre><code class="language-c">NODE_EXTERN napi_status napi_add_env_cleanup_hook(napi_env env,
                                                  void (*fun)(void* arg),
                                                  void* arg);
</code></pre>
<p>Registers <code>fun</code> as a function to be run with the <code>arg</code> parameter once the
current Node.js environment exits.</p>
<p>A function can safely be specified multiple times with different
<code>arg</code> values. In that case, it will be called multiple times as well.
Providing the same <code>fun</code> and <code>arg</code> values multiple times is not allowed
and will lead the process to abort.</p>
<p>The hooks will be called in reverse order, i.e. the most recently added one
will be called first.</p>
<p>Removing this hook can be done by using <code>napi_remove_env_cleanup_hook</code>.
Typically, that happens when the resource for which this hook was added
is being torn down anyway.</p>
<h4>napi_remove_env_cleanup_hook<span><a class="mark" href="#n_api_napi_remove_env_cleanup_hook" id="n_api_napi_remove_env_cleanup_hook">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.2.0</span>
<span>N-API version: 3</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_remove_env_cleanup_hook(napi_env env,
                                                     void (*fun)(void* arg),
                                                     void* arg);
</code></pre>
<p>Unregisters <code>fun</code> as a function to be run with the <code>arg</code> parameter once the
current Node.js environment exits. Both the argument and the function value
need to be exact matches.</p>
<p>The function must have originally been registered
with <code>napi_add_env_cleanup_hook</code>, otherwise the process will abort.</p>
<h2>Module registration<span><a class="mark" href="#n_api_module_registration" id="n_api_module_registration">#</a></span></h2>
<p>N-API modules are registered in a manner similar to other modules
except that instead of using the <code>NODE_MODULE</code> macro the following
is used:</p>
<pre><code class="language-c">NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
</code></pre>
<p>The next difference is the signature for the <code>Init</code> method. For a N-API
module it is as follows:</p>
<pre><code class="language-c">napi_value Init(napi_env env, napi_value exports);
</code></pre>
<p>The return value from <code>Init</code> is treated as the <code>exports</code> object for the module.
The <code>Init</code> method is passed an empty object via the <code>exports</code> parameter as a
convenience. If <code>Init</code> returns <code>NULL</code>, the parameter passed as <code>exports</code> is
exported by the module. N-API modules cannot modify the <code>module</code> object but can
specify anything as the <code>exports</code> property of the module.</p>
<p>To add the method <code>hello</code> as a function so that it can be called as a method
provided by the addon:</p>
<pre><code class="language-c">napi_value Init(napi_env env, napi_value exports) {
  napi_status status;
  napi_property_descriptor desc =
    {"hello", NULL, Method, NULL, NULL, NULL, napi_default, NULL};
  status = napi_define_properties(env, exports, 1, &#x26;desc);
  if (status != napi_ok) return NULL;
  return exports;
}
</code></pre>
<p>To set a function to be returned by the <code>require()</code> for the addon:</p>
<pre><code class="language-c">napi_value Init(napi_env env, napi_value exports) {
  napi_value method;
  napi_status status;
  status = napi_create_function(env, "exports", NAPI_AUTO_LENGTH, Method, NULL, &#x26;method);
  if (status != napi_ok) return NULL;
  return method;
}
</code></pre>
<p>To define a class so that new instances can be created (often used with
<a href="#n_api_object_wrap">Object wrap</a>):</p>
<pre><code class="language-c">// NOTE: partial example, not all referenced code is included
napi_value Init(napi_env env, napi_value exports) {
  napi_status status;
  napi_property_descriptor properties[] = {
    { "value", NULL, NULL, GetValue, SetValue, NULL, napi_default, NULL },
    DECLARE_NAPI_METHOD("plusOne", PlusOne),
    DECLARE_NAPI_METHOD("multiply", Multiply),
  };

  napi_value cons;
  status =
      napi_define_class(env, "MyObject", New, NULL, 3, properties, &#x26;cons);
  if (status != napi_ok) return NULL;

  status = napi_create_reference(env, cons, 1, &#x26;constructor);
  if (status != napi_ok) return NULL;

  status = napi_set_named_property(env, exports, "MyObject", cons);
  if (status != napi_ok) return NULL;

  return exports;
}
</code></pre>
<p>If the module will be loaded multiple times during the lifetime of the Node.js
process, use the <code>NAPI_MODULE_INIT</code> macro to initialize the module:</p>
<pre><code class="language-c">NAPI_MODULE_INIT() {
  napi_value answer;
  napi_status result;

  status = napi_create_int64(env, 42, &#x26;answer);
  if (status != napi_ok) return NULL;

  status = napi_set_named_property(env, exports, "answer", answer);
  if (status != napi_ok) return NULL;

  return exports;
}
</code></pre>
<p>This macro includes <code>NAPI_MODULE</code>, and declares an <code>Init</code> function with a
special name and with visibility beyond the addon. This will allow Node.js to
initialize the module even if it is loaded multiple times.</p>
<p>There are a few design considerations when declaring a module that may be loaded
multiple times. The documentation of <a href="#addons_context_aware_addons">context-aware addons</a> provides more
details.</p>
<p>The variables <code>env</code> and <code>exports</code> will be available inside the function body
following the macro invocation.</p>
<p>For more details on setting properties on objects, see the section on
<a href="#n_api_working_with_javascript_properties">Working with JavaScript properties</a>.</p>
<p>For more details on building addon modules in general, refer to the existing
API.</p>
<h2>Working with JavaScript values<span><a class="mark" href="#n_api_working_with_javascript_values" id="n_api_working_with_javascript_values">#</a></span></h2>
<p>N-API exposes a set of APIs to create all types of JavaScript values.
Some of these types are documented under <a href="https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values">Section 6</a>
of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p>
<p>Fundamentally, these APIs are used to do one of the following:</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_key_collection_mode<span><a class="mark" href="#n_api_napi_key_collection_mode" id="n_api_napi_key_collection_mode">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">typedef enum {
  napi_key_include_prototypes,
  napi_key_own_only
} napi_key_collection_mode;
</code></pre>
<p>Describes the <code>Keys/Properties</code> filter enums:</p>
<p><code>napi_key_collection_mode</code> limits the range of collected properties.</p>
<p><code>napi_key_own_only</code> limits the collected properties to the given
object only. <code>napi_key_include_prototypes</code> will include all keys
of the objects's prototype chain as well.</p>
<h4>napi_key_filter<span><a class="mark" href="#n_api_napi_key_filter" id="n_api_napi_key_filter">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">typedef enum {
  napi_key_all_properties = 0,
  napi_key_writable = 1,
  napi_key_enumerable = 1 &#x3C;&#x3C; 1,
  napi_key_configurable = 1 &#x3C;&#x3C; 2,
  napi_key_skip_strings = 1 &#x3C;&#x3C; 3,
  napi_key_skip_symbols = 1 &#x3C;&#x3C; 4
} napi_key_filter;
</code></pre>
<p>Property filter bits. They can be or'ed to build a composite filter.</p>
<h4>napi_key_conversion<span><a class="mark" href="#n_api_napi_key_conversion" id="n_api_napi_key_conversion">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">typedef enum {
  napi_key_keep_numbers,
  napi_key_numbers_to_strings
} napi_key_conversion;
</code></pre>
<p><code>napi_key_numbers_to_strings</code> will convert integer indices to
strings. <code>napi_key_keep_numbers</code> will return numbers for integer
indices.</p>
<h4>napi_valuetype<span><a class="mark" href="#n_api_napi_valuetype" id="n_api_napi_valuetype">#</a></span></h4>
<pre><code class="language-c">typedef enum {
  // ES6 types (corresponds to typeof)
  napi_undefined,
  napi_null,
  napi_boolean,
  napi_number,
  napi_string,
  napi_symbol,
  napi_object,
  napi_function,
  napi_external,
  napi_bigint,
} napi_valuetype;
</code></pre>
<p>Describes the type of a <code>napi_value</code>. This generally corresponds to the types
described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types">Section 6.1</a> of the ECMAScript Language Specification.
In addition to types in that section, <code>napi_valuetype</code> can also represent
<code>Function</code>s and <code>Object</code>s with external data.</p>
<p>A JavaScript value of type <code>napi_external</code> appears in JavaScript as a plain
object such that no properties can be set on it, and no prototype.</p>
<h4>napi_typedarray_type<span><a class="mark" href="#n_api_napi_typedarray_type" id="n_api_napi_typedarray_type">#</a></span></h4>
<pre><code class="language-c">typedef enum {
  napi_int8_array,
  napi_uint8_array,
  napi_uint8_clamped_array,
  napi_int16_array,
  napi_uint16_array,
  napi_int32_array,
  napi_uint32_array,
  napi_float32_array,
  napi_float64_array,
  napi_bigint64_array,
  napi_biguint64_array,
} napi_typedarray_type;
</code></pre>
<p>This represents the underlying binary scalar datatype of the <code>TypedArray</code>.
Elements of this enum correspond to
<a href="https://tc39.github.io/ecma262/#sec-typedarray-objects">Section 22.2</a> of the <a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p>
<h3>Object creation functions<span><a class="mark" href="#n_api_object_creation_functions" id="n_api_object_creation_functions">#</a></span></h3>
<h4>napi_create_array<span><a class="mark" href="#n_api_napi_create_array" id="n_api_napi_create_array">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_array(napi_env env, napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Array</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns an N-API value corresponding to a JavaScript <code>Array</code> type.
JavaScript arrays are described in
<a href="https://tc39.github.io/ecma262/#sec-array-objects">Section 22.1</a> of the ECMAScript Language Specification.</p>
<h4>napi_create_array_with_length<span><a class="mark" href="#n_api_napi_create_array_with_length" id="n_api_napi_create_array_with_length">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_array_with_length(napi_env env,
                                          size_t length,
                                          napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] length</code>: The initial length of the <code>Array</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Array</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns an N-API value corresponding to a JavaScript <code>Array</code> type.
The <code>Array</code>'s length property is set to the passed-in length parameter.
However, the underlying buffer is not guaranteed to be pre-allocated by the VM
when the array is created. That behavior is left to the underlying VM
implementation. If the buffer must be a contiguous block of memory that can be
directly read and/or written via C, consider using
<a href="#n_api_napi_create_external_arraybuffer"><code>napi_create_external_arraybuffer</code></a>.</p>
<p>JavaScript arrays are described in
<a href="https://tc39.github.io/ecma262/#sec-array-objects">Section 22.1</a> of the ECMAScript Language Specification.</p>
<h4>napi_create_arraybuffer<span><a class="mark" href="#n_api_napi_create_arraybuffer" id="n_api_napi_create_arraybuffer">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_arraybuffer(napi_env env,
                                    size_t byte_length,
                                    void** data,
                                    napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] length</code>: The length in bytes of the array buffer to create.</li>
<li><code>[out] data</code>: Pointer to the underlying byte buffer of the <code>ArrayBuffer</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>ArrayBuffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns an N-API value corresponding to a JavaScript <code>ArrayBuffer</code>.
<code>ArrayBuffer</code>s are used to represent fixed-length binary data buffers. They are
normally used as a backing-buffer for <code>TypedArray</code> objects.
The <code>ArrayBuffer</code> allocated will have an underlying byte buffer whose size is
determined by the <code>length</code> parameter that's passed in.
The underlying buffer is optionally returned back to the caller in case the
caller wants to directly manipulate the buffer. This buffer can only be
written to directly from native code. To write to this buffer from JavaScript,
a typed array or <code>DataView</code> object would need to be created.</p>
<p>JavaScript <code>ArrayBuffer</code> objects are described in
<a href="https://tc39.github.io/ecma262/#sec-arraybuffer-objects">Section 24.1</a> of the ECMAScript Language Specification.</p>
<h4>napi_create_buffer<span><a class="mark" href="#n_api_napi_create_buffer" id="n_api_napi_create_buffer">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_buffer(napi_env env,
                               size_t size,
                               void** data,
                               napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] size</code>: Size in bytes of the underlying buffer.</li>
<li><code>[out] data</code>: Raw pointer to the underlying buffer.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a <code>node::Buffer</code> object. While this is still a
fully-supported data structure, in most cases using a <code>TypedArray</code> will suffice.</p>
<h4>napi_create_buffer_copy<span><a class="mark" href="#n_api_napi_create_buffer_copy" id="n_api_napi_create_buffer_copy">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_buffer_copy(napi_env env,
                                    size_t length,
                                    const void* data,
                                    void** result_data,
                                    napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] size</code>: Size in bytes of the input buffer (should be the same as the size
of the new buffer).</li>
<li><code>[in] data</code>: Raw pointer to the underlying buffer to copy from.</li>
<li><code>[out] result_data</code>: Pointer to the new <code>Buffer</code>'s underlying data buffer.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a <code>node::Buffer</code> object and initializes it with data copied
from the passed-in buffer. While this is still a fully-supported data
structure, in most cases using a <code>TypedArray</code> will suffice.</p>
<h4>napi_create_date<span><a class="mark" href="#n_api_napi_create_date" id="n_api_napi_create_date">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.11.0</span>
<span>N-API version: 5</span>
</div>
<pre><code class="language-c">napi_status napi_create_date(napi_env env,
                             double time,
                             napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] time</code>: ECMAScript time value in milliseconds since 01 January, 1970 UTC.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Date</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API does not observe leap seconds; they are ignored, as
ECMAScript aligns with POSIX time specification.</p>
<p>This API allocates a JavaScript <code>Date</code> object.</p>
<p>JavaScript <code>Date</code> objects are described in
<a href="https://tc39.github.io/ecma262/#sec-date-objects">Section 20.3</a> of the ECMAScript Language Specification.</p>
<h4>napi_create_external<span><a class="mark" href="#n_api_napi_create_external" id="n_api_napi_create_external">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_external(napi_env env,
                                 void* data,
                                 napi_finalize finalize_cb,
                                 void* finalize_hint,
                                 napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] data</code>: Raw pointer to the external data.</li>
<li><code>[in] finalize_cb</code>: Optional callback to call when the external value is being
collected.</li>
<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
collection.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing an external value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a JavaScript value with external data attached to it. This
is used to pass external data through JavaScript code, so it can be retrieved
later by native code using <a href="#n_api_napi_get_value_external"><code>napi_get_value_external</code></a>.</p>
<p>The API adds a <code>napi_finalize</code> callback which will be called when the JavaScript
object just created is ready for garbage collection. It is similar to
<code>napi_wrap()</code> except that:</p>
<ul>
<li>the native data cannot be retrieved later using <code>napi_unwrap()</code>,</li>
<li>nor can it be removed later using <code>napi_remove_wrap()</code>, and</li>
<li>the object created by the API can be used with <code>napi_wrap()</code>.</li>
</ul>
<p>The created value is not an object, and therefore does not support additional
properties. It is considered a distinct value type: calling <code>napi_typeof()</code> with
an external value yields <code>napi_external</code>.</p>
<h4>napi_create_external_arraybuffer<span><a class="mark" href="#n_api_napi_create_external_arraybuffer" id="n_api_napi_create_external_arraybuffer">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status
napi_create_external_arraybuffer(napi_env env,
                                 void* external_data,
                                 size_t byte_length,
                                 napi_finalize finalize_cb,
                                 void* finalize_hint,
                                 napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] external_data</code>: Pointer to the underlying byte buffer of the
<code>ArrayBuffer</code>.</li>
<li><code>[in] byte_length</code>: The length in bytes of the underlying buffer.</li>
<li><code>[in] finalize_cb</code>: Optional callback to call when the <code>ArrayBuffer</code> is being
collected.</li>
<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
collection.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>ArrayBuffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns an N-API value corresponding to a JavaScript <code>ArrayBuffer</code>.
The underlying byte buffer of the <code>ArrayBuffer</code> is externally allocated and
managed. The caller must ensure that the byte buffer remains valid until the
finalize callback is called.</p>
<p>The API adds a <code>napi_finalize</code> callback which will be called when the JavaScript
object just created is ready for garbage collection. It is similar to
<code>napi_wrap()</code> except that:</p>
<ul>
<li>the native data cannot be retrieved later using <code>napi_unwrap()</code>,</li>
<li>nor can it be removed later using <code>napi_remove_wrap()</code>, and</li>
<li>the object created by the API can be used with <code>napi_wrap()</code>.</li>
</ul>
<p>JavaScript <code>ArrayBuffer</code>s are described in
<a href="https://tc39.github.io/ecma262/#sec-arraybuffer-objects">Section 24.1</a> of the ECMAScript Language Specification.</p>
<h4>napi_create_external_buffer<span><a class="mark" href="#n_api_napi_create_external_buffer" id="n_api_napi_create_external_buffer">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_external_buffer(napi_env env,
                                        size_t length,
                                        void* data,
                                        napi_finalize finalize_cb,
                                        void* finalize_hint,
                                        napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] length</code>: Size in bytes of the input buffer (should be the same as the
size of the new buffer).</li>
<li><code>[in] data</code>: Raw pointer to the underlying buffer to copy from.</li>
<li><code>[in] finalize_cb</code>: Optional callback to call when the <code>ArrayBuffer</code> is being
collected.</li>
<li><code>[in] finalize_hint</code>: Optional hint to pass to the finalize callback during
collection.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a <code>node::Buffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a <code>node::Buffer</code> object and initializes it with data
backed by the passed in buffer. While this is still a fully-supported data
structure, in most cases using a <code>TypedArray</code> will suffice.</p>
<p>The API adds a <code>napi_finalize</code> callback which will be called when the JavaScript
object just created is ready for garbage collection. It is similar to
<code>napi_wrap()</code> except that:</p>
<ul>
<li>the native data cannot be retrieved later using <code>napi_unwrap()</code>,</li>
<li>nor can it be removed later using <code>napi_remove_wrap()</code>, and</li>
<li>the object created by the API can be used with <code>napi_wrap()</code>.</li>
</ul>
<p>For Node.js >=4 <code>Buffers</code> are <code>Uint8Array</code>s.</p>
<h4>napi_create_object<span><a class="mark" href="#n_api_napi_create_object" id="n_api_napi_create_object">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_object(napi_env env, napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Object</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a default JavaScript <code>Object</code>.
It is the equivalent of doing <code>new Object()</code> in JavaScript.</p>
<p>The JavaScript <code>Object</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-object-type">Section 6.1.7</a> of the
ECMAScript Language Specification.</p>
<h4>napi_create_symbol<span><a class="mark" href="#n_api_napi_create_symbol" id="n_api_napi_create_symbol">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_symbol(napi_env env,
                               napi_value description,
                               napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] description</code>: Optional <code>napi_value</code> which refers to a JavaScript
<code>String</code> to be set as the description for the symbol.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Symbol</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>Symbol</code> object from a UTF8-encoded C string.</p>
<p>The JavaScript <code>Symbol</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-symbol-objects">Section 19.4</a>
of the ECMAScript Language Specification.</p>
<h4>napi_create_typedarray<span><a class="mark" href="#n_api_napi_create_typedarray" id="n_api_napi_create_typedarray">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_typedarray(napi_env env,
                                   napi_typedarray_type type,
                                   size_t length,
                                   napi_value arraybuffer,
                                   size_t byte_offset,
                                   napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] type</code>: Scalar datatype of the elements within the <code>TypedArray</code>.</li>
<li><code>[in] length</code>: Number of elements in the <code>TypedArray</code>.</li>
<li><code>[in] arraybuffer</code>: <code>ArrayBuffer</code> underlying the typed array.</li>
<li><code>[in] byte_offset</code>: The byte offset within the <code>ArrayBuffer</code> from which to
start projecting the <code>TypedArray</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>TypedArray</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>TypedArray</code> object over an existing
<code>ArrayBuffer</code>. <code>TypedArray</code> objects provide an array-like view over an
underlying data buffer where each element has the same underlying binary scalar
datatype.</p>
<p>It's required that <code>(length * size_of_element) + byte_offset</code> should
be &#x3C;= the size in bytes of the array passed in. If not, a <code>RangeError</code> exception
is raised.</p>
<p>JavaScript <code>TypedArray</code> objects are described in
<a href="https://tc39.github.io/ecma262/#sec-typedarray-objects">Section 22.2</a> of the ECMAScript Language Specification.</p>
<h4>napi_create_dataview<span><a class="mark" href="#n_api_napi_create_dataview" id="n_api_napi_create_dataview">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_dataview(napi_env env,
                                 size_t byte_length,
                                 napi_value arraybuffer,
                                 size_t byte_offset,
                                 napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] length</code>: Number of elements in the <code>DataView</code>.</li>
<li><code>[in] arraybuffer</code>: <code>ArrayBuffer</code> underlying the <code>DataView</code>.</li>
<li><code>[in] byte_offset</code>: The byte offset within the <code>ArrayBuffer</code> from which to
start projecting the <code>DataView</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>DataView</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>DataView</code> object over an existing <code>ArrayBuffer</code>.
<code>DataView</code> objects provide an array-like view over an underlying data buffer,
but one which allows items of different size and type in the <code>ArrayBuffer</code>.</p>
<p>It is required that <code>byte_length + byte_offset</code> is less than or equal to the
size in bytes of the array passed in. If not, a <code>RangeError</code> exception is
raised.</p>
<p>JavaScript <code>DataView</code> objects are described in
<a href="https://tc39.github.io/ecma262/#sec-dataview-objects">Section 24.3</a> of the ECMAScript Language Specification.</p>
<h3>Functions to convert from C types to N-API<span><a class="mark" href="#n_api_functions_to_convert_from_c_types_to_n_api" id="n_api_functions_to_convert_from_c_types_to_n_api">#</a></span></h3>
<h4>napi_create_int32<span><a class="mark" href="#n_api_napi_create_int32" id="n_api_napi_create_int32">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_int32(napi_env env, int32_t value, napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Integer value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to convert from the C <code>int32_t</code> type to the JavaScript
<code>Number</code> type.</p>
<p>The JavaScript <code>Number</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p>
<h4>napi_create_uint32<span><a class="mark" href="#n_api_napi_create_uint32" id="n_api_napi_create_uint32">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_uint32(napi_env env, uint32_t value, napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Unsigned integer value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to convert from the C <code>uint32_t</code> type to the JavaScript
<code>Number</code> type.</p>
<p>The JavaScript <code>Number</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p>
<h4>napi_create_int64<span><a class="mark" href="#n_api_napi_create_int64" id="n_api_napi_create_int64">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_int64(napi_env env, int64_t value, napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Integer value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to convert from the C <code>int64_t</code> type to the JavaScript
<code>Number</code> type.</p>
<p>The JavaScript <code>Number</code> type is described in <a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a>
of the ECMAScript Language Specification. Note the complete range of <code>int64_t</code>
cannot be represented with full precision in JavaScript. Integer values
outside the range of <a href="https://tc39.github.io/ecma262/#sec-number.min_safe_integer"><code>Number.MIN_SAFE_INTEGER</code></a> <code>-(2^53 - 1)</code> -
<a href="https://tc39.github.io/ecma262/#sec-number.max_safe_integer"><code>Number.MAX_SAFE_INTEGER</code></a> <code>(2^53 - 1)</code> will lose precision.</p>
<h4>napi_create_double<span><a class="mark" href="#n_api_napi_create_double" id="n_api_napi_create_double">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_double(napi_env env, double value, napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Double-precision value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>Number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to convert from the C <code>double</code> type to the JavaScript
<code>Number</code> type.</p>
<p>The JavaScript <code>Number</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-number-type">Section 6.1.6</a> of the ECMAScript Language Specification.</p>
<h4>napi_create_bigint_int64<span><a class="mark" href="#n_api_napi_create_bigint_int64" id="n_api_napi_create_bigint_int64">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status napi_create_bigint_int64(napi_env env,
                                     int64_t value,
                                     napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Integer value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API converts the C <code>int64_t</code> type to the JavaScript <code>BigInt</code> type.</p>
<h4>napi_create_bigint_uint64<span><a class="mark" href="#n_api_napi_create_bigint_uint64" id="n_api_napi_create_bigint_uint64">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status napi_create_bigint_uint64(napi_env env,
                                      uint64_t value,
                                      napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: Unsigned integer value to be represented in JavaScript.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API converts the C <code>uint64_t</code> type to the JavaScript <code>BigInt</code> type.</p>
<h4>napi_create_bigint_words<span><a class="mark" href="#n_api_napi_create_bigint_words" id="n_api_napi_create_bigint_words">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status napi_create_bigint_words(napi_env env,
                                     int sign_bit,
                                     size_t word_count,
                                     const uint64_t* words,
                                     napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] sign_bit</code>: Determines if the resulting <code>BigInt</code> will be positive or
negative.</li>
<li><code>[in] word_count</code>: The length of the <code>words</code> array.</li>
<li><code>[in] words</code>: An array of <code>uint64_t</code> little-endian 64-bit words.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>BigInt</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API converts an array of unsigned 64-bit words into a single <code>BigInt</code>
value.</p>
<p>The resulting <code>BigInt</code> is calculated as: (–1)<sup><code>sign_bit</code></sup> (<code>words[0]</code>
× (2<sup>64</sup>)<sup>0</sup> + <code>words[1]</code> × (2<sup>64</sup>)<sup>1</sup> + …)</p>
<h4>napi_create_string_latin1<span><a class="mark" href="#n_api_napi_create_string_latin1" id="n_api_napi_create_string_latin1">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_string_latin1(napi_env env,
                                      const char* str,
                                      size_t length,
                                      napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] str</code>: Character buffer representing an ISO-8859-1-encoded string.</li>
<li><code>[in] length</code>: The length of the string in bytes, or <code>NAPI_AUTO_LENGTH</code> if it
is null-terminated.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>String</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>String</code> object from an ISO-8859-1-encoded C
string. The native string is copied.</p>
<p>The JavaScript <code>String</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
<h4>napi_create_string_utf16<span><a class="mark" href="#n_api_napi_create_string_utf16" id="n_api_napi_create_string_utf16">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_string_utf16(napi_env env,
                                     const char16_t* str,
                                     size_t length,
                                     napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] str</code>: Character buffer representing a UTF16-LE-encoded string.</li>
<li><code>[in] length</code>: The length of the string in two-byte code units, or
<code>NAPI_AUTO_LENGTH</code> if it is null-terminated.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>String</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>String</code> object from a UTF16-LE-encoded C string.
The native string is copied.</p>
<p>The JavaScript <code>String</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
<h4>napi_create_string_utf8<span><a class="mark" href="#n_api_napi_create_string_utf8" id="n_api_napi_create_string_utf8">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_string_utf8(napi_env env,
                                    const char* str,
                                    size_t length,
                                    napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] str</code>: Character buffer representing a UTF8-encoded string.</li>
<li><code>[in] length</code>: The length of the string in bytes, or <code>NAPI_AUTO_LENGTH</code> if it
is null-terminated.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing a JavaScript <code>String</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>String</code> object from a UTF8-encoded C string.
The native string is copied.</p>
<p>The JavaScript <code>String</code> type is described in
<a href="https://tc39.github.io/ecma262/#sec-ecmascript-language-types-string-type">Section 6.1.4</a> of the ECMAScript Language Specification.</p>
<h3>Functions to convert from N-API to C types<span><a class="mark" href="#n_api_functions_to_convert_from_n_api_to_c_types" id="n_api_functions_to_convert_from_n_api_to_c_types">#</a></span></h3>
<h4>napi_get_array_length<span><a class="mark" href="#n_api_napi_get_array_length" id="n_api_napi_get_array_length">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_array_length(napi_env env,
                                  napi_value value,
                                  uint32_t* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing the JavaScript <code>Array</code> whose length is
being queried.</li>
<li><code>[out] result</code>: <code>uint32</code> representing length of the array.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the length of an array.</p>
<p><code>Array</code> length is described in <a href="https://tc39.github.io/ecma262/#sec-properties-of-array-instances-length">Section 22.1.4.1</a> of the ECMAScript Language
Specification.</p>
<h4>napi_get_arraybuffer_info<span><a class="mark" href="#n_api_napi_get_arraybuffer_info" id="n_api_napi_get_arraybuffer_info">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_arraybuffer_info(napi_env env,
                                      napi_value arraybuffer,
                                      void** data,
                                      size_t* byte_length)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] arraybuffer</code>: <code>napi_value</code> representing the <code>ArrayBuffer</code> being queried.</li>
<li><code>[out] data</code>: The underlying data buffer of the <code>ArrayBuffer</code>. If byte_length
is <code>0</code>, this may be <code>NULL</code> or any other pointer value.</li>
<li><code>[out] byte_length</code>: Length in bytes of the underlying data buffer.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to retrieve the underlying data buffer of an <code>ArrayBuffer</code> and
its length.</p>
<p><em>WARNING</em>: Use caution while using this API. The lifetime of the underlying data
buffer is managed by the <code>ArrayBuffer</code> even after it's returned. A
possible safe way to use this API is in conjunction with
<a href="#n_api_napi_create_reference"><code>napi_create_reference</code></a>, which can be used to guarantee control over the
lifetime of the <code>ArrayBuffer</code>. It's also safe to use the returned data buffer
within the same callback as long as there are no calls to other APIs that might
trigger a GC.</p>
<h4>napi_get_buffer_info<span><a class="mark" href="#n_api_napi_get_buffer_info" id="n_api_napi_get_buffer_info">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_buffer_info(napi_env env,
                                 napi_value value,
                                 void** data,
                                 size_t* length)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing the <code>node::Buffer</code> being queried.</li>
<li><code>[out] data</code>: The underlying data buffer of the <code>node::Buffer</code>.
If length is <code>0</code>, this may be <code>NULL</code> or any other pointer value.</li>
<li><code>[out] length</code>: Length in bytes of the underlying data buffer.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to retrieve the underlying data buffer of a <code>node::Buffer</code>
and it's length.</p>
<p><em>Warning</em>: Use caution while using this API since the underlying data buffer's
lifetime is not guaranteed if it's managed by the VM.</p>
<h4>napi_get_prototype<span><a class="mark" href="#n_api_napi_get_prototype" id="n_api_napi_get_prototype">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_prototype(napi_env env,
                               napi_value object,
                               napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] object</code>: <code>napi_value</code> representing JavaScript <code>Object</code> whose prototype
to return. This returns the equivalent of <code>Object.getPrototypeOf</code> (which is
not the same as the function's <code>prototype</code> property).</li>
<li><code>[out] result</code>: <code>napi_value</code> representing prototype of the given object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<h4>napi_get_typedarray_info<span><a class="mark" href="#n_api_napi_get_typedarray_info" id="n_api_napi_get_typedarray_info">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_typedarray_info(napi_env env,
                                     napi_value typedarray,
                                     napi_typedarray_type* type,
                                     size_t* length,
                                     void** data,
                                     napi_value* arraybuffer,
                                     size_t* byte_offset)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] typedarray</code>: <code>napi_value</code> representing the <code>TypedArray</code> whose
properties to query.</li>
<li><code>[out] type</code>: Scalar datatype of the elements within the <code>TypedArray</code>.</li>
<li><code>[out] length</code>: The number of elements in the <code>TypedArray</code>.</li>
<li><code>[out] data</code>: The data buffer underlying the <code>TypedArray</code> adjusted by
the <code>byte_offset</code> value so that it points to the first element in the
<code>TypedArray</code>. If the length of the array is <code>0</code>, this may be <code>NULL</code> or
any other pointer value.</li>
<li><code>[out] arraybuffer</code>: The <code>ArrayBuffer</code> underlying the <code>TypedArray</code>.</li>
<li><code>[out] byte_offset</code>: The byte offset within the underlying native array
at which the first element of the arrays is located. The value for the data
parameter has already been adjusted so that data points to the first element
in the array. Therefore, the first byte of the native array would be at
<code>data - byte_offset</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns various properties of a typed array.</p>
<p><em>Warning</em>: Use caution while using this API since the underlying data buffer
is managed by the VM.</p>
<h4>napi_get_dataview_info<span><a class="mark" href="#n_api_napi_get_dataview_info" id="n_api_napi_get_dataview_info">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_dataview_info(napi_env env,
                                   napi_value dataview,
                                   size_t* byte_length,
                                   void** data,
                                   napi_value* arraybuffer,
                                   size_t* byte_offset)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] dataview</code>: <code>napi_value</code> representing the <code>DataView</code> whose
properties to query.</li>
<li><code>[out] byte_length</code>: <code>Number</code> of bytes in the <code>DataView</code>.</li>
<li><code>[out] data</code>: The data buffer underlying the <code>DataView</code>.
If byte_length is <code>0</code>, this may be <code>NULL</code> or any other pointer value.</li>
<li><code>[out] arraybuffer</code>: <code>ArrayBuffer</code> underlying the <code>DataView</code>.</li>
<li><code>[out] byte_offset</code>: The byte offset within the data buffer from which
to start projecting the <code>DataView</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns various properties of a <code>DataView</code>.</p>
<h4>napi_get_date_value<span><a class="mark" href="#n_api_napi_get_date_value" id="n_api_napi_get_date_value">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.11.0</span>
<span>N-API version: 5</span>
</div>
<pre><code class="language-c">napi_status napi_get_date_value(napi_env env,
                                napi_value value,
                                double* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing a JavaScript <code>Date</code>.</li>
<li><code>[out] result</code>: Time value as a <code>double</code> represented as milliseconds since
midnight at the beginning of 01 January, 1970 UTC.</li>
</ul>
<p>This API does not observe leap seconds; they are ignored, as
ECMAScript aligns with POSIX time specification.</p>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-date <code>napi_value</code> is passed
in it returns <code>napi_date_expected</code>.</p>
<p>This API returns the C double primitive of time value for the given JavaScript
<code>Date</code>.</p>
<h4>napi_get_value_bool<span><a class="mark" href="#n_api_napi_get_value_bool" id="n_api_napi_get_value_bool">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_bool(napi_env env, napi_value value, bool* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Boolean</code>.</li>
<li><code>[out] result</code>: C boolean primitive equivalent of the given JavaScript
<code>Boolean</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-boolean <code>napi_value</code> is
passed in it returns <code>napi_boolean_expected</code>.</p>
<p>This API returns the C boolean primitive equivalent of the given JavaScript
<code>Boolean</code>.</p>
<h4>napi_get_value_double<span><a class="mark" href="#n_api_napi_get_value_double" id="n_api_napi_get_value_double">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_double(napi_env env,
                                  napi_value value,
                                  double* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Number</code>.</li>
<li><code>[out] result</code>: C double primitive equivalent of the given JavaScript
<code>Number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code> is passed
in it returns <code>napi_number_expected</code>.</p>
<p>This API returns the C double primitive equivalent of the given JavaScript
<code>Number</code>.</p>
<h4>napi_get_value_bigint_int64<span><a class="mark" href="#n_api_napi_get_value_bigint_int64" id="n_api_napi_get_value_bigint_int64">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_bigint_int64(napi_env env,
                                        napi_value value,
                                        int64_t* result,
                                        bool* lossless);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li>
<li><code>[out] result</code>: C <code>int64_t</code> primitive equivalent of the given JavaScript
<code>BigInt</code>.</li>
<li><code>[out] lossless</code>: Indicates whether the <code>BigInt</code> value was converted
losslessly.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>BigInt</code> is passed in it
returns <code>napi_bigint_expected</code>.</p>
<p>This API returns the C <code>int64_t</code> primitive equivalent of the given JavaScript
<code>BigInt</code>. If needed it will truncate the value, setting <code>lossless</code> to <code>false</code>.</p>
<h4>napi_get_value_bigint_uint64<span><a class="mark" href="#n_api_napi_get_value_bigint_uint64" id="n_api_napi_get_value_bigint_uint64">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_bigint_uint64(napi_env env,
                                        napi_value value,
                                        uint64_t* result,
                                        bool* lossless);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li>
<li><code>[out] result</code>: C <code>uint64_t</code> primitive equivalent of the given JavaScript
<code>BigInt</code>.</li>
<li><code>[out] lossless</code>: Indicates whether the <code>BigInt</code> value was converted
losslessly.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>BigInt</code> is passed in it
returns <code>napi_bigint_expected</code>.</p>
<p>This API returns the C <code>uint64_t</code> primitive equivalent of the given JavaScript
<code>BigInt</code>. If needed it will truncate the value, setting <code>lossless</code> to <code>false</code>.</p>
<h4>napi_get_value_bigint_words<span><a class="mark" href="#n_api_napi_get_value_bigint_words" id="n_api_napi_get_value_bigint_words">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_bigint_words(napi_env env,
                                        napi_value value,
                                        int* sign_bit,
                                        size_t* word_count,
                                        uint64_t* words);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>BigInt</code>.</li>
<li><code>[out] sign_bit</code>: Integer representing if the JavaScript <code>BigInt</code> is positive
or negative.</li>
<li><code>[in/out] word_count</code>: Must be initialized to the length of the <code>words</code>
array. Upon return, it will be set to the actual number of words that
would be needed to store this <code>BigInt</code>.</li>
<li><code>[out] words</code>: Pointer to a pre-allocated 64-bit word array.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API converts a single <code>BigInt</code> value into a sign bit, 64-bit little-endian
array, and the number of elements in the array. <code>sign_bit</code> and <code>words</code> may be
both set to <code>NULL</code>, in order to get only <code>word_count</code>.</p>
<h4>napi_get_value_external<span><a class="mark" href="#n_api_napi_get_value_external" id="n_api_napi_get_value_external">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_external(napi_env env,
                                    napi_value value,
                                    void** result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript external value.</li>
<li><code>[out] result</code>: Pointer to the data wrapped by the JavaScript external value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-external <code>napi_value</code> is
passed in it returns <code>napi_invalid_arg</code>.</p>
<p>This API retrieves the external data pointer that was previously passed to
<code>napi_create_external()</code>.</p>
<h4>napi_get_value_int32<span><a class="mark" href="#n_api_napi_get_value_int32" id="n_api_napi_get_value_int32">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_int32(napi_env env,
                                 napi_value value,
                                 int32_t* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Number</code>.</li>
<li><code>[out] result</code>: C <code>int32</code> primitive equivalent of the given JavaScript
<code>Number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code>
is passed in <code>napi_number_expected</code>.</p>
<p>This API returns the C <code>int32</code> primitive equivalent
of the given JavaScript <code>Number</code>.</p>
<p>If the number exceeds the range of the 32 bit integer, then the result is
truncated to the equivalent of the bottom 32 bits. This can result in a large
positive number becoming a negative number if the value is > 2^31 -1.</p>
<p>Non-finite number values (<code>NaN</code>, <code>+Infinity</code>, or <code>-Infinity</code>) set the
result to zero.</p>
<h4>napi_get_value_int64<span><a class="mark" href="#n_api_napi_get_value_int64" id="n_api_napi_get_value_int64">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_int64(napi_env env,
                                 napi_value value,
                                 int64_t* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Number</code>.</li>
<li><code>[out] result</code>: C <code>int64</code> primitive equivalent of the given JavaScript
<code>Number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code>
is passed in it returns <code>napi_number_expected</code>.</p>
<p>This API returns the C <code>int64</code> primitive equivalent of the given JavaScript
<code>Number</code>.</p>
<p><code>Number</code> values outside the range of <a href="https://tc39.github.io/ecma262/#sec-number.min_safe_integer"><code>Number.MIN_SAFE_INTEGER</code></a>
<code>-(2^53 - 1)</code> - <a href="https://tc39.github.io/ecma262/#sec-number.max_safe_integer"><code>Number.MAX_SAFE_INTEGER</code></a> <code>(2^53 - 1)</code> will lose precision.</p>
<p>Non-finite number values (<code>NaN</code>, <code>+Infinity</code>, or <code>-Infinity</code>) set the
result to zero.</p>
<h4>napi_get_value_string_latin1<span><a class="mark" href="#n_api_napi_get_value_string_latin1" id="n_api_napi_get_value_string_latin1">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_string_latin1(napi_env env,
                                         napi_value value,
                                         char* buf,
                                         size_t bufsize,
                                         size_t* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li>
<li><code>[in] buf</code>: Buffer to write the ISO-8859-1-encoded string into. If <code>NULL</code> is
passed in, the length of the string (in bytes) is returned.</li>
<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
insufficient, the returned string will be truncated.</li>
<li><code>[out] result</code>: Number of bytes copied into the buffer, excluding the null
terminator.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>String</code> <code>napi_value</code>
is passed in it returns <code>napi_string_expected</code>.</p>
<p>This API returns the ISO-8859-1-encoded string corresponding the value passed
in.</p>
<h4>napi_get_value_string_utf8<span><a class="mark" href="#n_api_napi_get_value_string_utf8" id="n_api_napi_get_value_string_utf8">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_string_utf8(napi_env env,
                                       napi_value value,
                                       char* buf,
                                       size_t bufsize,
                                       size_t* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li>
<li><code>[in] buf</code>: Buffer to write the UTF8-encoded string into. If <code>NULL</code> is passed
in, the length of the string (in bytes) is returned.</li>
<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
insufficient, the returned string will be truncated.</li>
<li><code>[out] result</code>: Number of bytes copied into the buffer, excluding the null
terminator.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>String</code> <code>napi_value</code>
is passed in it returns <code>napi_string_expected</code>.</p>
<p>This API returns the UTF8-encoded string corresponding the value passed in.</p>
<h4>napi_get_value_string_utf16<span><a class="mark" href="#n_api_napi_get_value_string_utf16" id="n_api_napi_get_value_string_utf16">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_string_utf16(napi_env env,
                                        napi_value value,
                                        char16_t* buf,
                                        size_t bufsize,
                                        size_t* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript string.</li>
<li><code>[in] buf</code>: Buffer to write the UTF16-LE-encoded string into. If <code>NULL</code> is
passed in, the length of the string (in 2-byte code units) is returned.</li>
<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
insufficient, the returned string will be truncated.</li>
<li><code>[out] result</code>: Number of 2-byte code units copied into the buffer, excluding
the null terminator.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-<code>String</code> <code>napi_value</code>
is passed in it returns <code>napi_string_expected</code>.</p>
<p>This API returns the UTF16-encoded string corresponding the value passed in.</p>
<h4>napi_get_value_uint32<span><a class="mark" href="#n_api_napi_get_value_uint32" id="n_api_napi_get_value_uint32">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_value_uint32(napi_env env,
                                  napi_value value,
                                  uint32_t* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: <code>napi_value</code> representing JavaScript <code>Number</code>.</li>
<li><code>[out] result</code>: C primitive equivalent of the given <code>napi_value</code> as a
<code>uint32_t</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-number <code>napi_value</code>
is passed in it returns <code>napi_number_expected</code>.</p>
<p>This API returns the C primitive equivalent of the given <code>napi_value</code> as a
<code>uint32_t</code>.</p>
<h3>Functions to get global instances<span><a class="mark" href="#n_api_functions_to_get_global_instances" id="n_api_functions_to_get_global_instances">#</a></span></h3>
<h4>napi_get_boolean<span><a class="mark" href="#n_api_napi_get_boolean" id="n_api_napi_get_boolean">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_boolean(napi_env env, bool value, napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The value of the boolean to retrieve.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>Boolean</code> singleton to
retrieve.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API is used to return the JavaScript singleton object that is used to
represent the given boolean value.</p>
<h4>napi_get_global<span><a class="mark" href="#n_api_napi_get_global" id="n_api_napi_get_global">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_global(napi_env env, napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>global</code> object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the <code>global</code> object.</p>
<h4>napi_get_null<span><a class="mark" href="#n_api_napi_get_null" id="n_api_napi_get_null">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_null(napi_env env, napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript <code>null</code> object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the <code>null</code> object.</p>
<h4>napi_get_undefined<span><a class="mark" href="#n_api_napi_get_undefined" id="n_api_napi_get_undefined">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_undefined(napi_env env, napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing JavaScript Undefined value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the Undefined object.</p>
<h2>Working with JavaScript values and abstract operations<span><a class="mark" href="#n_api_working_with_javascript_values_and_abstract_operations" id="n_api_working_with_javascript_values_and_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 <code>Number</code> or
<code>String</code>).</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>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_coerce_to_bool(napi_env env,
                                napi_value value,
                                napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to coerce.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>Boolean</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation <code>ToBoolean()</code> as defined in
<a href="https://tc39.github.io/ecma262/#sec-toboolean">Section 7.1.2</a> of the ECMAScript Language Specification.
This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p>
<h3>napi_coerce_to_number<span><a class="mark" href="#n_api_napi_coerce_to_number" id="n_api_napi_coerce_to_number">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_coerce_to_number(napi_env env,
                                  napi_value value,
                                  napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to coerce.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>Number</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation <code>ToNumber()</code> as defined in
<a href="https://tc39.github.io/ecma262/#sec-tonumber">Section 7.1.3</a> of the ECMAScript Language Specification.
This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p>
<h3>napi_coerce_to_object<span><a class="mark" href="#n_api_napi_coerce_to_object" id="n_api_napi_coerce_to_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_coerce_to_object(napi_env env,
                                  napi_value value,
                                  napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to coerce.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>Object</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation <code>ToObject()</code> as defined in
<a href="https://tc39.github.io/ecma262/#sec-toobject">Section 7.1.13</a> of the ECMAScript Language Specification.
This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p>
<h3>napi_coerce_to_string<span><a class="mark" href="#n_api_napi_coerce_to_string" id="n_api_napi_coerce_to_string">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_coerce_to_string(napi_env env,
                                  napi_value value,
                                  napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to coerce.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the coerced JavaScript <code>String</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API implements the abstract operation <code>ToString()</code> as defined in
<a href="https://tc39.github.io/ecma262/#sec-toobject">Section 7.1.13</a> of the ECMAScript Language Specification.
This API can be re-entrant if getters are defined on the passed-in <code>Object</code>.</p>
<h3>napi_typeof<span><a class="mark" href="#n_api_napi_typeof" id="n_api_napi_typeof">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_typeof(napi_env env, napi_value value, napi_valuetype* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value whose type to query.</li>
<li><code>[out] result</code>: The type of the JavaScript value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<ul>
<li><code>napi_invalid_arg</code> if the type of <code>value</code> is not a known ECMAScript type and
<code>value</code> is not an External value.</li>
</ul>
<p>This API represents behavior similar to invoking the <code>typeof</code> Operator on
the object as defined in <a href="https://tc39.github.io/ecma262/#sec-typeof-operator">Section 12.5.5</a> of the ECMAScript Language
Specification. However, it has support for detecting an External value.
If <code>value</code> has a type that is invalid, an error is returned.</p>
<h3>napi_instanceof<span><a class="mark" href="#n_api_napi_instanceof" id="n_api_napi_instanceof">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_instanceof(napi_env env,
                            napi_value object,
                            napi_value constructor,
                            bool* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] object</code>: The JavaScript value to check.</li>
<li><code>[in] constructor</code>: The JavaScript function object of the constructor function
to check against.</li>
<li><code>[out] result</code>: Boolean that is set to true if <code>object instanceof constructor</code>
is true.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API represents invoking the <code>instanceof</code> Operator on the object as
defined in <a href="https://tc39.github.io/ecma262/#sec-instanceofoperator">Section 12.10.4</a> of the ECMAScript Language Specification.</p>
<h3>napi_is_array<span><a class="mark" href="#n_api_napi_is_array" id="n_api_napi_is_array">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_is_array(napi_env env, napi_value value, bool* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given object is an array.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API represents invoking the <code>IsArray</code> operation on the object
as defined in <a href="https://tc39.github.io/ecma262/#sec-isarray">Section 7.2.2</a> of the ECMAScript Language Specification.</p>
<h3>napi_is_arraybuffer<span><a class="mark" href="#n_api_napi_is_arraybuffer" id="n_api_napi_is_arraybuffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_is_arraybuffer(napi_env env, napi_value value, bool* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given object is an <code>ArrayBuffer</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is an array buffer.</p>
<h3>napi_is_buffer<span><a class="mark" href="#n_api_napi_is_buffer" id="n_api_napi_is_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_is_buffer(napi_env env, napi_value value, bool* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>node::Buffer</code>
object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is a buffer.</p>
<h3>napi_is_date<span><a class="mark" href="#n_api_napi_is_date" id="n_api_napi_is_date">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.11.0</span>
<span>N-API version: 5</span>
</div>
<pre><code class="language-c">napi_status napi_is_date(napi_env env, napi_value value, bool* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a JavaScript <code>Date</code>
object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is a date.</p>
<h3>napi_is_error<span><a class="mark" href="#n_api_napi_is_error_1" id="n_api_napi_is_error_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_is_error(napi_env env, napi_value value, bool* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents an <code>Error</code> object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is an <code>Error</code>.</p>
<h3>napi_is_typedarray<span><a class="mark" href="#n_api_napi_is_typedarray" id="n_api_napi_is_typedarray">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_is_typedarray(napi_env env, napi_value value, bool* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>TypedArray</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is a typed array.</p>
<h3>napi_is_dataview<span><a class="mark" href="#n_api_napi_is_dataview" id="n_api_napi_is_dataview">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_is_dataview(napi_env env, napi_value value, bool* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The JavaScript value to check.</li>
<li><code>[out] result</code>: Whether the given <code>napi_value</code> represents a <code>DataView</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in is a <code>DataView</code>.</p>
<h3>napi_strict_equals<span><a class="mark" href="#n_api_napi_strict_equals" id="n_api_napi_strict_equals">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_strict_equals(napi_env env,
                               napi_value lhs,
                               napi_value rhs,
                               bool* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] lhs</code>: The JavaScript value to check.</li>
<li><code>[in] rhs</code>: The JavaScript value to check against.</li>
<li><code>[out] result</code>: Whether the two <code>napi_value</code> objects are equal.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API represents the invocation of the Strict Equality algorithm as
defined in <a href="https://tc39.github.io/ecma262/#sec-strict-equality-comparison">Section 7.2.14</a> of the ECMAScript Language Specification.</p>
<h3>napi_detach_arraybuffer<span><a class="mark" href="#n_api_napi_detach_arraybuffer" id="n_api_napi_detach_arraybuffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status napi_detach_arraybuffer(napi_env env,
                                    napi_value arraybuffer)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] arraybuffer</code>: The JavaScript <code>ArrayBuffer</code> to be detached.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded. If a non-detachable <code>ArrayBuffer</code> is
passed in it returns <code>napi_detachable_arraybuffer_expected</code>.</p>
<p>Generally, an <code>ArrayBuffer</code> is non-detachable if it has been detached before.
The engine may impose additional conditions on whether an <code>ArrayBuffer</code> is
detachable. For example, V8 requires that the <code>ArrayBuffer</code> be external,
that is, created with <a href="#n_api_napi_create_external_arraybuffer"><code>napi_create_external_arraybuffer</code></a>.</p>
<p>This API represents the invocation of the <code>ArrayBuffer</code> detach operation as
defined in <a href="https://tc39.es/ecma262/#sec-detacharraybuffer">Section 24.1.1.3</a> of the ECMAScript Language Specification.</p>
<h3>napi_is_detached_arraybuffer<span><a class="mark" href="#n_api_napi_is_detached_arraybuffer" id="n_api_napi_is_detached_arraybuffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status napi_is_detached_arraybuffer(napi_env env,
                                         napi_value arraybuffer,
                                         bool* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] arraybuffer</code>: The JavaScript <code>ArrayBuffer</code> to be checked.</li>
<li><code>[out] result</code>: Whether the <code>arraybuffer</code> is detached.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>The <code>ArrayBuffer</code> is considered detached if its internal data is <code>null</code>.</p>
<p>This API represents the invocation of the <code>ArrayBuffer</code> <code>IsDetachedBuffer</code>
operation as defined in <a href="https://tc39.es/ecma262/#sec-isdetachedbuffer">Section 24.1.1.2</a> of the ECMAScript Language
Specification.</p>
<h2>Working with JavaScript properties<span><a class="mark" href="#n_api_working_with_javascript_properties" id="n_api_working_with_javascript_properties">#</a></span></h2>
<p>N-API exposes a set of APIs to get and set properties on JavaScript
objects. Some of these types are documented under <a href="https://tc39.github.io/ecma262/#sec-abstract-operations">Section 7</a> of the
<a href="https://tc39.github.io/ecma262/">ECMAScript Language Specification</a>.</p>
<p>Properties in JavaScript are represented as a tuple of a key and a value.
Fundamentally, all property keys in N-API can be represented in one of the
following forms:</p>
<ul>
<li>Named: a simple UTF8-encoded string</li>
<li>Integer-Indexed: an index value represented by <code>uint32_t</code></li>
<li>JavaScript value: these are represented in N-API by <code>napi_value</code>. This can
be a <code>napi_value</code> representing a <code>String</code>, <code>Number</code>, or <code>Symbol</code>.</li>
</ul>
<p>N-API values are represented by the type <code>napi_value</code>.
Any N-API call that requires a JavaScript value takes in a <code>napi_value</code>.
However, it's the caller's responsibility to make sure that the
<code>napi_value</code> in question is of the JavaScript type expected by the API.</p>
<p>The APIs documented in this section provide a simple interface to
get and set properties on arbitrary JavaScript objects represented by
<code>napi_value</code>.</p>
<p>For instance, consider the following JavaScript code snippet:</p>
<pre><code class="language-js">const obj = {};
obj.myProp = 123;
</code></pre>
<p>The equivalent can be done using N-API values with the following snippet:</p>
<pre><code class="language-c">napi_status status = napi_generic_failure;

// const obj = {}
napi_value obj, value;
status = napi_create_object(env, &#x26;obj);
if (status != napi_ok) return status;

// Create a napi_value for 123
status = napi_create_int32(env, 123, &#x26;value);
if (status != napi_ok) return status;

// obj.myProp = 123
status = napi_set_named_property(env, obj, "myProp", value);
if (status != napi_ok) return status;
</code></pre>
<p>Indexed properties can be set in a similar manner. Consider the following
JavaScript snippet:</p>
<pre><code class="language-js">const arr = [];
arr[123] = 'hello';
</code></pre>
<p>The equivalent can be done using N-API values with the following snippet:</p>
<pre><code class="language-c">napi_status status = napi_generic_failure;

// const arr = [];
napi_value arr, value;
status = napi_create_array(env, &#x26;arr);
if (status != napi_ok) return status;

// Create a napi_value for 'hello'
status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &#x26;value);
if (status != napi_ok) return status;

// arr[123] = 'hello';
status = napi_set_element(env, arr, 123, value);
if (status != napi_ok) return status;
</code></pre>
<p>Properties can be retrieved using the APIs described in this section.
Consider the following JavaScript snippet:</p>
<pre><code class="language-js">const arr = [];
const value = arr[123];
</code></pre>
<p>The following is the approximate equivalent of the N-API counterpart:</p>
<pre><code class="language-c">napi_status status = napi_generic_failure;

// const arr = []
napi_value arr, value;
status = napi_create_array(env, &#x26;arr);
if (status != napi_ok) return status;

// const value = arr[123]
status = napi_get_element(env, arr, 123, &#x26;value);
if (status != napi_ok) return status;
</code></pre>
<p>Finally, multiple properties can also be defined on an object for performance
reasons. Consider the following JavaScript:</p>
<pre><code class="language-js">const obj = {};
Object.defineProperties(obj, {
  'foo': { value: 123, writable: true, configurable: true, enumerable: true },
  'bar': { value: 456, writable: true, configurable: true, enumerable: true }
});
</code></pre>
<p>The following is the approximate equivalent of the N-API counterpart:</p>
<pre><code class="language-c">napi_status status = napi_status_generic_failure;

// const obj = {};
napi_value obj;
status = napi_create_object(env, &#x26;obj);
if (status != napi_ok) return status;

// Create napi_values for 123 and 456
napi_value fooValue, barValue;
status = napi_create_int32(env, 123, &#x26;fooValue);
if (status != napi_ok) return status;
status = napi_create_int32(env, 456, &#x26;barValue);
if (status != napi_ok) return status;

// Set the properties
napi_property_descriptor descriptors[] = {
  { "foo", NULL, NULL, NULL, NULL, fooValue, napi_default, NULL },
  { "bar", NULL, NULL, NULL, NULL, barValue, napi_default, NULL }
}
status = napi_define_properties(env,
                                obj,
                                sizeof(descriptors) / sizeof(descriptors[0]),
                                descriptors);
if (status != napi_ok) return status;
</code></pre>
<h3>Structures<span><a class="mark" href="#n_api_structures" id="n_api_structures">#</a></span></h3>
<h4>napi_property_attributes<span><a class="mark" href="#n_api_napi_property_attributes" id="n_api_napi_property_attributes">#</a></span></h4>
<pre><code class="language-c">typedef enum {
  napi_default = 0,
  napi_writable = 1 &#x3C;&#x3C; 0,
  napi_enumerable = 1 &#x3C;&#x3C; 1,
  napi_configurable = 1 &#x3C;&#x3C; 2,

  // Used with napi_define_class to distinguish static properties
  // from instance properties. Ignored by napi_define_properties.
  napi_static = 1 &#x3C;&#x3C; 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>: No explicit attributes are set on the property. By default, a
property is read only, not enumerable and not configurable.</li>
<li><code>napi_writable</code>: The property is writable.</li>
<li><code>napi_enumerable</code>: The property is enumerable.</li>
<li><code>napi_configurable</code>: The 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>: The property will be defined as a static property on a class as
opposed to an instance property, which is the default. This is used only by
<a href="#n_api_napi_define_class"><code>napi_define_class</code></a>. It is ignored by <code>napi_define_properties</code>.</li>
</ul>
<h4>napi_property_descriptor<span><a class="mark" href="#n_api_napi_property_descriptor" id="n_api_napi_property_descriptor">#</a></span></h4>
<pre><code class="language-c">typedef struct {
  // One of utf8name or name should be NULL.
  const char* utf8name;
  napi_value name;

  napi_callback method;
  napi_callback getter;
  napi_callback setter;
  napi_value value;

  napi_property_attributes attributes;
  void* data;
} napi_property_descriptor;
</code></pre>
<ul>
<li><code>utf8name</code>: Optional <code>String</code> describing the key for the property,
encoded as UTF8. One of <code>utf8name</code> or <code>name</code> must be provided for the
property.</li>
<li><code>name</code>: Optional <code>napi_value</code> that points to a JavaScript string or symbol
to be used as the key for the property. One of <code>utf8name</code> or <code>name</code> must
be provided for the property.</li>
<li><code>value</code>: The value that's retrieved by a get access of the property if the
property is a data property. If this is passed in, set <code>getter</code>, <code>setter</code>,
<code>method</code> and <code>data</code> to <code>NULL</code> (since these members won't be used).</li>
<li><code>getter</code>: A function to call when a get access of the property is performed.
If this is passed in, set <code>value</code> and <code>method</code> to <code>NULL</code> (since these members
won't be used). The given function is called implicitly by the runtime when
the property is accessed from JavaScript code (or if a get on the property is
performed using a N-API call).</li>
<li><code>setter</code>: A function to call when a set access of the property is performed.
If this is passed in, set <code>value</code> and <code>method</code> to <code>NULL</code> (since these members
won't be used). The given function is called implicitly by the runtime when
the property is set from JavaScript code (or if a set on the property is
performed using a N-API call).</li>
<li><code>method</code>: Set this to make the property descriptor object's <code>value</code>
property to be a JavaScript function represented by <code>method</code>. If this is
passed in, set <code>value</code>, <code>getter</code> and <code>setter</code> to <code>NULL</code> (since these members
won't be used).</li>
<li><code>attributes</code>: The attributes associated with the particular property. See
<a href="#n_api_napi_property_attributes"><code>napi_property_attributes</code></a>.</li>
<li><code>data</code>: The callback data passed into <code>method</code>, <code>getter</code> and <code>setter</code> if this
function is invoked.</li>
</ul>
<h3>Functions<span><a class="mark" href="#n_api_functions" id="n_api_functions">#</a></span></h3>
<h4>napi_get_property_names<span><a class="mark" href="#n_api_napi_get_property_names" id="n_api_napi_get_property_names">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_property_names(napi_env env,
                                    napi_value object,
                                    napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the properties.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing an array of JavaScript values
that represent the property names of the object. The API can be used to
iterate over <code>result</code> using <a href="#n_api_napi_get_array_length"><code>napi_get_array_length</code></a>
and <a href="#n_api_napi_get_element"><code>napi_get_element</code></a>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the names of the enumerable properties of <code>object</code> as an array
of strings. The properties of <code>object</code> whose key is a symbol will not be
included.</p>
<h4>napi_get_all_property_names<span><a class="mark" href="#n_api_napi_get_all_property_names" id="n_api_napi_get_all_property_names">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_get_all_property_names(napi_env env,
                            napi_value object,
                            napi_key_collection_mode key_mode,
                            napi_key_filter key_filter,
                            napi_key_conversion key_conversion,
                            napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the properties.</li>
<li><code>[in] key_mode</code>: Whether to retrieve prototype properties as well.</li>
<li><code>[in] key_filter</code>: Which properties to retrieve
(enumerable/readable/writable).</li>
<li><code>[in] key_conversion</code>: Whether to convert numbered property keys to strings.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing an array of JavaScript values
that represent the property names of the object. <a href="#n_api_napi_get_array_length"><code>napi_get_array_length</code></a> and
<a href="#n_api_napi_get_element"><code>napi_get_element</code></a> can be used to iterate over <code>result</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns an array containing the names of the available properties
of this object.</p>
<h4>napi_set_property<span><a class="mark" href="#n_api_napi_set_property" id="n_api_napi_set_property">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_set_property(napi_env env,
                              napi_value object,
                              napi_value key,
                              napi_value value);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object on which to set the property.</li>
<li><code>[in] key</code>: The name of the property to set.</li>
<li><code>[in] value</code>: The property value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API set a property on the <code>Object</code> passed in.</p>
<h4>napi_get_property<span><a class="mark" href="#n_api_napi_get_property" id="n_api_napi_get_property">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_property(napi_env env,
                              napi_value object,
                              napi_value key,
                              napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the property.</li>
<li><code>[in] key</code>: The name of the property to retrieve.</li>
<li><code>[out] result</code>: The value of the property.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API gets the requested property from the <code>Object</code> passed in.</p>
<h4>napi_has_property<span><a class="mark" href="#n_api_napi_has_property" id="n_api_napi_has_property">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_has_property(napi_env env,
                              napi_value object,
                              napi_value key,
                              bool* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] key</code>: The name of the property whose existence to check.</li>
<li><code>[out] result</code>: Whether the property exists on the object or not.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in has the named property.</p>
<h4>napi_delete_property<span><a class="mark" href="#n_api_napi_delete_property" id="n_api_napi_delete_property">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_delete_property(napi_env env,
                                 napi_value object,
                                 napi_value key,
                                 bool* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] key</code>: The name of the property to delete.</li>
<li><code>[out] result</code>: Whether the property deletion succeeded or not. <code>result</code> can
optionally be ignored by passing <code>NULL</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API attempts to delete the <code>key</code> own property from <code>object</code>.</p>
<h4>napi_has_own_property<span><a class="mark" href="#n_api_napi_has_own_property" id="n_api_napi_has_own_property">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_has_own_property(napi_env env,
                                  napi_value object,
                                  napi_value key,
                                  bool* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] key</code>: The name of the own property whose existence to check.</li>
<li><code>[out] result</code>: Whether the own property exists on the object or not.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API checks if the <code>Object</code> passed in has the named own property. <code>key</code> must
be a string or a <code>Symbol</code>, or an error will be thrown. N-API will not perform
any conversion between data types.</p>
<h4>napi_set_named_property<span><a class="mark" href="#n_api_napi_set_named_property" id="n_api_napi_set_named_property">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_set_named_property(napi_env env,
                                    napi_value object,
                                    const char* utf8Name,
                                    napi_value value);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object on which to set the property.</li>
<li><code>[in] utf8Name</code>: The name of the property to set.</li>
<li><code>[in] value</code>: The property value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method is equivalent to calling <a href="#n_api_napi_set_property"><code>napi_set_property</code></a> with a <code>napi_value</code>
created from the string passed in as <code>utf8Name</code>.</p>
<h4>napi_get_named_property<span><a class="mark" href="#n_api_napi_get_named_property" id="n_api_napi_get_named_property">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_named_property(napi_env env,
                                    napi_value object,
                                    const char* utf8Name,
                                    napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the property.</li>
<li><code>[in] utf8Name</code>: The name of the property to get.</li>
<li><code>[out] result</code>: The value of the property.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method is equivalent to calling <a href="#n_api_napi_get_property"><code>napi_get_property</code></a> with a <code>napi_value</code>
created from the string passed in as <code>utf8Name</code>.</p>
<h4>napi_has_named_property<span><a class="mark" href="#n_api_napi_has_named_property" id="n_api_napi_has_named_property">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_has_named_property(napi_env env,
                                    napi_value object,
                                    const char* utf8Name,
                                    bool* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] utf8Name</code>: The name of the property whose existence to check.</li>
<li><code>[out] result</code>: Whether the property exists on the object or not.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method is equivalent to calling <a href="#n_api_napi_has_property"><code>napi_has_property</code></a> with a <code>napi_value</code>
created from the string passed in as <code>utf8Name</code>.</p>
<h4>napi_set_element<span><a class="mark" href="#n_api_napi_set_element" id="n_api_napi_set_element">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_set_element(napi_env env,
                             napi_value object,
                             uint32_t index,
                             napi_value value);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to set the properties.</li>
<li><code>[in] index</code>: The index of the property to set.</li>
<li><code>[in] value</code>: The property value.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API sets and element on the <code>Object</code> passed in.</p>
<h4>napi_get_element<span><a class="mark" href="#n_api_napi_get_element" id="n_api_napi_get_element">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_element(napi_env env,
                             napi_value object,
                             uint32_t index,
                             napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the property.</li>
<li><code>[in] index</code>: The index of the property to get.</li>
<li><code>[out] result</code>: The value of the property.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API gets the element at the requested index.</p>
<h4>napi_has_element<span><a class="mark" href="#n_api_napi_has_element" id="n_api_napi_has_element">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_has_element(napi_env env,
                             napi_value object,
                             uint32_t index,
                             bool* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] index</code>: The index of the property whose existence to check.</li>
<li><code>[out] result</code>: Whether the property exists on the object or not.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns if the <code>Object</code> passed in has an element at the
requested index.</p>
<h4>napi_delete_element<span><a class="mark" href="#n_api_napi_delete_element" id="n_api_napi_delete_element">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_delete_element(napi_env env,
                                napi_value object,
                                uint32_t index,
                                bool* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object to query.</li>
<li><code>[in] index</code>: The index of the property to delete.</li>
<li><code>[out] result</code>: Whether the element deletion succeeded or not. <code>result</code> can
optionally be ignored by passing <code>NULL</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API attempts to delete the specified <code>index</code> from <code>object</code>.</p>
<h4>napi_define_properties<span><a class="mark" href="#n_api_napi_define_properties" id="n_api_napi_define_properties">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_define_properties(napi_env env,
                                   napi_value object,
                                   size_t property_count,
                                   const napi_property_descriptor* properties);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the N-API call is invoked under.</li>
<li><code>[in] object</code>: The object from which to retrieve the properties.</li>
<li><code>[in] property_count</code>: The number of elements in the <code>properties</code> array.</li>
<li><code>[in] properties</code>: The array of property descriptors.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method allows the efficient definition of multiple properties on a given
object. The properties are defined using property descriptors (see
<a href="#n_api_napi_property_descriptor"><code>napi_property_descriptor</code></a>). Given an array of such property descriptors,
this API will set the properties on the object one at a time, as defined by
<code>DefineOwnProperty()</code> (described in <a href="https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots-defineownproperty-p-desc">Section 9.1.6</a> of the ECMA-262
specification).</p>
<h2>Working with JavaScript functions<span><a class="mark" href="#n_api_working_with_javascript_functions" id="n_api_working_with_javascript_functions">#</a></span></h2>
<p>N-API provides a set of APIs that allow JavaScript code to
call back into native code. N-API APIs that support calling back
into native code take in a callback functions represented by
the <code>napi_callback</code> type. When the JavaScript VM calls back to
native code, the <code>napi_callback</code> function provided is invoked. The APIs
documented in this section allow the callback function to do the
following:</p>
<ul>
<li>Get information about the context in which the callback was invoked.</li>
<li>Get the arguments passed into the callback.</li>
<li>Return a <code>napi_value</code> back from the callback.</li>
</ul>
<p>Additionally, N-API provides a set of functions which allow calling
JavaScript functions from native code. One can either call a function
like a regular JavaScript function call, or as a constructor
function.</p>
<p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> field of the
<code>napi_property_descriptor</code> items can be associated with <code>object</code> and freed
whenever <code>object</code> is garbage-collected by passing both <code>object</code> and the data to
<a href="#n_api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p>
<h3>napi_call_function<span><a class="mark" href="#n_api_napi_call_function" id="n_api_napi_call_function">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_call_function(napi_env env,
                                           napi_value recv,
                                           napi_value func,
                                           size_t argc,
                                           const napi_value* argv,
                                           napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] recv</code>: The <code>this</code> object passed to the called function.</li>
<li><code>[in] func</code>: <code>napi_value</code> representing the JavaScript function to be invoked.</li>
<li><code>[in] argc</code>: The count of elements in the <code>argv</code> array.</li>
<li><code>[in] argv</code>: Array of <code>napi_values</code> representing JavaScript values passed in
as arguments to the function.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript object returned.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method allows a JavaScript function object to be called from a native
add-on. This is the primary mechanism of calling back <em>from</em> the add-on's
native code <em>into</em> JavaScript. For the special case of calling into JavaScript
after an async operation, see <a href="#n_api_napi_make_callback"><code>napi_make_callback</code></a>.</p>
<p>A sample use case might look as follows. Consider the following JavaScript
snippet:</p>
<pre><code class="language-js">function AddTwo(num) {
  return num + 2;
}
</code></pre>
<p>Then, the above function can be invoked from a native add-on using the
following code:</p>
<pre><code class="language-c">// Get the function named "AddTwo" on the global object
napi_value global, add_two, arg;
napi_status status = napi_get_global(env, &#x26;global);
if (status != napi_ok) return;

status = napi_get_named_property(env, global, "AddTwo", &#x26;add_two);
if (status != napi_ok) return;

// const arg = 1337
status = napi_create_int32(env, 1337, &#x26;arg);
if (status != napi_ok) return;

napi_value* argv = &#x26;arg;
size_t argc = 1;

// AddTwo(arg);
napi_value return_val;
status = napi_call_function(env, global, add_two, argc, argv, &#x26;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, &#x26;result);
if (status != napi_ok) return;
</code></pre>
<h3>napi_create_function<span><a class="mark" href="#n_api_napi_create_function" id="n_api_napi_create_function">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_function(napi_env env,
                                 const char* utf8name,
                                 size_t length,
                                 napi_callback cb,
                                 void* data,
                                 napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] utf8Name</code>: The name of the function encoded as UTF8. This is visible
within JavaScript as the new function object's <code>name</code> property.</li>
<li><code>[in] length</code>: The length of the <code>utf8name</code> in bytes, or <code>NAPI_AUTO_LENGTH</code> if
it is null-terminated.</li>
<li><code>[in] cb</code>: The native function which should be called when this function
object is invoked.</li>
<li><code>[in] data</code>: User-provided data context. This will be passed back into the
function when invoked later.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript function object for
the newly created function.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allows an add-on author to create a function object in native code.
This is the primary mechanism to allow calling <em>into</em> the add-on's native code
<em>from</em> JavaScript.</p>
<p>The newly created function is not automatically visible from script after this
call. Instead, a property must be explicitly set on any object that is visible
to JavaScript, in order for the function to be accessible from script.</p>
<p>In order to expose a function as part of the
add-on's module exports, set the newly created function on the exports
object. A sample module might look as follows:</p>
<pre><code class="language-c">napi_value SayHello(napi_env env, napi_callback_info info) {
  printf("Hello\n");
  return NULL;
}

napi_value Init(napi_env env, napi_value exports) {
  napi_status status;

  napi_value fn;
  status = napi_create_function(env, NULL, 0, SayHello, NULL, &#x26;fn);
  if (status != napi_ok) return NULL;

  status = napi_set_named_property(env, exports, "sayHello", fn);
  if (status != napi_ok) return NULL;

  return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
</code></pre>
<p>Given the above code, the add-on can be used from JavaScript as follows:</p>
<pre><code class="language-js">const myaddon = require('./addon');
myaddon.sayHello();
</code></pre>
<p>The string passed to <code>require()</code> is the name of the target in <code>binding.gyp</code>
responsible for creating the <code>.node</code> file.</p>
<p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> parameter can
be associated with the resulting JavaScript function (which is returned in the
<code>result</code> parameter) and freed whenever the function is garbage-collected by
passing both the JavaScript function and the data to <a href="#n_api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p>
<p>JavaScript <code>Function</code>s are described in <a href="https://tc39.github.io/ecma262/#sec-function-objects">Section 19.2</a> of the ECMAScript
Language Specification.</p>
<h3>napi_get_cb_info<span><a class="mark" href="#n_api_napi_get_cb_info" id="n_api_napi_get_cb_info">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_cb_info(napi_env env,
                             napi_callback_info cbinfo,
                             size_t* argc,
                             napi_value* argv,
                             napi_value* thisArg,
                             void** data)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] cbinfo</code>: The callback info passed into the callback function.</li>
<li><code>[in-out] argc</code>: Specifies the size of the provided <code>argv</code> array and receives
the actual count of arguments.</li>
<li><code>[out] argv</code>: Buffer to which the <code>napi_value</code> representing the arguments are
copied. If there are more arguments than the provided count, only the
requested number of arguments are copied. If there are fewer arguments
provided than claimed, the rest of <code>argv</code> is filled with <code>napi_value</code> values
that represent <code>undefined</code>.</li>
<li><code>[out] this</code>: Receives the JavaScript <code>this</code> argument for the call.</li>
<li><code>[out] data</code>: Receives the data pointer for the callback.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method is used within a callback function to retrieve details about the
call like the arguments and the <code>this</code> pointer from a given callback info.</p>
<h3>napi_get_new_target<span><a class="mark" href="#n_api_napi_get_new_target" id="n_api_napi_get_new_target">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.6.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_new_target(napi_env env,
                                napi_callback_info cbinfo,
                                napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] cbinfo</code>: The callback info passed into the callback function.</li>
<li><code>[out] result</code>: The <code>new.target</code> of the constructor call.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the <code>new.target</code> of the constructor call. If the current
callback is not a constructor call, the result is <code>NULL</code>.</p>
<h3>napi_new_instance<span><a class="mark" href="#n_api_napi_new_instance" id="n_api_napi_new_instance">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_new_instance(napi_env env,
                              napi_value cons,
                              size_t argc,
                              napi_value* argv,
                              napi_value* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] cons</code>: <code>napi_value</code> representing the JavaScript function to be invoked
as a constructor.</li>
<li><code>[in] argc</code>: The count of elements in the <code>argv</code> array.</li>
<li><code>[in] argv</code>: Array of JavaScript values as <code>napi_value</code> representing the
arguments to the constructor.</li>
<li><code>[out] result</code>: <code>napi_value</code> representing the JavaScript object returned,
which in this case is the constructed object.</li>
</ul>
<p>This method is used to instantiate a new JavaScript value using a given
<code>napi_value</code> that represents the constructor for the object. For example,
consider the following snippet:</p>
<pre><code class="language-js">function MyObject(param) {
  this.param = param;
}

const arg = 'hello';
const value = new MyObject(arg);
</code></pre>
<p>The following can be approximated in N-API using the following snippet:</p>
<pre><code class="language-c">// Get the constructor function MyObject
napi_value global, constructor, arg, value;
napi_status status = napi_get_global(env, &#x26;global);
if (status != napi_ok) return;

status = napi_get_named_property(env, global, "MyObject", &#x26;constructor);
if (status != napi_ok) return;

// const arg = "hello"
status = napi_create_string_utf8(env, "hello", NAPI_AUTO_LENGTH, &#x26;arg);
if (status != napi_ok) return;

napi_value* argv = &#x26;arg;
size_t argc = 1;

// const value = new MyObject(arg)
status = napi_new_instance(env, constructor, argc, argv, &#x26;value);
</code></pre>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<h2>Object wrap<span><a class="mark" href="#n_api_object_wrap" id="n_api_object_wrap">#</a></span></h2>
<p>N-API offers a way to "wrap" C++ classes and instances so that the class
constructor and methods can be called from JavaScript.</p>
<ol>
<li>The <a href="#n_api_napi_define_class"><code>napi_define_class</code></a> API defines a JavaScript class with constructor,
static properties and methods, and instance properties and methods that
correspond to the C++ class.</li>
<li>When JavaScript code invokes the constructor, the constructor callback
uses <a href="#n_api_napi_wrap"><code>napi_wrap</code></a> to wrap a new C++ instance in a JavaScript object,
then returns the wrapper object.</li>
<li>When JavaScript code invokes a method or property accessor on the class,
the corresponding <code>napi_callback</code> C++ function is invoked. For an instance
callback, <a href="#n_api_napi_unwrap"><code>napi_unwrap</code></a> obtains the C++ instance that is the target of
the call.</li>
</ol>
<p>For wrapped objects it may be difficult to distinguish between a function
called on a class prototype and a function called on an instance of a class.
A common pattern used to address this problem is to save a persistent
reference to the class constructor for later <code>instanceof</code> checks.</p>
<pre><code class="language-c">napi_value MyClass_constructor = NULL;
status = napi_get_reference_value(env, MyClass::es_constructor, &#x26;MyClass_constructor);
assert(napi_ok == status);
bool is_instance = false;
status = napi_instanceof(env, es_this, MyClass_constructor, &#x26;is_instance);
assert(napi_ok == status);
if (is_instance) {
  // napi_unwrap() ...
} else {
  // otherwise...
}
</code></pre>
<p>The reference must be freed once it is no longer needed.</p>
<h3>napi_define_class<span><a class="mark" href="#n_api_napi_define_class" id="n_api_napi_define_class">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_define_class(napi_env env,
                              const char* utf8name,
                              size_t length,
                              napi_callback constructor,
                              void* data,
                              size_t property_count,
                              const napi_property_descriptor* properties,
                              napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] utf8name</code>: Name of the JavaScript constructor function; this is
not required to be the same as the C++ class name, though it is recommended
for clarity.</li>
<li><code>[in] length</code>: The length of the <code>utf8name</code> in bytes, or <code>NAPI_AUTO_LENGTH</code>
if it is null-terminated.</li>
<li><code>[in] constructor</code>: Callback function that handles constructing instances
of the class. (This should be a static method on the class, not an actual
C++ constructor function.)</li>
<li><code>[in] data</code>: Optional data to be passed to the constructor callback as
the <code>data</code> property of the callback info.</li>
<li><code>[in] property_count</code>: Number of items in the <code>properties</code> array argument.</li>
<li><code>[in] properties</code>: Array of property descriptors describing static and
instance data properties, accessors, and methods on the class
See <code>napi_property_descriptor</code>.</li>
<li><code>[out] result</code>: A <code>napi_value</code> representing the constructor function for
the class.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Defines a JavaScript class that corresponds to a C++ class, including:</p>
<ul>
<li>A JavaScript constructor function that has the class name and invokes the
provided C++ constructor callback.</li>
<li>Properties on the constructor function corresponding to <em>static</em> data
properties, accessors, and methods of the C++ class (defined by
property descriptors with the <code>napi_static</code> attribute).</li>
<li>Properties on the constructor function's <code>prototype</code> object corresponding to
<em>non-static</em> data properties, accessors, and methods of the C++ class
(defined by property descriptors without the <code>napi_static</code> attribute).</li>
</ul>
<p>The C++ constructor callback should be a static method on the class that calls
the actual class constructor, then wraps the new C++ instance in a JavaScript
object, and returns the wrapper object. See <code>napi_wrap()</code> for details.</p>
<p>The JavaScript constructor function returned from <a href="#n_api_napi_define_class"><code>napi_define_class</code></a> is
often saved and used later, to construct new instances of the class from native
code, and/or check whether provided values are instances of the class. In that
case, to prevent the function value from being garbage-collected, create a
persistent reference to it using <a href="#n_api_napi_create_reference"><code>napi_create_reference</code></a> and ensure the
reference count is kept >= 1.</p>
<p>Any non-<code>NULL</code> data which is passed to this API via the <code>data</code> parameter or via
the <code>data</code> field of the <code>napi_property_descriptor</code> array items can be associated
with the resulting JavaScript constructor (which is returned in the <code>result</code>
parameter) and freed whenever the class is garbage-collected by passing both
the JavaScript function and the data to <a href="#n_api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p>
<h3>napi_wrap<span><a class="mark" href="#n_api_napi_wrap" id="n_api_napi_wrap">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_wrap(napi_env env,
                      napi_value js_object,
                      void* native_object,
                      napi_finalize finalize_cb,
                      void* finalize_hint,
                      napi_ref* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] js_object</code>: The JavaScript object that will be the wrapper for the
native object.</li>
<li><code>[in] native_object</code>: The native instance that will be wrapped in the
JavaScript object.</li>
<li><code>[in] finalize_cb</code>: Optional native callback that can be used to free the
native instance when the JavaScript object is ready for garbage-collection.</li>
<li><code>[in] finalize_hint</code>: Optional contextual hint that is passed to the
finalize callback.</li>
<li><code>[out] result</code>: Optional reference to the wrapped object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Wraps a native instance in a JavaScript object. The native instance can be
retrieved later using <code>napi_unwrap()</code>.</p>
<p>When JavaScript code invokes a constructor for a class that was defined using
<code>napi_define_class()</code>, the <code>napi_callback</code> for the constructor is invoked.
After constructing an instance of the native class, the callback must then call
<code>napi_wrap()</code> to wrap the newly constructed instance in the already-created
JavaScript object that is the <code>this</code> argument to the constructor callback.
(That <code>this</code> object was created from the constructor function's <code>prototype</code>,
so it already has definitions of all the instance properties and methods.)</p>
<p>Typically when wrapping a class instance, a finalize callback should be
provided that simply deletes the native instance that is received as the <code>data</code>
argument to the finalize callback.</p>
<p>The optional returned reference is initially a weak reference, meaning it
has a reference count of 0. Typically this reference count would be incremented
temporarily during async operations that require the instance to remain valid.</p>
<p><em>Caution</em>: The optional returned reference (if obtained) should be deleted via
<a href="#n_api_napi_delete_reference"><code>napi_delete_reference</code></a> ONLY in response to the finalize callback
invocation. If it is deleted before then, then the finalize callback may never
be invoked. Therefore, when obtaining a reference a finalize callback is also
required in order to enable correct disposal of the reference.</p>
<p>Calling <code>napi_wrap()</code> a second time on an object will return an error. To
associate another native instance with the object, use <code>napi_remove_wrap()</code>
first.</p>
<h3>napi_unwrap<span><a class="mark" href="#n_api_napi_unwrap" id="n_api_napi_unwrap">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_unwrap(napi_env env,
                        napi_value js_object,
                        void** result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] js_object</code>: The object associated with the native instance.</li>
<li><code>[out] result</code>: Pointer to the wrapped native instance.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Retrieves a native instance that was previously wrapped in a JavaScript
object using <code>napi_wrap()</code>.</p>
<p>When JavaScript code invokes a method or property accessor on the class, the
corresponding <code>napi_callback</code> is invoked. If the callback is for an instance
method or accessor, then the <code>this</code> argument to the callback is the wrapper
object; the wrapped C++ instance that is the target of the call can be obtained
then by calling <code>napi_unwrap()</code> on the wrapper object.</p>
<h3>napi_remove_wrap<span><a class="mark" href="#n_api_napi_remove_wrap" id="n_api_napi_remove_wrap">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_remove_wrap(napi_env env,
                             napi_value js_object,
                             void** result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] js_object</code>: The object associated with the native instance.</li>
<li><code>[out] result</code>: Pointer to the wrapped native instance.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Retrieves a native instance that was previously wrapped in the JavaScript
object <code>js_object</code> using <code>napi_wrap()</code> and removes the wrapping. If a finalize
callback was associated with the wrapping, it will no longer be called when the
JavaScript object becomes garbage-collected.</p>
<h3>napi_add_finalizer<span><a class="mark" href="#n_api_napi_add_finalizer" id="n_api_napi_add_finalizer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 5</span>
</div>
<pre><code class="language-c">napi_status napi_add_finalizer(napi_env env,
                               napi_value js_object,
                               void* native_object,
                               napi_finalize finalize_cb,
                               void* finalize_hint,
                               napi_ref* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] js_object</code>: The JavaScript object to which the native data will be
attached.</li>
<li><code>[in] native_object</code>: The native data that will be attached to the JavaScript
object.</li>
<li><code>[in] finalize_cb</code>: Native callback that will be used to free the
native data when the JavaScript object is ready for garbage-collection.</li>
<li><code>[in] finalize_hint</code>: Optional contextual hint that is passed to the
finalize callback.</li>
<li><code>[out] result</code>: Optional reference to the JavaScript object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Adds a <code>napi_finalize</code> callback which will be called when the JavaScript object
in <code>js_object</code> is ready for garbage collection. This API is similar to
<code>napi_wrap()</code> except that:</p>
<ul>
<li>the native data cannot be retrieved later using <code>napi_unwrap()</code>,</li>
<li>nor can it be removed later using <code>napi_remove_wrap()</code>, and</li>
<li>the API can be called multiple times with different data items in order to
attach each of them to the JavaScript object, and</li>
<li>the object manipulated by the API can be used with <code>napi_wrap()</code>.</li>
</ul>
<p><em>Caution</em>: The optional returned reference (if obtained) should be deleted via
<a href="#n_api_napi_delete_reference"><code>napi_delete_reference</code></a> ONLY in response to the finalize callback
invocation. If it is deleted before then, then the finalize callback may never
be invoked. Therefore, when obtaining a reference a finalize callback is also
required in order to enable correct disposal of the reference.</p>
<h2>Simple asynchronous operations<span><a class="mark" href="#n_api_simple_asynchronous_operations" id="n_api_simple_asynchronous_operations">#</a></span></h2>
<p>Addon modules often need to leverage async helpers from libuv as part of their
implementation. This allows them to schedule work to be executed asynchronously
so that their methods can return in advance of the work being completed. This
allows 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_async_work</code> structure which is used to manage
asynchronous workers. Instances are created/deleted with
<a href="#n_api_napi_create_async_work"><code>napi_create_async_work</code></a> and <a href="#n_api_napi_delete_async_work"><code>napi_delete_async_work</code></a>.</p>
<p>The <code>execute</code> and <code>complete</code> callbacks are functions that will be
invoked when the executor is ready to execute and when it completes its
task respectively.</p>
<p>The <code>execute</code> function should avoid making any N-API calls
that could result in the execution of JavaScript or interaction with
JavaScript objects. Most often, any code that needs to make N-API
calls should be made in <code>complete</code> callback instead.
Avoid using the <code>napi_env</code> parameter in the execute callback as
it will likely execute JavaScript.</p>
<p>These functions implement the following interfaces:</p>
<pre><code class="language-c">typedef void (*napi_async_execute_callback)(napi_env env,
                                            void* data);
typedef void (*napi_async_complete_callback)(napi_env env,
                                             napi_status status,
                                             void* data);
</code></pre>
<p>When these methods are invoked, the <code>data</code> parameter passed will be the
addon-provided <code>void*</code> data that was passed into the
<code>napi_create_async_work</code> call.</p>
<p>Once created the async worker can be queued
for execution using the <a href="#n_api_napi_queue_async_work"><code>napi_queue_async_work</code></a> function:</p>
<pre><code class="language-c">napi_status napi_queue_async_work(napi_env env,
                                  napi_async_work work);
</code></pre>
<p><a href="#n_api_napi_cancel_async_work"><code>napi_cancel_async_work</code></a> can be used if the work needs
to be cancelled before the work has started execution.</p>
<p>After calling <a href="#n_api_napi_cancel_async_work"><code>napi_cancel_async_work</code></a>, the <code>complete</code> callback
will be invoked with a status value of <code>napi_cancelled</code>.
The work should not be deleted before the <code>complete</code>
callback invocation, even when it was cancelled.</p>
<h3>napi_create_async_work<span><a class="mark" href="#n_api_napi_create_async_work" id="n_api_napi_create_async_work">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.6.0</td>
<td><p>Added <code>async_resource</code> and <code>async_resource_name</code> parameters.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><span>Added in: v8.0.0</span></p></td></tr>
</tbody></table>
</details>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_async_work(napi_env env,
                                   napi_value async_resource,
                                   napi_value async_resource_name,
                                   napi_async_execute_callback execute,
                                   napi_async_complete_callback complete,
                                   void* data,
                                   napi_async_work* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] async_resource</code>: An optional object associated with the async work
that will be passed to possible <code>async_hooks</code> <a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a>.</li>
<li><code>[in] async_resource_name</code>: Identifier for the kind of resource that is being
provided for diagnostic information exposed by the <code>async_hooks</code> API.</li>
<li><code>[in] execute</code>: The native function which should be called to execute the
logic asynchronously. The given function is called from a worker pool thread
and can execute in parallel with the main event loop thread.</li>
<li><code>[in] complete</code>: The native function which will be called when the
asynchronous logic is completed or is cancelled. The given function is called
from the main event loop thread.</li>
<li><code>[in] data</code>: User-provided data context. This will be passed back into the
execute and complete functions.</li>
<li><code>[out] result</code>: <code>napi_async_work*</code> which is the handle to the newly created
async work.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API allocates a work object that is used to execute logic asynchronously.
It should be freed using <a href="#n_api_napi_delete_async_work"><code>napi_delete_async_work</code></a> once the work is no longer
required.</p>
<p><code>async_resource_name</code> should be a null-terminated, UTF-8-encoded string.</p>
<p>The <code>async_resource_name</code> identifier is provided by the user and should be
representative of the type of async work being performed. It is also recommended
to apply namespacing to the identifier, e.g. by including the module name. See
the <a href="#async_hooks_type"><code>async_hooks</code> documentation</a> for more information.</p>
<h3>napi_delete_async_work<span><a class="mark" href="#n_api_napi_delete_async_work" id="n_api_napi_delete_async_work">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_delete_async_work(napi_env env,
                                   napi_async_work work);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API frees a previously allocated work object.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h3>napi_queue_async_work<span><a class="mark" href="#n_api_napi_queue_async_work" id="n_api_napi_queue_async_work">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_queue_async_work(napi_env env,
                                  napi_async_work work);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API requests that the previously allocated work be scheduled
for execution. Once it returns successfully, this API must not be called again
with the same <code>napi_async_work</code> item or the result will be undefined.</p>
<h3>napi_cancel_async_work<span><a class="mark" href="#n_api_napi_cancel_async_work" id="n_api_napi_cancel_async_work">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_cancel_async_work(napi_env env,
                                   napi_async_work work);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] work</code>: The handle returned by the call to <code>napi_create_async_work</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API cancels queued work if it has not yet
been started. If it has already started executing, it cannot be
cancelled and <code>napi_generic_failure</code> will be returned. If successful,
the <code>complete</code> callback will be invoked with a status value of
<code>napi_cancelled</code>. The work should not be deleted before the <code>complete</code>
callback invocation, even if it has been successfully cancelled.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h2>Custom asynchronous operations<span><a class="mark" href="#n_api_custom_asynchronous_operations" id="n_api_custom_asynchronous_operations">#</a></span></h2>
<p>The simple asynchronous work APIs above may not be appropriate for every
scenario. When using any other asynchronous mechanism, the following APIs
are necessary to ensure an asynchronous operation is properly tracked by
the runtime.</p>
<h3>napi_async_init<span><a class="mark" href="#n_api_napi_async_init" id="n_api_napi_async_init">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.6.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_async_init(napi_env env,
                            napi_value async_resource,
                            napi_value async_resource_name,
                            napi_async_context* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] async_resource</code>: Object associated with the async work
that will be passed to possible <code>async_hooks</code> <a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a>.
In order to retain ABI compatibility with previous versions,
passing <code>NULL</code> for <code>async_resource</code> will not result in an error, however,
this will result incorrect operation of async hooks for the
napi_async_context created. Potential issues include
loss of async context when using the AsyncLocalStorage API.</li>
<li><code>[in] async_resource_name</code>: Identifier for the kind of resource
that is being provided for diagnostic information exposed by the
<code>async_hooks</code> API.</li>
<li><code>[out] result</code>: The initialized async context.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<h3>napi_async_destroy<span><a class="mark" href="#n_api_napi_async_destroy" id="n_api_napi_async_destroy">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.6.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_async_destroy(napi_env env,
                               napi_async_context async_context);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] async_context</code>: The async context to be destroyed.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h3>napi_make_callback<span><a class="mark" href="#n_api_napi_make_callback" id="n_api_napi_make_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.6.0</td>
<td><p>Added <code>async_context</code> parameter.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><span>Added in: v8.0.0</span></p></td></tr>
</tbody></table>
</details>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_make_callback(napi_env env,
                                           napi_async_context async_context,
                                           napi_value recv,
                                           napi_value func,
                                           size_t 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>
<p>Any <code>process.nextTick</code>s or Promises scheduled on the microtask queue by
JavaScript during the callback are ran before returning back to C/C++.</p>
<h3>napi_open_callback_scope<span><a class="mark" href="#n_api_napi_open_callback_scope" id="n_api_napi_open_callback_scope">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
<span>N-API version: 3</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_open_callback_scope(napi_env env,
                                                 napi_value resource_object,
                                                 napi_async_context context,
                                                 napi_callback_scope* result)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] resource_object</code>: An object associated with the async work
that will be passed to possible <code>async_hooks</code> <a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a>.</li>
<li><code>[in] context</code>: Context for the async operation that is invoking the callback.
This should be a value previously obtained from <a href="#n_api_napi_async_init"><code>napi_async_init</code></a>.</li>
<li><code>[out] result</code>: The newly created scope.</li>
</ul>
<p>There are cases (for example, resolving promises) where it is
necessary to have the equivalent of the scope associated with a callback
in place when making certain N-API calls. If there is no other script on
the stack the <a href="#n_api_napi_open_callback_scope"><code>napi_open_callback_scope</code></a> and
<a href="#n_api_napi_close_callback_scope"><code>napi_close_callback_scope</code></a> functions can be used to open/close
the required scope.</p>
<h3>napi_close_callback_scope<span><a class="mark" href="#n_api_napi_close_callback_scope" id="n_api_napi_close_callback_scope">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
<span>N-API version: 3</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_close_callback_scope(napi_env env,
                                                  napi_callback_scope scope)
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] scope</code>: The scope to be closed.</li>
</ul>
<p>This API can be called even if there is a pending JavaScript exception.</p>
<h2>Version management<span><a class="mark" href="#n_api_version_management" id="n_api_version_management">#</a></span></h2>
<h3>napi_get_node_version<span><a class="mark" href="#n_api_napi_get_node_version" id="n_api_napi_get_node_version">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">typedef struct {
  uint32_t major;
  uint32_t minor;
  uint32_t patch;
  const char* release;
} napi_node_version;

napi_status napi_get_node_version(napi_env env,
                                  const napi_node_version** version);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] version</code>: A pointer to version information for Node.js itself.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This function fills the <code>version</code> struct with the major, minor, and patch
version of Node.js that is currently running, and the <code>release</code> field with the
value of <a href="#process_process_release"><code>process.release.name</code></a>.</p>
<p>The returned buffer is statically allocated and does not need to be freed.</p>
<h3>napi_get_version<span><a class="mark" href="#n_api_napi_get_version" id="n_api_napi_get_version">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_get_version(napi_env env,
                             uint32_t* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: The highest version of N-API supported.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the highest N-API version supported by the
Node.js runtime. N-API is planned to be additive such that
newer releases of Node.js may support additional API functions.
In order to allow an addon to use a newer function when running with
versions of Node.js that support it, while providing
fallback behavior when running with Node.js versions that don't
support it:</p>
<ul>
<li>Call <code>napi_get_version()</code> to determine if the API is available.</li>
<li>If available, dynamically load a pointer to the function using <code>uv_dlsym()</code>.</li>
<li>Use the dynamically loaded pointer to invoke the function.</li>
<li>If the function is not available, provide an alternate implementation
that does not use the function.</li>
</ul>
<h2>Memory management<span><a class="mark" href="#n_api_memory_management" id="n_api_memory_management">#</a></span></h2>
<h3>napi_adjust_external_memory<span><a class="mark" href="#n_api_napi_adjust_external_memory" id="n_api_napi_adjust_external_memory">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_adjust_external_memory(napi_env env,
                                                    int64_t change_in_bytes,
                                                    int64_t* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] change_in_bytes</code>: The change in externally allocated memory that is kept
alive by JavaScript objects.</li>
<li><code>[out] result</code>: The adjusted value</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This function gives V8 an indication of the amount of externally allocated
memory that is kept alive by JavaScript objects (i.e. a JavaScript object
that points to its own memory allocated by a native module). Registering
externally allocated memory will trigger global garbage collections more
often than it would otherwise.</p>
<h2>Promises<span><a class="mark" href="#n_api_promises" id="n_api_promises">#</a></span></h2>
<p>N-API provides facilities for creating <code>Promise</code> objects as described in
<a href="https://tc39.github.io/ecma262/#sec-promise-objects">Section 25.4</a> of the ECMA specification. It implements promises as a pair of
objects. When a promise is created by <code>napi_create_promise()</code>, a "deferred"
object is created and returned alongside the <code>Promise</code>. The deferred object is
bound to the created <code>Promise</code> and is the only means to resolve or reject the
<code>Promise</code> using <code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code>. The
deferred object that is created by <code>napi_create_promise()</code> is freed by
<code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code>. The <code>Promise</code> object may
be returned to JavaScript where it can be used in the usual fashion.</p>
<p>For example, to create a promise and pass it to an asynchronous worker:</p>
<pre><code class="language-c">napi_deferred deferred;
napi_value promise;
napi_status status;

// Create the promise.
status = napi_create_promise(env, &#x26;deferred, &#x26;promise);
if (status != napi_ok) return NULL;

// Pass the deferred to a function that performs an asynchronous action.
do_something_asynchronous(deferred);

// Return the promise to JS
return promise;
</code></pre>
<p>The above function <code>do_something_asynchronous()</code> would perform its asynchronous
action and then it would resolve or reject the deferred, thereby concluding the
promise and freeing the deferred:</p>
<pre><code class="language-c">napi_deferred deferred;
napi_value undefined;
napi_status status;

// Create a value with which to conclude the deferred.
status = napi_get_undefined(env, &#x26;undefined);
if (status != napi_ok) return NULL;

// Resolve or reject the promise associated with the deferred depending on
// whether the asynchronous action succeeded.
if (asynchronous_action_succeeded) {
  status = napi_resolve_deferred(env, deferred, undefined);
} else {
  status = napi_reject_deferred(env, deferred, undefined);
}
if (status != napi_ok) return NULL;

// At this point the deferred has been freed, so we should assign NULL to it.
deferred = NULL;
</code></pre>
<h3>napi_create_promise<span><a class="mark" href="#n_api_napi_create_promise" id="n_api_napi_create_promise">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_create_promise(napi_env env,
                                napi_deferred* deferred,
                                napi_value* promise);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] deferred</code>: A newly created deferred object which can later be passed to
<code>napi_resolve_deferred()</code> or <code>napi_reject_deferred()</code> to resolve resp. reject
the associated promise.</li>
<li><code>[out] promise</code>: The JavaScript promise associated with the deferred object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a deferred object and a JavaScript promise.</p>
<h3>napi_resolve_deferred<span><a class="mark" href="#n_api_napi_resolve_deferred" id="n_api_napi_resolve_deferred">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_resolve_deferred(napi_env env,
                                  napi_deferred deferred,
                                  napi_value resolution);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] deferred</code>: The deferred object whose associated promise to resolve.</li>
<li><code>[in] resolution</code>: The value with which to resolve the promise.</li>
</ul>
<p>This API resolves a JavaScript promise by way of the deferred object
with which it is associated. Thus, it can only be used to resolve JavaScript
promises for which the corresponding deferred object is available. This
effectively means that the promise must have been created using
<code>napi_create_promise()</code> and the deferred object returned from that call must
have been retained in order to be passed to this API.</p>
<p>The deferred object is freed upon successful completion.</p>
<h3>napi_reject_deferred<span><a class="mark" href="#n_api_napi_reject_deferred" id="n_api_napi_reject_deferred">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_reject_deferred(napi_env env,
                                 napi_deferred deferred,
                                 napi_value rejection);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] deferred</code>: The deferred object whose associated promise to resolve.</li>
<li><code>[in] rejection</code>: The value with which to reject the promise.</li>
</ul>
<p>This API rejects a JavaScript promise by way of the deferred object
with which it is associated. Thus, it can only be used to reject JavaScript
promises for which the corresponding deferred object is available. This
effectively means that the promise must have been created using
<code>napi_create_promise()</code> and the deferred object returned from that call must
have been retained in order to be passed to this API.</p>
<p>The deferred object is freed upon successful completion.</p>
<h3>napi_is_promise<span><a class="mark" href="#n_api_napi_is_promise" id="n_api_napi_is_promise">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">napi_status napi_is_promise(napi_env env,
                            napi_value value,
                            bool* is_promise);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] value</code>: The value to examine</li>
<li><code>[out] is_promise</code>: Flag indicating whether <code>promise</code> is a native promise
object (that is, a promise object created by the underlying engine).</li>
</ul>
<h2>Script execution<span><a class="mark" href="#n_api_script_execution" id="n_api_script_execution">#</a></span></h2>
<p>N-API provides an API for executing a string containing JavaScript using the
underlying JavaScript engine.</p>
<h3>napi_run_script<span><a class="mark" href="#n_api_napi_run_script" id="n_api_napi_run_script">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_run_script(napi_env env,
                                        napi_value script,
                                        napi_value* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] script</code>: A JavaScript string containing the script to execute.</li>
<li><code>[out] result</code>: The value resulting from having executed the script.</li>
</ul>
<p>This function executes a string of JavaScript code and returns its result with
the following caveats:</p>
<ul>
<li>Unlike <code>eval</code>, this function does not allow the script to access the current
lexical scope, and therefore also does not allow to access the
<a href="#modules_the_module_scope">module scope</a>, meaning that pseudo-globals such as <code>require</code> will not be
available.</li>
<li>The script can access the <a href="globals.html">global scope</a>. Function and <code>var</code> declarations
in the script will be added to the <a href="#globals_global"><code>global</code></a> object. Variable declarations
made using <code>let</code> and <code>const</code> will be visible globally, but will not be added
to the <a href="#globals_global"><code>global</code></a> object.</li>
<li>The value of <code>this</code> is <a href="#globals_global"><code>global</code></a> within the script.</li>
</ul>
<h2>libuv event loop<span><a class="mark" href="#n_api_libuv_event_loop" id="n_api_libuv_event_loop">#</a></span></h2>
<p>N-API provides a function for getting the current event loop associated with
a specific <code>napi_env</code>.</p>
<h3>napi_get_uv_event_loop<span><a class="mark" href="#n_api_napi_get_uv_event_loop" id="n_api_napi_get_uv_event_loop">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.10.0, v9.3.0</span>
<span>N-API version: 2</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status napi_get_uv_event_loop(napi_env env,
                                               struct uv_loop_s** 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>
<h2>Asynchronous thread-safe function calls<span><a class="mark" href="#n_api_asynchronous_thread_safe_function_calls" id="n_api_asynchronous_thread_safe_function_calls">#</a></span></h2>
<p>JavaScript functions can normally only be called from a native addon's main
thread. If an addon creates additional threads, then N-API functions that
require a <code>napi_env</code>, <code>napi_value</code>, or <code>napi_ref</code> must not be called from those
threads.</p>
<p>When an addon has additional threads and JavaScript functions need to be invoked
based on the processing completed by those threads, those threads must
communicate with the addon's main thread so that the main thread can invoke the
JavaScript function on their behalf. The thread-safe function APIs provide an
easy way to do this.</p>
<p>These APIs provide the type <code>napi_threadsafe_function</code> as well as APIs to
create, destroy, and call objects of this type.
<code>napi_create_threadsafe_function()</code> creates a persistent reference to a
<code>napi_value</code> that holds a JavaScript function which can be called from multiple
threads. The calls happen asynchronously. This means that values with which the
JavaScript callback is to be called will be placed in a queue, and, for each
value in the queue, a call will eventually be made to the JavaScript function.</p>
<p>Upon creation of a <code>napi_threadsafe_function</code> a <code>napi_finalize</code> callback can be
provided. This callback will be invoked on the main thread when the thread-safe
function is about to be destroyed. It receives the context and the finalize data
given during construction, and provides an opportunity for cleaning up after the
threads e.g. by calling <code>uv_thread_join()</code>. <strong>Aside from the main loop thread,
no threads should be using the thread-safe function after the finalize callback
completes.</strong></p>
<p>The <code>context</code> given during the call to <code>napi_create_threadsafe_function()</code> can
be retrieved from any thread with a call to
<code>napi_get_threadsafe_function_context()</code>.</p>
<h3>Calling a thread-safe function<span><a class="mark" href="#n_api_calling_a_thread_safe_function" id="n_api_calling_a_thread_safe_function">#</a></span></h3>
<p><code>napi_call_threadsafe_function()</code> can be used for initiating a call into
JavaScript. <code>napi_call_threadsafe_function()</code> accepts a parameter which controls
whether the API behaves blockingly. If set to <code>napi_tsfn_nonblocking</code>, the API
behaves non-blockingly, returning <code>napi_queue_full</code> if the queue was full,
preventing data from being successfully added to the queue. If set to
<code>napi_tsfn_blocking</code>, the API blocks until space becomes available in the queue.
<code>napi_call_threadsafe_function()</code> never blocks if the thread-safe function was
created with a maximum queue size of 0.</p>
<p>The actual call into JavaScript is controlled by the callback given via the
<code>call_js_cb</code> parameter. <code>call_js_cb</code> is invoked on the main thread once for each
value that was placed into the queue by a successful call to
<code>napi_call_threadsafe_function()</code>. If such a callback is not given, a default
callback will be used, and the resulting JavaScript call will have no arguments.
The <code>call_js_cb</code> callback receives the JavaScript function to call as a
<code>napi_value</code> in its parameters, as well as the <code>void*</code> context pointer used when
creating the <code>napi_threadsafe_function</code>, and the next data pointer that was
created by one of the secondary threads. The callback can then use an API such
as <code>napi_call_function()</code> to call into JavaScript.</p>
<p>The callback may also be invoked with <code>env</code> and <code>call_js_cb</code> both set to <code>NULL</code>
to indicate that calls into JavaScript are no longer possible, while items
remain in the queue that may need to be freed. This normally occurs when the
Node.js process exits while there is a thread-safe function still active.</p>
<p>It is not necessary to call into JavaScript via <code>napi_make_callback()</code> because
N-API runs <code>call_js_cb</code> in a context appropriate for callbacks.</p>
<h3>Reference counting of thread-safe functions<span><a class="mark" href="#n_api_reference_counting_of_thread_safe_functions" id="n_api_reference_counting_of_thread_safe_functions">#</a></span></h3>
<p>Threads can be added to and removed from a <code>napi_threadsafe_function</code> object
during its existence. Thus, in addition to specifying an initial number of
threads upon creation, <code>napi_acquire_threadsafe_function</code> can be called to
indicate that a new thread will start making use of the thread-safe function.
Similarly, <code>napi_release_threadsafe_function</code> can be called to indicate that an
existing thread will stop making use of the thread-safe function.</p>
<p><code>napi_threadsafe_function</code> objects are destroyed when every thread which uses
the object has called <code>napi_release_threadsafe_function()</code> or has received a
return status of <code>napi_closing</code> in response to a call to
<code>napi_call_threadsafe_function</code>. The queue is emptied before the
<code>napi_threadsafe_function</code> is destroyed. <code>napi_release_threadsafe_function()</code>
should be the last API call made in conjunction with a given
<code>napi_threadsafe_function</code>, because after the call completes, there is no
guarantee that the <code>napi_threadsafe_function</code> is still allocated. For the same
reason, do not make use of a thread-safe function
after receiving a return value of <code>napi_closing</code> in response to a call to
<code>napi_call_threadsafe_function</code>. Data associated with the
<code>napi_threadsafe_function</code> can be freed in its <code>napi_finalize</code> callback which
was passed to <code>napi_create_threadsafe_function()</code>. The parameter
<code>initial_thread_count</code> of <code>napi_create_threadsafe_function</code> marks the initial
number of aquisitions of the thread-safe functions, instead of calling
<code>napi_acquire_threadsafe_function</code> multiple times at creation.</p>
<p>Once the number of threads making use of a <code>napi_threadsafe_function</code> reaches
zero, no further threads can start making use of it by calling
<code>napi_acquire_threadsafe_function()</code>. In fact, all subsequent API calls
associated with it, except <code>napi_release_threadsafe_function()</code>, will return an
error value of <code>napi_closing</code>.</p>
<p>The thread-safe function can be "aborted" by giving a value of <code>napi_tsfn_abort</code>
to <code>napi_release_threadsafe_function()</code>. This will cause all subsequent APIs
associated with the thread-safe function except
<code>napi_release_threadsafe_function()</code> to return <code>napi_closing</code> even before its
reference count reaches zero. In particular, <code>napi_call_threadsafe_function()</code>
will return <code>napi_closing</code>, thus informing the threads that it is no longer
possible to make asynchronous calls to the thread-safe function. This can be
used as a criterion for terminating the thread. <strong>Upon receiving a return value
of <code>napi_closing</code> from <code>napi_call_threadsafe_function()</code> a thread must make no
further use of the thread-safe function because it is no longer guaranteed to
be allocated.</strong></p>
<h3>Deciding whether to keep the process running<span><a class="mark" href="#n_api_deciding_whether_to_keep_the_process_running" id="n_api_deciding_whether_to_keep_the_process_running">#</a></span></h3>
<p>Similarly to libuv handles, thread-safe functions can be "referenced" and
"unreferenced". A "referenced" thread-safe function will cause the event loop on
the thread on which it is created to remain alive until the thread-safe function
is destroyed. In contrast, an "unreferenced" thread-safe function will not
prevent the event loop from exiting. The APIs <code>napi_ref_threadsafe_function</code> and
<code>napi_unref_threadsafe_function</code> exist for this purpose.</p>
<p>Neither does <code>napi_unref_threadsafe_function</code> mark the thread-safe functions as
able to be destroyed nor does <code>napi_ref_threadsafe_function</code> prevent it from
being destroyed.</p>
<h3>napi_create_threadsafe_function<span><a class="mark" href="#n_api_napi_create_threadsafe_function" id="n_api_napi_create_threadsafe_function">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.6.0</td>
<td><p>Made <code>func</code> parameter optional with custom <code>call_js_cb</code>.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p><span>Added in: v10.6.0</span></p></td></tr>
</tbody></table>
</details>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
napi_create_threadsafe_function(napi_env env,
                                napi_value func,
                                napi_value async_resource,
                                napi_value async_resource_name,
                                size_t max_queue_size,
                                size_t initial_thread_count,
                                void* thread_finalize_data,
                                napi_finalize thread_finalize_cb,
                                void* context,
                                napi_threadsafe_function_call_js call_js_cb,
                                napi_threadsafe_function* result);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] func</code>: An optional JavaScript function to call from another thread. It
must be provided if <code>NULL</code> is passed to <code>call_js_cb</code>.</li>
<li><code>[in] async_resource</code>: An optional object associated with the async work that
will be passed to possible <code>async_hooks</code> <a href="#async_hooks_init_asyncid_type_triggerasyncid_resource"><code>init</code> hooks</a>.</li>
<li><code>[in] async_resource_name</code>: A JavaScript string to provide an identifier for
the kind of resource that is being provided for diagnostic information exposed
by the <code>async_hooks</code> API.</li>
<li><code>[in] max_queue_size</code>: Maximum size of the queue. <code>0</code> for no limit.</li>
<li><code>[in] initial_thread_count</code>: The initial number of acquisitions, i.e. the
initial number of threads, including the main thread, which will be making use
of this function.</li>
<li><code>[in] thread_finalize_data</code>: Optional data to be passed to <code>thread_finalize_cb</code>.</li>
<li><code>[in] thread_finalize_cb</code>: Optional function to call when the
<code>napi_threadsafe_function</code> is being destroyed.</li>
<li><code>[in] context</code>: Optional data to attach to the resulting
<code>napi_threadsafe_function</code>.</li>
<li><code>[in] call_js_cb</code>: Optional callback which calls the JavaScript function in
response to a call on a different thread. This callback will be called on the
main thread. If not given, the JavaScript function will be called with no
parameters and with <code>undefined</code> as its <code>this</code> value.</li>
<li><code>[out] result</code>: The asynchronous thread-safe JavaScript function.</li>
</ul>
<h3>napi_get_threadsafe_function_context<span><a class="mark" href="#n_api_napi_get_threadsafe_function_context" id="n_api_napi_get_threadsafe_function_context">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
napi_get_threadsafe_function_context(napi_threadsafe_function func,
                                     void** result);
</code></pre>
<ul>
<li><code>[in] func</code>: The thread-safe function for which to retrieve the context.</li>
<li><code>[out] result</code>: The location where to store the context.</li>
</ul>
<p>This API may be called from any thread which makes use of <code>func</code>.</p>
<h3>napi_call_threadsafe_function<span><a class="mark" href="#n_api_napi_call_threadsafe_function" id="n_api_napi_call_threadsafe_function">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
napi_call_threadsafe_function(napi_threadsafe_function func,
                              void* data,
                              napi_threadsafe_function_call_mode is_blocking);
</code></pre>
<ul>
<li><code>[in] func</code>: The asynchronous thread-safe JavaScript function to invoke.</li>
<li><code>[in] data</code>: Data to send into JavaScript via the callback <code>call_js_cb</code>
provided during the creation of the thread-safe JavaScript function.</li>
<li><code>[in] is_blocking</code>: Flag whose value can be either <code>napi_tsfn_blocking</code> to
indicate that the call should block if the queue is full or
<code>napi_tsfn_nonblocking</code> to indicate that the call should return immediately
with a status of <code>napi_queue_full</code> whenever the queue is full.</li>
</ul>
<p>This API will return <code>napi_closing</code> if <code>napi_release_threadsafe_function()</code> was
called with <code>abort</code> set to <code>napi_tsfn_abort</code> from any thread. The value is only
added to the queue if the API returns <code>napi_ok</code>.</p>
<p>This API may be called from any thread which makes use of <code>func</code>.</p>
<h3>napi_acquire_threadsafe_function<span><a class="mark" href="#n_api_napi_acquire_threadsafe_function" id="n_api_napi_acquire_threadsafe_function">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
napi_acquire_threadsafe_function(napi_threadsafe_function func);
</code></pre>
<ul>
<li><code>[in] func</code>: The asynchronous thread-safe JavaScript function to start making
use of.</li>
</ul>
<p>A thread should call this API before passing <code>func</code> to any other thread-safe
function APIs to indicate that it will be making use of <code>func</code>. This prevents
<code>func</code> from being destroyed when all other threads have stopped making use of
it.</p>
<p>This API may be called from any thread which will start making use of <code>func</code>.</p>
<h3>napi_release_threadsafe_function<span><a class="mark" href="#n_api_napi_release_threadsafe_function" id="n_api_napi_release_threadsafe_function">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
napi_release_threadsafe_function(napi_threadsafe_function func,
                                 napi_threadsafe_function_release_mode mode);
</code></pre>
<ul>
<li><code>[in] func</code>: The asynchronous thread-safe JavaScript function whose reference
count to decrement.</li>
<li><code>[in] mode</code>: Flag whose value can be either <code>napi_tsfn_release</code> to indicate
that the current thread will make no further calls to the thread-safe
function, or <code>napi_tsfn_abort</code> to indicate that in addition to the current
thread, no other thread should make any further calls to the thread-safe
function. If set to <code>napi_tsfn_abort</code>, further calls to
<code>napi_call_threadsafe_function()</code> will return <code>napi_closing</code>, and no further
values will be placed in the queue.</li>
</ul>
<p>A thread should call this API when it stops making use of <code>func</code>. Passing <code>func</code>
to any thread-safe APIs after having called this API has undefined results, as
<code>func</code> may have been destroyed.</p>
<p>This API may be called from any thread which will stop making use of <code>func</code>.</p>
<h3>napi_ref_threadsafe_function<span><a class="mark" href="#n_api_napi_ref_threadsafe_function" id="n_api_napi_ref_threadsafe_function">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] func</code>: The thread-safe function to reference.</li>
</ul>
<p>This API is used to indicate that the event loop running on the main thread
should not exit until <code>func</code> has been destroyed. Similar to <a href="http://docs.libuv.org/en/v1.x/handle.html#c.uv_ref"><code>uv_ref</code></a> it is
also idempotent.</p>
<p>Neither does <code>napi_unref_threadsafe_function</code> mark the thread-safe functions as
able to be destroyed nor does <code>napi_ref_threadsafe_function</code> prevent it from
being destroyed. <code>napi_acquire_threadsafe_function</code> and
<code>napi_release_threadsafe_function</code> are available for that purpose.</p>
<p>This API may only be called from the main thread.</p>
<h3>napi_unref_threadsafe_function<span><a class="mark" href="#n_api_napi_unref_threadsafe_function" id="n_api_napi_unref_threadsafe_function">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func);
</code></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] func</code>: The thread-safe function to unreference.</li>
</ul>
<p>This API is used to indicate that the event loop running on the main thread
may exit before <code>func</code> is destroyed. Similar to <a href="http://docs.libuv.org/en/v1.x/handle.html#c.uv_unref"><code>uv_unref</code></a> it is also
idempotent.</p>
<p>This API may only be called from the main thread.</p>
<h1>Child process<span><a class="mark" href="#child_process_child_process" id="child_process_child_process">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>child_process</code> module provides the ability to spawn child processes in
a manner that is similar, but not identical, to <a href="http://man7.org/linux/man-pages/man3/popen.3.html"><code>popen(3)</code></a>. This capability
is primarily provided by the <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> function:</p>
<pre><code class="language-js">const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.error(`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 command lookup will be performed using <code>options.env.PATH</code> environment
variable if passed in <code>options</code> object, otherwise <code>process.env.PATH</code> will be
used. To account for the fact that Windows environment variables are
case-insensitive Node.js will lexicographically sort all <code>env</code> keys and choose
the first one case-insensitively matching <code>PATH</code> to perform command lookup.
This may lead to issues on Windows when passing objects to <code>env</code> option that
have multiple variants of <code>PATH</code> variable.</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>. 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>.</p>
<ul>
<li><a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>: spawns a shell and runs a command within that
shell, passing the <code>stdout</code> and <code>stderr</code> to a callback function when
complete.</li>
<li><a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a>: similar to <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> except
that it spawns the command directly without first spawning a shell by
default.</li>
<li><a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>: spawns a new Node.js process and invokes a
specified module with an IPC communication channel established that allows
sending messages between parent and child.</li>
<li><a href="#child_process_child_process_execsync_command_options"><code>child_process.execSync()</code></a>: a synchronous version of
<a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> that will 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 will block the Node.js event loop.</li>
</ul>
<p>For certain use cases, such as automating shell scripts, the
<a href="#child_process_synchronous_process_creation">synchronous counterparts</a> may be more convenient. In many cases, however,
the synchronous methods can have significant impact on performance due to
stalling the event loop while spawned processes complete.</p>
<h2>Asynchronous process creation<span><a class="mark" href="#child_process_asynchronous_process_creation" id="child_process_asynchronous_process_creation">#</a></span></h2>
<p>The <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>, <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>, <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>,
and <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a> methods all follow the idiomatic asynchronous
programming pattern typical of other Node.js APIs.</p>
<p>Each of the methods returns a <a href="#child_process_child_process"><code>ChildProcess</code></a> instance. These objects
implement the Node.js <a href="#events_class_eventemitter"><code>EventEmitter</code></a> API, allowing the parent process to
register listener functions that are called when certain events occur during
the life cycle of the child process.</p>
<p>The <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> and <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a> methods
additionally allow for an optional <code>callback</code> function to be specified that is
invoked when the child process terminates.</p>
<h3>Spawning <code>.bat</code> and <code>.cmd</code> files on Windows<span><a class="mark" href="#child_process_spawning_bat_and_cmd_files_on_windows" id="child_process_spawning_bat_and_cmd_files_on_windows">#</a></span></h3>
<p>The importance of the distinction between <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> and
<a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a> can vary based on platform. On Unix-type
operating systems (Unix, Linux, macOS) <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a> can be
more efficient because it does not spawn a shell by default. On Windows,
however, <code>.bat</code> and <code>.cmd</code> files are not executable on their own without a
terminal, and therefore cannot be launched using <a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a>.
When running on Windows, <code>.bat</code> and <code>.cmd</code> files can be invoked using
<a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> with the <code>shell</code> option set, with
<a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>, or by spawning <code>cmd.exe</code> and passing the <code>.bat</code> or
<code>.cmd</code> file as an argument (which is what the <code>shell</code> option and
<a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> do). In any case, if the script filename contains
spaces it needs to be quoted.</p>
<pre><code class="language-js">// On Windows Only...
const { spawn } = require('child_process');
const bat = spawn('cmd.exe', ['/c', 'my.bat']);

bat.stdout.on('data', (data) => {
  console.log(data.toString());
});

bat.stderr.on('data', (data) => {
  console.error(data.toString());
});

bat.on('exit', (code) => {
  console.log(`Child exited with code ${code}`);
});
</code></pre>
<pre><code class="language-js">// OR...
const { exec, spawn } = 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><code>child_process.exec(command[, options][, callback])</code><span><a class="mark" href="#child_process_child_process_exec_command_options_callback" id="child_process_child_process_exec_command_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The command to run, with space-separated arguments.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Current working directory of the child process.
<strong>Default:</strong> <code>null</code>.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> Shell to execute the command with. See
<a href="#child_process_shell_requirements">Shell requirements</a> and <a href="#child_process_default_windows_shell">Default Windows shell</a>. <strong>Default:</strong>
<code>'/bin/sh'</code> on Unix, <code>process.env.ComSpec</code> on Windows.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;number></a> Largest amount of data in bytes allowed on stdout or
stderr. If exceeded, the child process is terminated and any output is
truncated. See caveat at <a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a>.
<strong>Default:</strong> <code>1024 * 1024</code>.</li>
<li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Hide the subprocess console window that would
normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> called with the output when process terminates.</p>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#child_process_class_childprocess" class="type">&#x3C;ChildProcess></a></li>
</ul>
<p>Spawns a shell then executes the <code>command</code> within that shell, buffering any
generated output. The <code>command</code> string passed to the exec function is processed
directly by the shell and special characters (vary based on
<a href="https://en.wikipedia.org/wiki/List_of_command-line_interpreters">shell</a>)
need to be dealt with accordingly:</p>
<pre><code class="language-js">exec('"/path/to/test file/test.sh" arg1 arg2');
// Double quotes are used so that the space in the path is not interpreted as
// a delimiter of multiple arguments.

exec('echo "The \\$HOME variable is $HOME"');
// The $HOME variable is escaped in the first instance, but not in the second.
</code></pre>
<p><strong>Never pass unsanitized user input to this function. Any input containing shell
metacharacters may be used to trigger arbitrary command execution.</strong></p>
<p>If a <code>callback</code> function is provided, it is called with the arguments
<code>(error, stdout, stderr)</code>. On success, <code>error</code> will be <code>null</code>. On error,
<code>error</code> will be an instance of <a href="#errors_class_error"><code>Error</code></a>. The <code>error.code</code> property will be
the exit code of the child process while <code>error.signal</code> will be set to the
signal that terminated the process. Any exit code other than <code>0</code> is considered
to be an error.</p>
<p>The <code>stdout</code> and <code>stderr</code> arguments passed to the callback will contain the
stdout and stderr output of the child process. By default, Node.js will decode
the output as UTF-8 and pass strings to the callback. The <code>encoding</code> option
can be used to specify the character encoding used to decode the stdout and
stderr output. If <code>encoding</code> is <code>'buffer'</code>, or an unrecognized character
encoding, <code>Buffer</code> objects will be passed to the callback instead.</p>
<pre><code class="language-js">const { exec } = require('child_process');
exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.error(`stderr: ${stderr}`);
});
</code></pre>
<p>If <code>timeout</code> is greater than <code>0</code>, the parent will send the signal
identified by the <code>killSignal</code> property (the default is <code>'SIGTERM'</code>) if the
child runs longer than <code>timeout</code> milliseconds.</p>
<p>Unlike the <a href="http://man7.org/linux/man-pages/man3/exec.3.html"><code>exec(3)</code></a> POSIX system call, <code>child_process.exec()</code> does not replace
the existing process and uses a shell to execute the command.</p>
<p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns
a <code>Promise</code> for an <code>Object</code> with <code>stdout</code> and <code>stderr</code> properties. The returned
<code>ChildProcess</code> instance is attached to the <code>Promise</code> as a <code>child</code> property. 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 two additional properties <code>stdout</code> and <code>stderr</code>.</p>
<pre><code class="language-js">const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function lsExample() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.error('stderr:', stderr);
}
lsExample();
</code></pre>
<h3><code>child_process.execFile(file[, args][, options][, callback])</code><span><a class="mark" href="#child_process_child_process_execfile_file_args_options_callback" id="child_process_child_process_execfile_file_args_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v0.1.91</td>
<td><p><span>Added in: v0.1.91</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string[]></a> List of string arguments.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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">&#x3C;number></a> Largest amount of data in bytes allowed on stdout or
stderr. If exceeded, the child process is terminated and any output is
truncated. See caveat at <a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a>.
<strong>Default:</strong> <code>1024 * 1024</code>.</li>
<li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>windowsHide</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;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">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses
<code>'/bin/sh'</code> on Unix, and <code>process.env.ComSpec</code> on Windows. A different
shell can be specified as a string. See <a href="#child_process_shell_requirements">Shell requirements</a> and
<a href="#child_process_default_windows_shell">Default Windows shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called with the output when process terminates.</p>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#child_process_class_childprocess" class="type">&#x3C;ChildProcess></a></li>
</ul>
<p>The <code>child_process.execFile()</code> function is similar to <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>
except that it does not spawn a shell by default. Rather, the specified
executable <code>file</code> is spawned directly as a new process making it slightly more
efficient than <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>.</p>
<p>The same options as <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> are supported. Since a shell is
not spawned, behaviors such as I/O redirection and file globbing are not
supported.</p>
<pre><code class="language-js">const { execFile } = require('child_process');
const child = execFile('node', ['--version'], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);
});
</code></pre>
<p>The <code>stdout</code> and <code>stderr</code> arguments passed to the callback will contain the
stdout and stderr output of the child process. By default, Node.js will decode
the output as UTF-8 and pass strings to the callback. The <code>encoding</code> option
can be used to specify the character encoding used to decode the stdout and
stderr output. If <code>encoding</code> is <code>'buffer'</code>, or an unrecognized character
encoding, <code>Buffer</code> objects will be passed to the callback instead.</p>
<p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns
a <code>Promise</code> for an <code>Object</code> with <code>stdout</code> and <code>stderr</code> properties. The returned
<code>ChildProcess</code> instance is attached to the <code>Promise</code> as a <code>child</code> property. 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 two additional properties <code>stdout</code> and <code>stderr</code>.</p>
<pre><code class="language-js">const util = require('util');
const execFile = util.promisify(require('child_process').execFile);
async function getVersion() {
  const { stdout } = await execFile('node', ['--version']);
  console.log(stdout);
}
getVersion();
</code></pre>
<p><strong>If the <code>shell</code> option is enabled, do not pass unsanitized user input to this
function. Any input containing shell metacharacters may be used to trigger
arbitrary command execution.</strong></p>
<h3><code>child_process.fork(modulePath[, args][, options])</code><span><a class="mark" href="#child_process_child_process_fork_modulepath_args_options" id="child_process_child_process_fork_modulepath_args_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>serialization</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>stdio</code> option can now be a string.</p></td></tr>
<tr><td>v6.4.0</td>
<td><p>The <code>stdio</code> option is supported now.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>modulePath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The module to run in the child.</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> List of string arguments.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Current working directory of the child process.</li>
<li><code>detached</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Prepare child to run independently of its parent
process. Specific behavior depends on the platform, see
<a href="#child_process_options_detached"><code>options.detached</code></a>).</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>execPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Executable used to create the child process.</li>
<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> List of string arguments passed to the executable.
<strong>Default:</strong> <code>process.execArgv</code>.</li>
<li><code>serialization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specify the kind of serialization used for sending
messages between processes. Possible values are <code>'json'</code> and <code>'advanced'</code>.
See <a href="#child_process_advanced_serialization">Advanced serialization</a> for more details. <strong>Default:</strong> <code>'json'</code>.</li>
<li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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">&#x3C;number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
</ul>
</li>
<li>Returns: <a href="#child_process_class_childprocess" class="type">&#x3C;ChildProcess></a></li>
</ul>
<p>The <code>child_process.fork()</code> method is a special case of
<a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> used specifically to spawn new Node.js processes.
Like <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>, a <a href="#child_process_child_process"><code>ChildProcess</code></a> object is returned. The
returned <a href="#child_process_child_process"><code>ChildProcess</code></a> will have an additional communication channel
built-in that allows messages to be passed back and forth between the parent and
child. See <a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>subprocess.send()</code></a> for details.</p>
<p>Keep in mind that spawned Node.js child processes are
independent of the parent with exception of the IPC communication channel
that is established between the two. Each process has its own memory, with
their own V8 instances. Because of the additional resource allocations
required, spawning a large number of child Node.js processes is not
recommended.</p>
<p>By default, <code>child_process.fork()</code> will spawn new Node.js instances using the
<a href="#process_process_execpath"><code>process.execPath</code></a> of the parent process. The <code>execPath</code> property in the
<code>options</code> object allows for an alternative execution path to be used.</p>
<p>Node.js processes launched with a custom <code>execPath</code> will communicate with the
parent process using the file descriptor (fd) identified using the
environment variable <code>NODE_CHANNEL_FD</code> on the child process.</p>
<p>Unlike the <a href="http://man7.org/linux/man-pages/man2/fork.2.html"><code>fork(2)</code></a> POSIX system call, <code>child_process.fork()</code> does not clone the
current process.</p>
<p>The <code>shell</code> option available in <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> is not supported by
<code>child_process.fork()</code> and will be ignored if set.</p>
<h3><code>child_process.spawn(command[, args][, options])</code><span><a class="mark" href="#child_process_child_process_spawn_command_args_options" id="child_process_child_process_spawn_command_args_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>serialization</code> option is supported now.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v6.4.0</td>
<td><p>The <code>argv0</code> option is supported now.</p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>shell</code> option is supported now.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The command to run.</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> List of string arguments.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>argv0</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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">&#x3C;number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>serialization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specify the kind of serialization used for sending
messages between processes. Possible values are <code>'json'</code> and <code>'advanced'</code>.
See <a href="#child_process_advanced_serialization">Advanced serialization</a> for more details. <strong>Default:</strong> <code>'json'</code>.</li>
<li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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 and is CMD. <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">&#x3C;boolean></a> Hide the subprocess console window that would
normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#child_process_class_childprocess" class="type">&#x3C;ChildProcess></a></li>
</ul>
<p>The <code>child_process.spawn()</code> method spawns a new process using the given
<code>command</code>, with command line arguments in <code>args</code>. If omitted, <code>args</code> defaults
to an empty array.</p>
<p><strong>If the <code>shell</code> option is enabled, do not pass unsanitized user input to this
function. Any input containing shell metacharacters may be used to trigger
arbitrary command execution.</strong></p>
<p>A third argument may be used to specify additional options, with these defaults:</p>
<pre><code class="language-js">const defaults = {
  cwd: undefined,
  env: process.env
};
</code></pre>
<p>Use <code>cwd</code> to specify the working directory from which the process is spawned.
If not given, the default is to inherit the current working directory.</p>
<p>Use <code>env</code> to specify environment variables that will be visible to the new
process, the default is <a href="#process_process_env"><code>process.env</code></a>.</p>
<p><code>undefined</code> values in <code>env</code> will be ignored.</p>
<p>Example of running <code>ls -lh /usr</code>, capturing <code>stdout</code>, <code>stderr</code>, and the
exit code:</p>
<pre><code class="language-js">const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});
</code></pre>
<p>Example: A very elaborate way to run <code>ps ax | grep ssh</code></p>
<pre><code class="language-js">const { spawn } = require('child_process');
const ps = spawn('ps', ['ax']);
const grep = spawn('grep', ['ssh']);

ps.stdout.on('data', (data) => {
  grep.stdin.write(data);
});

ps.stderr.on('data', (data) => {
  console.error(`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.error(`grep stderr: ${data}`);
});

grep.on('close', (code) => {
  if (code !== 0) {
    console.log(`grep process exited with code ${code}`);
  }
});
</code></pre>
<p>Example of checking for failed <code>spawn</code>:</p>
<pre><code class="language-js">const { spawn } = require('child_process');
const subprocess = spawn('bad_command');

subprocess.on('error', (err) => {
  console.error('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><code>options.detached</code><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. Once enabled for a child process, it cannot be
disabled.</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. Child
processes may continue running after the parent exits regardless of whether
they are detached or not. See <a href="http://man7.org/linux/man-pages/man2/setsid.2.html"><code>setsid(2)</code></a> for more information.</p>
<p>By default, the parent will wait for the detached child to exit. To prevent the
parent from waiting for a given <code>subprocess</code> to exit, use the
<code>subprocess.unref()</code> method. Doing so will cause the parent's event loop to not
include the child in its reference count, allowing the parent to exit
independently of the child, unless there is an established IPC channel between
the child and the parent.</p>
<p>When using the <code>detached</code> option to start a long-running process, the process
will not stay running in the background after the parent exits unless it is
provided with a <code>stdio</code> configuration that is not connected to the parent.
If the parent's <code>stdio</code> is inherited, the child will remain attached to the
controlling terminal.</p>
<p>Example of a long-running process, by detaching and also ignoring its parent
<code>stdio</code> file descriptors, in order to ignore the parent's termination:</p>
<pre><code class="language-js">const { spawn } = require('child_process');

const subprocess = spawn(process.argv[0], ['child_program.js'], {
  detached: true,
  stdio: 'ignore'
});

subprocess.unref();
</code></pre>
<p>Alternatively one can redirect the child process' output into files:</p>
<pre><code class="language-js">const fs = require('fs');
const { spawn } = require('child_process');
const out = fs.openSync('./out.log', 'a');
const err = fs.openSync('./out.log', 'a');

const subprocess = spawn('prg', [], {
  detached: true,
  stdio: [ 'ignore', out, err ]
});

subprocess.unref();
</code></pre>
<h4><code>options.stdio</code><span><a class="mark" href="#child_process_options_stdio" id="child_process_options_stdio">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v3.3.1</td>
<td><p>The value <code>0</code> is now accepted as a file descriptor.</p></td></tr>
<tr><td>v0.7.10</td>
<td><p><span>Added in: v0.7.10</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>options.stdio</code> option is used to configure the pipes that are established
between the parent and child process. By default, the child's stdin, stdout,
and stderr are redirected to corresponding <a href="#child_process_subprocess_stdin"><code>subprocess.stdin</code></a>,
<a href="#child_process_subprocess_stdout"><code>subprocess.stdout</code></a>, and <a href="#child_process_subprocess_stderr"><code>subprocess.stderr</code></a> streams on the
<a href="#child_process_child_process"><code>ChildProcess</code></a> object. This is equivalent to setting the <code>options.stdio</code>
equal to <code>['pipe', 'pipe', 'pipe']</code>.</p>
<p>For convenience, <code>options.stdio</code> may be one of the following strings:</p>
<ul>
<li><code>'pipe'</code>: equivalent to <code>['pipe', 'pipe', 'pipe']</code> (the default)</li>
<li><code>'ignore'</code>: equivalent to <code>['ignore', 'ignore', 'ignore']</code></li>
<li><code>'inherit'</code>: equivalent to <code>['inherit', 'inherit', 'inherit']</code> or <code>[0, 1, 2]</code></li>
</ul>
<p>Otherwise, the value of <code>options.stdio</code> is an array where each index corresponds
to an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,
and stderr, respectively. Additional fds can be specified to create additional
pipes between the parent and child. The value is one of the following:</p>
<ol>
<li>
<p><code>'pipe'</code>: Create a pipe between the child process and the parent process.
The parent end of the pipe is exposed to the parent as a property on the
<code>child_process</code> object as <a href="#child_process_subprocess_stdio"><code>subprocess.stdio[fd]</code></a>. Pipes
created for fds 0, 1, and 2 are also available as <a href="#child_process_subprocess_stdin"><code>subprocess.stdin</code></a>,
<a href="#child_process_subprocess_stdout"><code>subprocess.stdout</code></a> and <a href="#child_process_subprocess_stderr"><code>subprocess.stderr</code></a>, respectively.</p>
</li>
<li>
<p><code>'ipc'</code>: Create an IPC channel for passing messages/file descriptors
between parent and child. A <a href="#child_process_child_process"><code>ChildProcess</code></a> may have at most one IPC
stdio file descriptor. Setting this option enables the
<a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>subprocess.send()</code></a> method. If the child is a Node.js process, the
presence of an IPC channel will enable <a href="#process_process_send_message_sendhandle_options_callback"><code>process.send()</code></a> and
<a href="#process_process_disconnect"><code>process.disconnect()</code></a> methods, as well as <a href="#process_event_disconnect"><code>'disconnect'</code></a> and
<a href="#process_event_message"><code>'message'</code></a> events within the child.</p>
<p>Accessing the IPC channel fd in any way other than <a href="#process_process_send_message_sendhandle_options_callback"><code>process.send()</code></a>
or using the IPC channel with a child process that is not a Node.js instance
is not supported.</p>
</li>
<li>
<p><code>'ignore'</code>: Instructs Node.js to ignore the fd in the child. While Node.js
will always open fds 0, 1, and 2 for the processes it spawns, setting the fd
to <code>'ignore'</code> will cause Node.js to open <code>/dev/null</code> and attach it to the
child's fd.</p>
</li>
<li>
<p><code>'inherit'</code>: Pass through the corresponding stdio stream to/from the
parent process. In the first three positions, this is equivalent to
<code>process.stdin</code>, <code>process.stdout</code>, and <code>process.stderr</code>, respectively. In
any other position, equivalent to <code>'ignore'</code>.</p>
</li>
<li>
<p><a href="#stream_stream" class="type">&#x3C;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. The stream must have an
underlying descriptor (file streams do not until the <code>'open'</code> event has
occurred).</p>
</li>
<li>
<p>Positive integer: The integer value is interpreted as a file descriptor
that is currently open in the parent process. It is shared with the child
process, similar to how <a href="#stream_stream" class="type">&#x3C;Stream></a> objects can be shared. Passing sockets
is not supported on Windows.</p>
</li>
<li>
<p><code>null</code>, <code>undefined</code>: Use default value. For stdio fds 0, 1, and 2 (in other
words, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the
default is <code>'ignore'</code>.</p>
</li>
</ol>
<pre><code class="language-js">const { spawn } = require('child_process');

// Child will use parent's stdios.
spawn('prg', [], { stdio: 'inherit' });

// Spawn child sharing only stderr.
spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });

// Open an extra fd=4, to interact with programs presenting a
// startd-style interface.
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
</code></pre>
<p><em>It is worth noting that when an IPC channel is established between the
parent and child processes, and the child is a Node.js process, the child
is launched with the IPC channel unreferenced (using <code>unref()</code>) until the
child registers an event handler for the <a href="#process_event_disconnect"><code>'disconnect'</code></a> event
or the <a href="#process_event_message"><code>'message'</code></a> event. This allows the child to exit
normally without the process being held open by the open IPC channel.</em></p>
<p>On Unix-like operating systems, the <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> method
performs memory operations synchronously before decoupling the event loop
from the child. Applications with a large memory footprint may find frequent
<a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> calls to be a bottleneck. For more information,
see <a href="https://bugs.chromium.org/p/v8/issues/detail?id=7381">V8 issue 7381</a>.</p>
<p>See also: <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> and <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>.</p>
<h2>Synchronous process creation<span><a class="mark" href="#child_process_synchronous_process_creation" id="child_process_synchronous_process_creation">#</a></span></h2>
<p>The <a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a>, <a href="#child_process_child_process_execsync_command_options"><code>child_process.execSync()</code></a>, and
<a href="#child_process_child_process_execfilesync_file_args_options"><code>child_process.execFileSync()</code></a> methods are synchronous and will 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><code>child_process.execFileSync(file[, args][, options])</code><span><a class="mark" href="#child_process_child_process_execfilesync_file_args_options" id="child_process_child_process_execfilesync_file_args_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>input</code> option can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>input</code> option can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v6.2.1, v4.5.0</td>
<td><p>The <code>encoding</code> option can now explicitly be set to <code>buffer</code>.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string[]></a> List of string arguments.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> The value which will be passed
as stdin to the spawned process. Supplying this value will override
<code>stdio[0]</code>.</li>
<li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> Child's stdio configuration. <code>stderr</code> by default will
be output to the parent process' stderr unless <code>stdio</code> is specified.
<strong>Default:</strong> <code>'pipe'</code>.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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>1024 * 1024</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If <code>true</code>, runs <code>command</code> inside of a shell. Uses
<code>'/bin/sh'</code> on Unix, and <code>process.env.ComSpec</code> on Windows. A different
shell can be specified as a string. See <a href="#child_process_shell_requirements">Shell requirements</a> and
<a href="#child_process_default_windows_shell">Default Windows shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li>
</ul>
</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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 will throw an
<a href="#errors_class_error"><code>Error</code></a> that will include the full result of the underlying
<a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a>.</p>
<p><strong>If the <code>shell</code> option is enabled, do not pass unsanitized user input to this
function. Any input containing shell metacharacters may be used to trigger
arbitrary command execution.</strong></p>
<h3><code>child_process.execSync(command[, options])</code><span><a class="mark" href="#child_process_child_process_execsync_command_options" id="child_process_child_process_execsync_command_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>input</code> option can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>input</code> option can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The command to run.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> The value which will be passed
as stdin to the spawned process. Supplying this value will override
<code>stdio[0]</code>.</li>
<li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> Child's stdio configuration. <code>stderr</code> by default will
be output to the parent process' stderr unless <code>stdio</code> is specified.
<strong>Default:</strong> <code>'pipe'</code>.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>shell</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Shell to execute the command with. See
<a href="#child_process_shell_requirements">Shell requirements</a> and <a href="#child_process_default_windows_shell">Default Windows shell</a>. <strong>Default:</strong>
<code>'/bin/sh'</code> on Unix, <code>process.env.ComSpec</code> on Windows.</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;number></a> Largest amount of data in bytes allowed on stdout or
stderr. If exceeded, the child process is terminated and any output is
truncated. See caveat at <a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a>.
<strong>Default:</strong> <code>1024 * 1024</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;boolean></a> Hide the subprocess console window that would
normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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. 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.</p>
<p>If the process times out or has a non-zero exit code, this method will throw.
The <a href="#errors_class_error"><code>Error</code></a> object will contain the entire result from
<a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a>.</p>
<p><strong>Never pass unsanitized user input to this function. Any input containing shell
metacharacters may be used to trigger arbitrary command execution.</strong></p>
<h3><code>child_process.spawnSync(command[, args][, options])</code><span><a class="mark" href="#child_process_child_process_spawnsync_command_args_options" id="child_process_child_process_spawnsync_command_args_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>input</code> option can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>input</code> option can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v6.2.1, v4.5.0</td>
<td><p>The <code>encoding</code> option can now explicitly be set to <code>buffer</code>.</p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>shell</code> option is supported now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>command</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The command to run.</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> List of string arguments.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> The value which will be passed
as stdin to the spawned process. Supplying this value will override
<code>stdio[0]</code>.</li>
<li><code>argv0</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Explicitly set the value of <code>argv[0]</code> sent to the child
process. This will be set to <code>command</code> if not specified.</li>
<li><code>stdio</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;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">&#x3C;Object></a> Environment key-value pairs. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the user identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>).</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the group identity of the process (see <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>).</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;number></a> Largest amount of data in bytes allowed on stdout or
stderr. If exceeded, the child process is terminated and any output is
truncated. See caveat at <a href="#child_process_maxbuffer_and_unicode"><code>maxBuffer</code> and Unicode</a>.
<strong>Default:</strong> <code>1024 * 1024</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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 and is CMD. <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">&#x3C;boolean></a> Hide the subprocess console window that would
normally be created on Windows systems. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;Array></a> Array of results from stdio output.</li>
<li><code>stdout</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The contents of <code>output[1]</code>.</li>
<li><code>stderr</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> The exit code of the subprocess, or <code>null</code> if the
subprocess terminated due to a signal.</li>
<li><code>signal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> The signal used to kill the subprocess, or <code>null</code> if
the subprocess did not terminate due to a signal.</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;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. 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: <code>ChildProcess</code><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>
<ul>
<li>Extends: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Instances of the <code>ChildProcess</code> represent spawned child processes.</p>
<p>Instances of <code>ChildProcess</code> are not intended to be created directly. Rather,
use the <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>, <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>,
<a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a>, or <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a> methods to create
instances of <code>ChildProcess</code>.</p>
<h3>Event: <code>'close'</code><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">&#x3C;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">&#x3C;string></a> The signal by which the child process was terminated.</li>
</ul>
<p>The <code>'close'</code> event is emitted when the stdio streams of a child process have
been closed. This is distinct from the <a href="#child_process_event_exit"><code>'exit'</code></a> event, since multiple
processes might share the same stdio streams.</p>
<pre><code class="language-js">const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process close all stdio with code ${code}`);
});

ls.on('exit', (code) => {
  console.log(`child process exited with code ${code}`);
});
</code></pre>
<h3>Event: <code>'disconnect'</code><span><a class="mark" href="#child_process_event_disconnect" id="child_process_event_disconnect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.2</span>
</div>
<p>The <code>'disconnect'</code> event is emitted after calling the
<a href="#child_process_subprocess_disconnect"><code>subprocess.disconnect()</code></a> method in parent process or
<a href="#process_process_disconnect"><code>process.disconnect()</code></a> in child process. After disconnecting it is no longer
possible to send or receive messages, and the <a href="#child_process_subprocess_connected"><code>subprocess.connected</code></a>
property is <code>false</code>.</p>
<h3>Event: <code>'error'</code><span><a class="mark" href="#child_process_event_error" id="child_process_event_error">#</a></span></h3>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> The error.</li>
</ul>
<p>The <code>'error'</code> event is emitted whenever:</p>
<ol>
<li>The process could not be spawned, or</li>
<li>The process could not be killed, or</li>
<li>Sending a message to the child process failed.</li>
</ol>
<p>The <code>'exit'</code> event may or may not fire after an error has occurred. When
listening to both the <code>'exit'</code> and <code>'error'</code> events, guard
against accidentally invoking handler functions multiple times.</p>
<p>See also <a href="#child_process_subprocess_kill_signal"><code>subprocess.kill()</code></a> and <a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>subprocess.send()</code></a>.</p>
<h3>Event: <code>'exit'</code><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">&#x3C;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">&#x3C;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-<code>null</code>.</p>
<p>When the <code>'exit'</code> event is triggered, child process stdio streams might still be
open.</p>
<p>Node.js establishes signal handlers for <code>SIGINT</code> and <code>SIGTERM</code> and Node.js
processes will not terminate immediately due to receipt of those signals.
Rather, Node.js will perform a sequence of cleanup actions and then will
re-raise the handled signal.</p>
<p>See <a href="http://man7.org/linux/man-pages/man2/waitpid.2.html"><code>waitpid(2)</code></a>.</p>
<h3>Event: <code>'message'</code><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">&#x3C;Object></a> A parsed JSON object or primitive value.</li>
<li><code>sendHandle</code> <a href="#net_server_listen_handle_backlog_callback" class="type">&#x3C;Handle></a> A <a href="#net_class_net_socket"><code>net.Socket</code></a> or <a href="#net_class_net_server"><code>net.Server</code></a> object, or
undefined.</li>
</ul>
<p>The <code>'message'</code> event is triggered when a child process uses
<a href="#process_process_send_message_sendhandle_options_callback"><code>process.send()</code></a> to send messages.</p>
<p>The message goes through serialization and parsing. The resulting
message might not be the same as what is originally sent.</p>
<p>If the <code>serialization</code> option was set to <code>'advanced'</code> used when spawning the
child process, the <code>message</code> argument can contain data that JSON is not able
to represent.
See <a href="#child_process_advanced_serialization">Advanced serialization</a> for more details.</p>
<h3><code>subprocess.channel</code><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">&#x3C;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><code>subprocess.connected</code><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">&#x3C;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><code>subprocess.disconnect()</code><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>When the child process is a Node.js instance (e.g. spawned using
<a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>), the <code>process.disconnect()</code> method can be invoked
within the child process to close the IPC channel as well.</p>
<h3><code>subprocess.exitCode</code><span><a class="mark" href="#child_process_subprocess_exitcode" id="child_process_subprocess_exitcode">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>The <code>subprocess.exitCode</code> property indicates the exit code of the child process.
If the child process is still running, the field will be <code>null</code>.</p>
<h3><code>subprocess.kill([signal])</code><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#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <code>subprocess.kill()</code> method sends a signal to the child process. If no
argument is given, the process will be sent the <code>'SIGTERM'</code> signal. See
<a href="http://man7.org/linux/man-pages/man7/signal.7.html"><code>signal(7)</code></a> for a list of available signals. This function returns <code>true</code> if
<a href="http://man7.org/linux/man-pages/man2/kill.2.html"><code>kill(2)</code></a> succeeds, and <code>false</code> otherwise.</p>
<pre><code class="language-js">const { spawn } = require('child_process');
const grep = spawn('grep', ['ssh']);

grep.on('close', (code, signal) => {
  console.log(
    `child process terminated due to receipt of signal ${signal}`);
});

// Send SIGHUP to process.
grep.kill('SIGHUP');
</code></pre>
<p>The <a href="#child_process_child_process"><code>ChildProcess</code></a> object may emit an <a href="#child_process_event_error"><code>'error'</code></a> event if the signal
cannot be delivered. Sending a signal to a child process that has already exited
is not an error but may have unforeseen consequences. Specifically, if the
process identifier (PID) has been reassigned to another process, the signal will
be delivered to that process instead which can have unexpected results.</p>
<p>While the function is called <code>kill</code>, the signal delivered to the child process
may not actually terminate the process.</p>
<p>See <a href="http://man7.org/linux/man-pages/man2/kill.2.html"><code>kill(2)</code></a> for reference.</p>
<p>On Linux, child processes of child processes will not be terminated
when attempting to kill their parent. This is likely to happen when running a
new process in a shell or with the use of the <code>shell</code> option of <code>ChildProcess</code>:</p>
<pre><code class="language-js">'use strict';
const { spawn } = require('child_process');

const subprocess = spawn(
  'sh',
  [
    '-c',
    `node -e "setInterval(() => {
      console.log(process.pid, 'is alive')
    }, 500);"`
  ], {
    stdio: ['inherit', 'inherit', 'inherit']
  }
);

setTimeout(() => {
  subprocess.kill(); // Does not terminate the Node.js process in the shell.
}, 2000);
</code></pre>
<h3><code>subprocess.killed</code><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">&#x3C;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><code>subprocess.pid</code><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">&#x3C;integer></a></li>
</ul>
<p>Returns the process identifier (PID) of the child process.</p>
<pre><code class="language-js">const { spawn } = require('child_process');
const grep = spawn('grep', ['ssh']);

console.log(`Spawned child pid: ${grep.pid}`);
grep.stdin.end();
</code></pre>
<h3><code>subprocess.ref()</code><span><a class="mark" href="#child_process_subprocess_ref" id="child_process_subprocess_ref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.10</span>
</div>
<p>Calling <code>subprocess.ref()</code> after making a call to <code>subprocess.unref()</code> will
restore the removed reference count for the child process, forcing the parent
to wait for the child to exit before exiting itself.</p>
<pre><code class="language-js">const { spawn } = require('child_process');

const subprocess = spawn(process.argv[0], ['child_program.js'], {
  detached: true,
  stdio: 'ignore'
});

subprocess.unref();
subprocess.ref();
</code></pre>
<h3><code>subprocess.send(message[, sendHandle[, options]][, callback])</code><span><a class="mark" href="#child_process_subprocess_send_message_sendhandle_options_callback" id="child_process_subprocess_send_message_sendhandle_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.8.0</td>
<td><p>The <code>options</code> parameter, and the <code>keepOpen</code> option in particular, is supported now.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>This method returns a boolean for flow control now.</p></td></tr>
<tr><td>v4.0.0</td>
<td><p>The <code>callback</code> parameter is supported now.</p></td></tr>
<tr><td>v0.5.9</td>
<td><p><span>Added in: v0.5.9</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>sendHandle</code> <a href="#net_server_listen_handle_backlog_callback" class="type">&#x3C;Handle></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <code>options</code> argument, if present, is an object used to
parameterize the sending of certain types of handles. <code>options</code> supports
the following properties:</p>
<ul>
<li><code>keepOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A value that can be used when passing instances of
<code>net.Socket</code>. When <code>true</code>, the socket is kept open in the sending process.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>When an IPC channel has been established between the parent and child (
i.e. when using <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>), the <code>subprocess.send()</code> method can
be used to send messages to the child process. When the child process is a
Node.js instance, these messages can be received via the <a href="#process_event_message"><code>'message'</code></a> event.</p>
<p>The message goes through serialization and parsing. The resulting
message might not be the same as what is originally sent.</p>
<p>For example, in the parent script:</p>
<pre><code class="language-js">const cp = require('child_process');
const n = cp.fork(`${__dirname}/sub.js`);

n.on('message', (m) => {
  console.log('PARENT got message:', m);
});

// Causes the child to print: CHILD got message: { hello: 'world' }
n.send({ hello: 'world' });
</code></pre>
<p>And then the child script, <code>'sub.js'</code> might look like this:</p>
<pre><code class="language-js">process.on('message', (m) => {
  console.log('CHILD got message:', m);
});

// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }
process.send({ foo: 'bar', baz: NaN });
</code></pre>
<p>Child Node.js processes will have a <a href="#process_process_send_message_sendhandle_options_callback"><code>process.send()</code></a> method of their own
that allows the child to send messages back to the parent.</p>
<p>There is a special case when sending a <code>{cmd: 'NODE_foo'}</code> message. Messages
containing a <code>NODE_</code> prefix in the <code>cmd</code> property are reserved for use within
Node.js core and will not be emitted in the child's <a href="#process_event_message"><code>'message'</code></a>
event. Rather, such messages are emitted using the
<code>'internalMessage'</code> event and are consumed internally by Node.js.
Applications should avoid using such messages or listening for
<code>'internalMessage'</code> events as it is subject to change without notice.</p>
<p>The optional <code>sendHandle</code> argument that may be passed to <code>subprocess.send()</code> is
for passing a TCP server or socket object to the child process. The child will
receive the object as the second argument passed to the callback function
registered on the <a href="#process_event_message"><code>'message'</code></a> event. Any data that is received
and buffered in the socket will not be sent to the child.</p>
<p>The optional <code>callback</code> is a function that is invoked after the message is
sent but before the child may have received it. The function is called with a
single argument: <code>null</code> on success, or an <a href="#errors_class_error"><code>Error</code></a> object on failure.</p>
<p>If no <code>callback</code> function is provided and the message cannot be sent, an
<code>'error'</code> event will be emitted by the <a href="#child_process_child_process"><code>ChildProcess</code></a> object. This can
happen, for instance, when the child process has already exited.</p>
<p><code>subprocess.send()</code> will return <code>false</code> if the channel has closed or when the
backlog of unsent messages exceeds a threshold that makes it unwise to send
more. Otherwise, the method returns <code>true</code>. The <code>callback</code> function can be
used to implement flow control.</p>
<h4>Example: sending a server object<span><a class="mark" href="#child_process_example_sending_a_server_object" id="child_process_example_sending_a_server_object">#</a></span></h4>
<p>The <code>sendHandle</code> argument can be used, for instance, to pass the handle of
a TCP server object to the child process as illustrated in the example below:</p>
<pre><code class="language-js">const subprocess = require('child_process').fork('subprocess.js');

// Open up the server object and send the handle.
const server = require('net').createServer();
server.on('connection', (socket) => {
  socket.end('handled by parent');
});
server.listen(1337, () => {
  subprocess.send('server', server);
});
</code></pre>
<p>The child would then receive the server object as:</p>
<pre><code class="language-js">process.on('message', (m, server) => {
  if (m === 'server') {
    server.on('connection', (socket) => {
      socket.end('handled by child');
    });
  }
});
</code></pre>
<p>Once the server is now shared between the parent and child, some connections
can be handled by the parent and some by the child.</p>
<p>While the example above uses a server created using the <code>net</code> module, <code>dgram</code>
module servers use exactly the same workflow with the exceptions of listening on
a <code>'message'</code> event instead of <code>'connection'</code> and using <code>server.bind()</code> instead
of <code>server.listen()</code>. This is, however, currently only supported on Unix
platforms.</p>
<h4>Example: sending a socket object<span><a class="mark" href="#child_process_example_sending_a_socket_object" id="child_process_example_sending_a_socket_object">#</a></span></h4>
<p>Similarly, the <code>sendHandler</code> argument can be used to pass the handle of a
socket to the child process. The example below spawns two children that each
handle connections with "normal" or "special" priority:</p>
<pre><code class="language-js">const { fork } = require('child_process');
const normal = fork('subprocess.js', ['normal']);
const special = fork('subprocess.js', ['special']);

// Open up the server and send sockets to child. Use pauseOnConnect to prevent
// the sockets from being read before they are sent to the child process.
const server = require('net').createServer({ pauseOnConnect: true });
server.on('connection', (socket) => {

  // If this is special priority...
  if (socket.remoteAddress === '74.125.127.100') {
    special.send('socket', socket);
    return;
  }
  // This is normal priority.
  normal.send('socket', socket);
});
server.listen(1337);
</code></pre>
<p>The <code>subprocess.js</code> would receive the socket handle as the second argument
passed to the event callback function:</p>
<pre><code class="language-js">process.on('message', (m, socket) => {
  if (m === 'socket') {
    if (socket) {
      // Check that the client socket exists.
      // It is possible for the socket to be closed between the time it is
      // sent and the time it is received in the child process.
      socket.end(`Request handled with ${process.argv[2]} priority`);
    }
  }
});
</code></pre>
<p>Once a socket has been passed to a child, the parent is no longer capable of
tracking when the socket is destroyed. To indicate this, the <code>.connections</code>
property becomes <code>null</code>. It is recommended not to use <code>.maxConnections</code> when
this occurs.</p>
<p>It is also recommended that any <code>'message'</code> handlers in the child process
verify that <code>socket</code> exists, as the connection may have been closed during the
time it takes to send the connection to the child.</p>
<h3><code>subprocess.signalCode</code><span><a class="mark" href="#child_process_subprocess_signalcode" id="child_process_subprocess_signalcode">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>The <code>subprocess.signalCode</code> property indicates the signal number received by
the child process if any, else <code>null</code>.</p>
<h3><code>subprocess.spawnargs</code><span><a class="mark" href="#child_process_subprocess_spawnargs" id="child_process_subprocess_spawnargs">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a></li>
</ul>
<p>The <code>subprocess.spawnargs</code> property represents the full list of command line
arguments the child process was launched with.</p>
<h3><code>subprocess.spawnfile</code><span><a class="mark" href="#child_process_subprocess_spawnfile" id="child_process_subprocess_spawnfile">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>subprocess.spawnfile</code> property indicates the executable file name of
the child process that is launched.</p>
<p>For <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>, its value will be equal to
<a href="#process_process_execpath"><code>process.execPath</code></a>.
For <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>, its value will be the name of
the executable file.
For <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>,  its value will be the name of the shell
in which the child process is launched.</p>
<h3><code>subprocess.stderr</code><span><a class="mark" href="#child_process_subprocess_stderr" id="child_process_subprocess_stderr">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#stream_class_stream_readable" class="type">&#x3C;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><code>subprocess.stdin</code><span><a class="mark" href="#child_process_subprocess_stdin" id="child_process_subprocess_stdin">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a></li>
</ul>
<p>A <code>Writable Stream</code> that represents the child process's <code>stdin</code>.</p>
<p>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>.</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><code>subprocess.stdio</code><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">&#x3C;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>. <code>subprocess.stdio[0]</code>, <code>subprocess.stdio[1]</code>, and
<code>subprocess.stdio[2]</code> are also available as <code>subprocess.stdin</code>,
<code>subprocess.stdout</code>, and <code>subprocess.stderr</code>, respectively.</p>
<p>In the following example, only the child's fd <code>1</code> (stdout) is configured as a
pipe, so only the parent's <code>subprocess.stdio[1]</code> is a stream, all other values
in the array are <code>null</code>.</p>
<pre><code class="language-js">const assert = require('assert');
const fs = require('fs');
const child_process = require('child_process');

const subprocess = child_process.spawn('ls', {
  stdio: [
    0, // Use parent's stdin for child.
    'pipe', // Pipe child's stdout to parent.
    fs.openSync('err.out', 'w') // Direct child's stderr to a file.
  ]
});

assert.strictEqual(subprocess.stdio[0], null);
assert.strictEqual(subprocess.stdio[0], subprocess.stdin);

assert(subprocess.stdout);
assert.strictEqual(subprocess.stdio[1], subprocess.stdout);

assert.strictEqual(subprocess.stdio[2], null);
assert.strictEqual(subprocess.stdio[2], subprocess.stderr);
</code></pre>
<h3><code>subprocess.stdout</code><span><a class="mark" href="#child_process_subprocess_stdout" id="child_process_subprocess_stdout">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#stream_class_stream_readable" class="type">&#x3C;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>
<pre><code class="language-js">const { spawn } = require('child_process');

const subprocess = spawn('ls');

subprocess.stdout.on('data', (data) => {
  console.log(`Received chunk ${data}`);
});
</code></pre>
<h3><code>subprocess.unref()</code><span><a class="mark" href="#child_process_subprocess_unref" id="child_process_subprocess_unref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.10</span>
</div>
<p>By default, the parent will wait for the detached child to exit. To prevent the
parent from waiting for a given <code>subprocess</code> to exit, use the
<code>subprocess.unref()</code> method. Doing so will cause the parent's event loop to not
include the child in its reference count, allowing the parent to exit
independently of the child, unless there is an established IPC channel between
the child and the parent.</p>
<pre><code class="language-js">const { spawn } = require('child_process');

const subprocess = spawn(process.argv[0], ['child_program.js'], {
  detached: true,
  stdio: 'ignore'
});

subprocess.unref();
</code></pre>
<h2><code>maxBuffer</code> and Unicode<span><a class="mark" href="#child_process_maxbuffer_and_unicode" id="child_process_maxbuffer_and_unicode">#</a></span></h2>
<p>The <code>maxBuffer</code> option specifies the largest number of bytes allowed on <code>stdout</code>
or <code>stderr</code>. If this value is exceeded, then the child process is terminated.
This impacts output that includes multibyte character encodings such as UTF-8 or
UTF-16. For instance, <code>console.log('中文测试')</code> will send 13 UTF-8 encoded bytes
to <code>stdout</code> although there are only 4 characters.</p>
<h2>Shell requirements<span><a class="mark" href="#child_process_shell_requirements" id="child_process_shell_requirements">#</a></span></h2>
<p>The shell should understand the <code>-c</code> switch. If the shell is <code>'cmd.exe'</code>, it
should understand the <code>/d /s /c</code> switches and command line parsing should be
compatible.</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>
<h2>Advanced serialization<span><a class="mark" href="#child_process_advanced_serialization" id="child_process_advanced_serialization">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p>Child processes support a serialization mechanism for IPC that is based on the
<a href="#v8_serialization_api">serialization API of the <code>v8</code> module</a>, based on the
<a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>. This is generally more powerful and
supports more built-in JavaScript object types, such as <code>BigInt</code>, <code>Map</code>
and <code>Set</code>, <code>ArrayBuffer</code> and <code>TypedArray</code>, <code>Buffer</code>, <code>Error</code>, <code>RegExp</code> etc.</p>
<p>However, this format is not a full superset of JSON, and e.g. properties set on
objects of such built-in types will not be passed on through the serialization
step. Additionally, performance may not be equivalent to that of JSON, depending
on the structure of the passed data.
Therefore, this feature requires opting in by setting the
<code>serialization</code> option to <code>'advanced'</code> when calling <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>
or <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>.</p>
<h1>Cluster<span><a class="mark" href="#cluster_cluster" id="cluster_cluster">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>A single instance of Node.js runs in a single thread. To take advantage of
multi-core systems, the user will sometimes want to launch a cluster of Node.js
processes to handle the load.</p>
<p>The cluster module allows easy creation of child processes that all share
server ports.</p>
<pre><code class="language-js">const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i &#x3C; numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });
} else {
  // Workers can share any TCP connection
  // In this case it is an HTTP server
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
  }).listen(8000);

  console.log(`Worker ${process.pid} started`);
}
</code></pre>
<p>Running Node.js will now share port 8000 between the workers:</p>
<pre><code class="language-console">$ node server.js
Master 3596 is running
Worker 4324 started
Worker 4520 started
Worker 6056 started
Worker 5644 started
</code></pre>
<p>On Windows, it is not yet possible to set up a named pipe server in a worker.</p>
<h2>How it works<span><a class="mark" href="#cluster_how_it_works" id="cluster_how_it_works">#</a></span></h2>

<p>The worker processes are spawned using the <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a> method,
so that they can communicate with the parent via IPC and pass server
handles back and forth.</p>
<p>The cluster module supports two methods of distributing incoming
connections.</p>
<p>The first one (and the default one on all platforms except Windows),
is the round-robin approach, where the master process listens on a
port, accepts new connections and distributes them across the workers
in a round-robin fashion, with some built-in smarts to avoid
overloading a worker process.</p>
<p>The second approach is where the master process creates the listen
socket and sends it to interested workers. The workers then accept
incoming connections directly.</p>
<p>The second approach should, in theory, give the best performance.
In practice however, distribution tends to be very unbalanced due
to operating system scheduler vagaries. Loads have been observed
where over 70% of all connections ended up in just two processes,
out of a total of eight.</p>
<p>Because <code>server.listen()</code> hands off most of the work to the master
process, there are three cases where the behavior between a normal
Node.js process and a cluster worker differs:</p>
<ol>
<li><code>server.listen({fd: 7})</code> Because the message is passed to the master,
file descriptor 7 <strong>in the parent</strong> will be listened on, and the
handle passed to the worker, rather than listening to the worker's
idea of what the number 7 file descriptor references.</li>
<li><code>server.listen(handle)</code> Listening on handles explicitly will cause
the worker to use the supplied handle, rather than talk to the master
process.</li>
<li><code>server.listen(0)</code> Normally, this will cause servers to listen on a
random port. However, in a cluster, each worker will receive the
same "random" port each time they do <code>listen(0)</code>. In essence, the
port is random the first time, but predictable thereafter. To listen
on a unique port, generate a port number based on the cluster worker ID.</li>
</ol>
<p>Node.js does not provide routing logic. It is, therefore important to design an
application such that it does not rely too heavily on in-memory data objects for
things like sessions and login.</p>
<p>Because workers are all separate processes, they can be killed or
re-spawned depending on a program's needs, without affecting other
workers. As long as there are some workers still alive, the server will
continue to accept connections. If no workers are alive, existing connections
will be dropped and new connections will be refused. Node.js does not
automatically manage the number of workers, however. It is the application's
responsibility to manage the worker pool based on its own needs.</p>
<p>Although a primary use case for the <code>cluster</code> module is networking, it can
also be used for other use cases requiring worker processes.</p>
<h2>Class: <code>Worker</code><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>
<ul>
<li>Extends: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>A <code>Worker</code> object contains all public information and method about a worker.
In the master it can be obtained using <code>cluster.workers</code>. In a worker
it can be obtained using <code>cluster.worker</code>.</p>
<h3>Event: <code>'disconnect'</code><span><a class="mark" href="#cluster_event_disconnect" id="cluster_event_disconnect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>Similar to the <code>cluster.on('disconnect')</code> event, but specific to this worker.</p>
<pre><code class="language-js">cluster.fork().on('disconnect', () => {
  // Worker has disconnected
});
</code></pre>
<h3>Event: <code>'error'</code><span><a class="mark" href="#cluster_event_error" id="cluster_event_error">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.3</span>
</div>
<p>This event is the same as the one provided by <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>.</p>
<p>Within a worker, <code>process.on('error')</code> may also be used.</p>
<h3>Event: <code>'exit'</code><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">&#x3C;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">&#x3C;string></a> The name of the signal (e.g. <code>'SIGHUP'</code>) that caused
the process to be killed.</li>
</ul>
<p>Similar to the <code>cluster.on('exit')</code> event, but specific to this worker.</p>
<pre><code class="language-js">const worker = cluster.fork();
worker.on('exit', (code, signal) => {
  if (signal) {
    console.log(`worker was killed by signal: ${signal}`);
  } else if (code !== 0) {
    console.log(`worker exited with error code: ${code}`);
  } else {
    console.log('worker success!');
  }
});
</code></pre>
<h3>Event: <code>'listening'</code><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">&#x3C;Object></a></li>
</ul>
<p>Similar to the <code>cluster.on('listening')</code> event, but specific to this worker.</p>
<pre><code class="language-js">cluster.fork().on('listening', (address) => {
  // Worker is listening
});
</code></pre>
<p>It is not emitted in the worker.</p>
<h3>Event: <code>'message'</code><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">&#x3C;Object></a></li>
<li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Similar to the <code>'message'</code> event of <code>cluster</code>, but specific to this worker.</p>
<p>Within a worker, <code>process.on('message')</code> may also be used.</p>
<p>See <a href="#process_event_message"><code>process</code> event: <code>'message'</code></a>.</p>
<p>Here is an example using the message system. It keeps a count in the master
process of the number of HTTP requests received by the workers:</p>
<pre><code class="language-js">const cluster = require('cluster');
const http = require('http');

if (cluster.isMaster) {

  // Keep track of http requests
  let numReqs = 0;
  setInterval(() => {
    console.log(`numReqs = ${numReqs}`);
  }, 1000);

  // Count requests
  function messageHandler(msg) {
    if (msg.cmd &#x26;&#x26; msg.cmd === 'notifyRequest') {
      numReqs += 1;
    }
  }

  // Start workers and listen for messages containing notifyRequest
  const numCPUs = require('os').cpus().length;
  for (let i = 0; i &#x3C; 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: <code>'online'</code><span><a class="mark" href="#cluster_event_online" id="cluster_event_online">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<p>Similar to the <code>cluster.on('online')</code> event, but specific to this worker.</p>
<pre><code class="language-js">cluster.fork().on('online', () => {
  // Worker is online
});
</code></pre>
<p>It is not emitted in the worker.</p>
<h3><code>worker.disconnect()</code><span><a class="mark" href="#cluster_worker_disconnect" id="cluster_worker_disconnect">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.3.0</td>
<td><p>This method now returns a reference to <code>worker</code>.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="#cluster_class_worker" class="type">&#x3C;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>After a server is closed, it will no longer accept new connections,
but connections may be accepted by any other listening worker. Existing
connections will be allowed to close as usual. When no more connections exist,
see <a href="#net_event_close"><code>server.close()</code></a>, the IPC channel to the worker will close allowing it
to die gracefully.</p>
<p>The above applies <em>only</em> to server connections, client connections are not
automatically closed by workers, and disconnect does not wait for them to close
before exiting.</p>
<p>In a worker, <code>process.disconnect</code> exists, but it is not this function;
it is <a href="#child_process_subprocess_disconnect"><code>disconnect()</code></a>.</p>
<p>Because long living server connections may block workers from disconnecting, it
may be useful to send a message, so application specific actions may be taken to
close them. It also may be useful to implement a timeout, killing a worker if
the <code>'disconnect'</code> event has not been emitted after some time.</p>
<pre><code class="language-js">if (cluster.isMaster) {
  const worker = cluster.fork();
  let timeout;

  worker.on('listening', (address) => {
    worker.send('shutdown');
    worker.disconnect();
    timeout = setTimeout(() => {
      worker.kill();
    }, 2000);
  });

  worker.on('disconnect', () => {
    clearTimeout(timeout);
  });

} else if (cluster.isWorker) {
  const net = require('net');
  const server = net.createServer((socket) => {
    // Connections never end
  });

  server.listen(8000);

  process.on('message', (msg) => {
    if (msg === 'shutdown') {
      // Initiate graceful close of any connections to server
    }
  });
}
</code></pre>
<h3><code>worker.exitedAfterDisconnect</code><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">&#x3C;boolean></a></li>
</ul>
<p>This property is <code>true</code> if the worker exited due to <code>.kill()</code> or
<code>.disconnect()</code>. If the worker exited any other way, it is <code>false</code>. If the
worker has not exited, it is <code>undefined</code>.</p>
<p>The boolean <a href="#cluster_worker_exitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a> allows distinguishing between
voluntary and accidental exit, the master may choose not to respawn a worker
based on this value.</p>
<pre><code class="language-js">cluster.on('exit', (worker, code, signal) => {
  if (worker.exitedAfterDisconnect === true) {
    console.log('Oh, it was just voluntary – no need to worry');
  }
});

// kill worker
worker.kill();
</code></pre>
<h3><code>worker.id</code><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">&#x3C;number></a></li>
</ul>
<p>Each new worker is given its own unique id, this id is stored in the
<code>id</code>.</p>
<p>While a worker is alive, this is the key that indexes it in
<code>cluster.workers</code>.</p>
<h3><code>worker.isConnected()</code><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><code>worker.isDead()</code><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>
<pre><code class="language-js">const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`Master ${process.pid} is running`);

  // Fork workers.
  for (let i = 0; i &#x3C; numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('fork', (worker) => {
    console.log('worker is dead:', worker.isDead());
  });

  cluster.on('exit', (worker, code, signal) => {
    console.log('worker is dead:', worker.isDead());
  });
} else {
  // Workers can share any TCP connection. In this case, it is an HTTP server.
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Current process\n ${process.pid}`);
    process.kill(process.pid);
  }).listen(8000);
}
</code></pre>
<h3><code>worker.kill([signal])</code><span><a class="mark" href="#cluster_worker_kill_signal" id="cluster_worker_kill_signal">#</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">&#x3C;string></a> Name of the kill signal to send to the worker
process. <strong>Default</strong>: <code>'SIGTERM'</code></li>
</ul>
<p>This function will kill the worker. In the master, it does this by disconnecting
the <code>worker.process</code>, and once disconnected, killing with <code>signal</code>. In the
worker, it does it by disconnecting the channel, and then exiting with code <code>0</code>.</p>
<p>Because <code>kill()</code> attempts to gracefully disconnect the worker process, it is
susceptible to waiting indefinitely for the disconnect to complete. For example,
if the worker enters an infinite loop, a graceful disconnect will never occur.
If the graceful disconnect behavior is not needed, use <code>worker.process.kill()</code>.</p>
<p>Causes <code>.exitedAfterDisconnect</code> to be set.</p>
<p>This method is aliased as <code>worker.destroy()</code> for backwards compatibility.</p>
<p>In a worker, <code>process.kill()</code> exists, but it is not this function;
it is <a href="#process_process_kill_pid_signal"><code>kill()</code></a>.</p>
<h3><code>worker.process</code><span><a class="mark" href="#cluster_worker_process" id="cluster_worker_process">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><a href="#child_process_class_childprocess" class="type">&#x3C;ChildProcess></a></li>
</ul>
<p>All workers are created using <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>, the returned object
from this function is stored as <code>.process</code>. In a worker, the global <code>process</code>
is stored.</p>
<p>See: <a href="#child_process_child_process_fork_modulepath_args_options">Child Process module</a>.</p>
<p>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><code>worker.send(message[, sendHandle[, options]][, callback])</code><span><a class="mark" href="#cluster_worker_send_message_sendhandle_options_callback" id="cluster_worker_send_message_sendhandle_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.0.0</td>
<td><p>The <code>callback</code> parameter is supported now.</p></td></tr>
<tr><td>v0.7.0</td>
<td><p><span>Added in: v0.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>sendHandle</code> <a href="#net_server_listen_handle_backlog_callback" class="type">&#x3C;Handle></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <code>options</code> argument, if present, is an object used to
parameterize the sending of certain types of handles. <code>options</code> supports
the following properties:</p>
<ul>
<li><code>keepOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A value that can be used when passing instances of
<code>net.Socket</code>. When <code>true</code>, the socket is kept open in the sending process.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Send a message to a worker or master, optionally with a handle.</p>
<p>In the master this sends a message to a specific worker. It is identical to
<a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>ChildProcess.send()</code></a>.</p>
<p>In a worker this sends a message to the master. It is identical to
<code>process.send()</code>.</p>
<p>This example will echo back all messages from the master:</p>
<pre><code class="language-js">if (cluster.isMaster) {
  const worker = cluster.fork();
  worker.send('hi there');

} else if (cluster.isWorker) {
  process.on('message', (msg) => {
    process.send(msg);
  });
}
</code></pre>
<h2>Event: <code>'disconnect'</code><span><a class="mark" href="#cluster_event_disconnect_1" id="cluster_event_disconnect_1">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.9</span>
</div>
<ul>
<li><code>worker</code> <a href="#cluster_class_worker" class="type">&#x3C;cluster.Worker></a></li>
</ul>
<p>Emitted after the worker IPC channel has disconnected. This can occur when a
worker exits gracefully, is killed, or is disconnected manually (such as with
<code>worker.disconnect()</code>).</p>
<p>There may be a delay between the <code>'disconnect'</code> and <code>'exit'</code> events. These
events can be used to detect if the process is stuck in a cleanup or if there
are long-living connections.</p>
<pre><code class="language-js">cluster.on('disconnect', (worker) => {
  console.log(`The worker #${worker.id} has disconnected`);
});
</code></pre>
<h2>Event: <code>'exit'</code><span><a class="mark" href="#cluster_event_exit_1" id="cluster_event_exit_1">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.9</span>
</div>
<ul>
<li><code>worker</code> <a href="#cluster_class_worker" class="type">&#x3C;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">&#x3C;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">&#x3C;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 <a href="#cluster_cluster_fork_env"><code>.fork()</code></a> again.</p>
<pre><code class="language-js">cluster.on('exit', (worker, code, signal) => {
  console.log('worker %d died (%s). restarting...',
              worker.process.pid, signal || code);
  cluster.fork();
});
</code></pre>
<p>See <a href="#child_process_event_exit"><code>child_process</code> event: <code>'exit'</code></a>.</p>
<h2>Event: <code>'fork'</code><span><a class="mark" href="#cluster_event_fork" id="cluster_event_fork">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>worker</code> <a href="#cluster_class_worker" class="type">&#x3C;cluster.Worker></a></li>
</ul>
<p>When a new worker is forked the cluster module will emit a <code>'fork'</code> event.
This can be used to log worker activity, and create a custom timeout.</p>
<pre><code class="language-js">const timeouts = [];
function errorMsg() {
  console.error('Something must be wrong with the connection ...');
}

cluster.on('fork', (worker) => {
  timeouts[worker.id] = setTimeout(errorMsg, 2000);
});
cluster.on('listening', (worker, address) => {
  clearTimeout(timeouts[worker.id]);
});
cluster.on('exit', (worker, code, signal) => {
  clearTimeout(timeouts[worker.id]);
  errorMsg();
});
</code></pre>
<h2>Event: <code>'listening'</code><span><a class="mark" href="#cluster_event_listening_1" id="cluster_event_listening_1">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>worker</code> <a href="#cluster_class_worker" class="type">&#x3C;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">&#x3C;Object></a></li>
</ul>
<p>After calling <code>listen()</code> from a worker, when the <code>'listening'</code> event is emitted
on the server a <code>'listening'</code> event will also be emitted on <code>cluster</code> in the
master.</p>
<p>The event handler is executed with two arguments, the <code>worker</code> contains the
worker object and the <code>address</code> object contains the following connection
properties: <code>address</code>, <code>port</code> and <code>addressType</code>. This is very useful if the
worker is listening on more than one address.</p>
<pre><code class="language-js">cluster.on('listening', (worker, address) => {
  console.log(
    `A worker is now connected to ${address.address}:${address.port}`);
});
</code></pre>
<p>The <code>addressType</code> is one of:</p>
<ul>
<li><code>4</code> (TCPv4)</li>
<li><code>6</code> (TCPv6)</li>
<li><code>-1</code> (Unix domain socket)</li>
<li><code>'udp4'</code> or <code>'udp6'</code> (UDP v4 or v6)</li>
</ul>
<h2>Event: <code>'message'</code><span><a class="mark" href="#cluster_event_message_1" id="cluster_event_message_1">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>worker</code> parameter is passed now; see below for details.</p></td></tr>
<tr><td>v2.5.0</td>
<td><p><span>Added in: v2.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>worker</code> <a href="#cluster_class_worker" class="type">&#x3C;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">&#x3C;Object></a></li>
<li><code>handle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Emitted when the cluster master receives a message from any worker.</p>
<p>See <a href="#child_process_event_message"><code>child_process</code> event: <code>'message'</code></a>.</p>
<h2>Event: <code>'online'</code><span><a class="mark" href="#cluster_event_online_1" id="cluster_event_online_1">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>worker</code> <a href="#cluster_class_worker" class="type">&#x3C;cluster.Worker></a></li>
</ul>
<p>After forking a new worker, the worker should respond with an online message.
When the master receives an online message it will emit this event.
The difference between <code>'fork'</code> and <code>'online'</code> is that fork is emitted when the
master forks a worker, and <code>'online'</code> is emitted when the worker is running.</p>
<pre><code class="language-js">cluster.on('online', (worker) => {
  console.log('Yay, the worker responded after it was forked');
});
</code></pre>
<h2>Event: <code>'setup'</code><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">&#x3C;Object></a></li>
</ul>
<p>Emitted every time <a href="#cluster_cluster_setupmaster_settings"><code>.setupMaster()</code></a> is called.</p>
<p>The <code>settings</code> object is the <code>cluster.settings</code> object at the time
<a href="#cluster_cluster_setupmaster_settings"><code>.setupMaster()</code></a> was called and is advisory only, since multiple calls to
<a href="#cluster_cluster_setupmaster_settings"><code>.setupMaster()</code></a> can be made in a single tick.</p>
<p>If accuracy is important, use <code>cluster.settings</code>.</p>
<h2><code>cluster.disconnect([callback])</code><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">&#x3C;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><code>cluster.fork([env])</code><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">&#x3C;Object></a> Key/value pairs to add to worker process environment.</li>
<li>Returns: <a href="#cluster_class_worker" class="type">&#x3C;cluster.Worker></a></li>
</ul>
<p>Spawn a new worker process.</p>
<p>This can only be called from the master process.</p>
<h2><code>cluster.isMaster</code><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">&#x3C;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><code>cluster.isWorker</code><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">&#x3C;boolean></a></li>
</ul>
<p>True if the process is not a master (it is the negation of <code>cluster.isMaster</code>).</p>
<h2><code>cluster.schedulingPolicy</code><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 <a href="#cluster_cluster_setupmaster_settings"><code>.setupMaster()</code></a> 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><code>cluster.settings</code><span><a class="mark" href="#cluster_cluster_settings" id="cluster_cluster_settings">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>serialization</code> option is supported now.</p></td></tr>
<tr><td>v9.5.0</td>
<td><p>The <code>cwd</code> option is supported now.</p></td></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>windowsHide</code> option is supported now.</p></td></tr>
<tr><td>v8.2.0</td>
<td><p>The <code>inspectPort</code> option is supported now.</p></td></tr>
<tr><td>v6.4.0</td>
<td><p>The <code>stdio</code> option is supported now.</p></td></tr>
<tr><td>v0.7.1</td>
<td><p><span>Added in: v0.7.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> List of string arguments passed to the Node.js
executable. <strong>Default:</strong> <code>process.execArgv</code>.</li>
<li><code>exec</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> File path to worker file. <strong>Default:</strong> <code>process.argv[1]</code>.</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> String arguments passed to worker.
<strong>Default:</strong> <code>process.argv.slice(2)</code>.</li>
<li><code>cwd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Current working directory of the worker process. <strong>Default:</strong>
<code>undefined</code> (inherits from parent process).</li>
<li><code>serialization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specify the kind of serialization used for sending
messages between processes. Possible values are <code>'json'</code> and <code>'advanced'</code>.
See <a href="#child_process_advanced_serialization">Advanced serialization for <code>child_process</code></a> for more details.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>silent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;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">&#x3C;number></a> Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>.)</li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>.)</li>
<li><code>inspectPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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">&#x3C;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 <a href="#cluster_cluster_setupmaster_settings"><code>.setupMaster()</code></a> (or <a href="#cluster_cluster_fork_env"><code>.fork()</code></a>) 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><code>cluster.setupMaster([settings])</code><span><a class="mark" href="#cluster_cluster_setupmaster_settings" id="cluster_cluster_setupmaster_settings">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.4.0</td>
<td><p>The <code>stdio</code> option is supported now.</p></td></tr>
<tr><td>v0.7.1</td>
<td><p><span>Added in: v0.7.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>settings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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>Any settings changes only affect future calls to <a href="#cluster_cluster_fork_env"><code>.fork()</code></a> and have no
effect on workers that are already running.</p>
<p>The only attribute of a worker that cannot be set via <code>.setupMaster()</code> is
the <code>env</code> passed to <a href="#cluster_cluster_fork_env"><code>.fork()</code></a>.</p>
<p>The defaults above apply to the first call only; the defaults for later
calls are the current values at the time of <code>cluster.setupMaster()</code> is called.</p>
<pre><code class="language-js">const cluster = require('cluster');
cluster.setupMaster({
  exec: 'worker.js',
  args: ['--use', 'https'],
  silent: true
});
cluster.fork(); // https worker
cluster.setupMaster({
  exec: 'worker.js',
  args: ['--use', 'http']
});
cluster.fork(); // http worker
</code></pre>
<p>This can only be called from the master process.</p>
<h2><code>cluster.worker</code><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">&#x3C;Object></a></li>
</ul>
<p>A reference to the current worker object. Not available in the master process.</p>
<pre><code class="language-js">const cluster = require('cluster');

if (cluster.isMaster) {
  console.log('I am master');
  cluster.fork();
  cluster.fork();
} else if (cluster.isWorker) {
  console.log(`I am worker #${cluster.worker.id}`);
}
</code></pre>
<h2><code>cluster.workers</code><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">&#x3C;Object></a></li>
</ul>
<p>A hash that stores the active worker objects, keyed by <code>id</code> field. Makes it
easy to loop through all the workers. It is only available in the master
process.</p>
<p>A worker is removed from <code>cluster.workers</code> after the worker has disconnected
<em>and</em> exited. The order between these two events cannot be determined in
advance. However, it is guaranteed that the removal from the <code>cluster.workers</code>
list happens before last <code>'disconnect'</code> or <code>'exit'</code> event is emitted.</p>
<pre><code class="language-js">// Go through all workers
function eachWorker(callback) {
  for (const id in cluster.workers) {
    callback(cluster.workers[id]);
  }
}
eachWorker((worker) => {
  worker.send('big announcement to all workers');
});
</code></pre>
<p>Using the worker's unique id is the easiest way to locate the worker.</p>
<pre><code class="language-js">socket.on('data', (id) => {
  const worker = cluster.workers[id];
});
</code></pre>
<h1>Command line options<span><a class="mark" href="#cli_command_line_options" id="cli_command_line_options">#</a></span></h1>


<p>Node.js comes with a variety of CLI options. These options expose built-in
debugging, multiple ways to execute scripts, and other helpful runtime options.</p>
<p>To view this documentation as a manual page in a terminal, run <code>man node</code>.</p>
<h2>Synopsis<span><a class="mark" href="#cli_synopsis" id="cli_synopsis">#</a></span></h2>
<p><code>node [options] [V8 options] [script.js | -e "script" | -] [--] [arguments]</code></p>
<p><code>node inspect [script.js | -e "script" | &#x3C;host>:&#x3C;port>] …</code></p>
<p><code>node --v8-options</code></p>
<p>Execute without arguments to start the <a href="repl.html">REPL</a>.</p>
<p><em>For more info about <code>node inspect</code>, please see the <a href="debugger.html">debugger</a> documentation.</em></p>
<h2>Options<span><a class="mark" href="#cli_options" id="cli_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.12.0</td>
<td><p>Underscores instead of dashes are now allowed for Node.js options as well, in addition to V8 options.</p></td></tr>
</tbody></table>
</details>
</div>
<p>All options, including V8 options, allow words to be separated by both
dashes (<code>-</code>) or underscores (<code>_</code>).</p>
<p>For example, <code>--pending-deprecation</code> is equivalent to <code>--pending_deprecation</code>.</p>
<h3><code>-</code><span><a class="mark" href="#cli" id="cli">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Alias for stdin. Analogous to the use of <code>-</code> in other command line utilities,
meaning that the script will be read from stdin, and the rest of the options
are passed to that script.</p>
<h3><code>--</code><span><a class="mark" href="#cli_1" id="cli_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.11.0</span>
</div>
<p>Indicate the end of node options. Pass the rest of the arguments to the script.
If no script filename or eval/print script is supplied prior to this, then
the next argument will be used as a script filename.</p>
<h3><code>--abort-on-uncaught-exception</code><span><a class="mark" href="#cli_abort_on_uncaught_exception" id="cli_abort_on_uncaught_exception">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.10.8</span>
</div>
<p>Aborting instead of exiting causes a core file to be generated for post-mortem
analysis using a debugger (such as <code>lldb</code>, <code>gdb</code>, and <code>mdb</code>).</p>
<p>If this flag is passed, the behavior can still be set to not abort through
<a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> (and through usage of the
<code>domain</code> module that uses it).</p>
<h3><code>--completion-bash</code><span><a class="mark" href="#cli_completion_bash" id="cli_completion_bash">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<p>Print source-able bash completion script for Node.js.</p>
<pre><code class="language-console">$ node --completion-bash > node_bash_completion
$ source node_bash_completion
</code></pre>
<h3><code>--cpu-prof</code><span><a class="mark" href="#cli_cpu_prof" id="cli_cpu_prof">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Starts the V8 CPU profiler on start up, and writes the CPU profile to disk
before exit.</p>
<p>If <code>--cpu-prof-dir</code> is not specified, the generated profile will be placed
in the current working directory.</p>
<p>If <code>--cpu-prof-name</code> is not specified, the generated profile will be
named <code>CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile</code>.</p>
<pre><code class="language-console">$ node --cpu-prof index.js
$ ls *.cpuprofile
CPU.20190409.202950.15293.0.0.cpuprofile
</code></pre>
<h3><code>--cpu-prof-dir</code><span><a class="mark" href="#cli_cpu_prof_dir" id="cli_cpu_prof_dir">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Specify the directory where the CPU profiles generated by <code>--cpu-prof</code> will
be placed.</p>
<h3><code>--cpu-prof-interval</code><span><a class="mark" href="#cli_cpu_prof_interval" id="cli_cpu_prof_interval">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.2.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Specify the sampling interval in microseconds for the CPU profiles generated
by <code>--cpu-prof</code>. The default is 1000 microseconds.</p>
<h3><code>--cpu-prof-name</code><span><a class="mark" href="#cli_cpu_prof_name" id="cli_cpu_prof_name">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Specify the file name of the CPU profile generated by <code>--cpu-prof</code>.</p>
<h3><code>--disable-proto=mode</code><span><a class="mark" href="#cli_disable_proto_mode" id="cli_disable_proto_mode">#</a></span></h3>
<!--YAML
added: v12.17.0
-->
<p>Disable the <code>Object.prototype.__proto__</code> property. If <code>mode</code> is <code>delete</code>, the
property will be removed entirely. If <code>mode</code> is <code>throw</code>, accesses to the
property will throw an exception with the code <code>ERR_PROTO_ACCESS</code>.</p>
<h3><code>--disallow-code-generation-from-strings</code><span><a class="mark" href="#cli_disallow_code_generation_from_strings" id="cli_disallow_code_generation_from_strings">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.8.0</span>
</div>
<p>Make built-in language features like <code>eval</code> and <code>new Function</code> that generate
code from strings throw an exception instead. This does not affect the Node.js
<code>vm</code> module.</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>--enable-source-maps</code><span><a class="mark" href="#cli_enable_source_maps" id="cli_enable_source_maps">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Enable experimental Source Map v3 support for stack traces.</p>
<p>Currently, overriding <code>Error.prepareStackTrace</code> is ignored when the
<code>--enable-source-maps</code> flag is set.</p>
<h3><code>--experimental-import-meta-resolve</code><span><a class="mark" href="#cli_experimental_import_meta_resolve" id="cli_experimental_import_meta_resolve">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.2</span>
</div>
<p>Enable experimental <code>import.meta.resolve()</code> support.</p>
<h3><code>--experimental-json-modules</code><span><a class="mark" href="#cli_experimental_json_modules" id="cli_experimental_json_modules">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<p>Enable experimental JSON support for the ES Module loader.</p>
<h3><code>--experimental-loader=module</code><span><a class="mark" href="#cli_experimental_loader_module" id="cli_experimental_loader_module">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span>
</div>
<p>Specify the <code>module</code> of a custom <a href="#esm_experimental_loaders">experimental ECMAScript Module loader</a>.
<code>module</code> may be either a path to a file, or an ECMAScript Module name.</p>
<h3><code>--experimental-modules</code><span><a class="mark" href="#cli_experimental_modules" id="cli_experimental_modules">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>Enable latest experimental modules features (deprecated).</p>
<h3><code>--experimental-policy</code><span><a class="mark" href="#cli_experimental_policy" id="cli_experimental_policy">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.8.0</span>
</div>
<p>Use the specified file as a security policy.</p>
<h3><code>--experimental-repl-await</code><span><a class="mark" href="#cli_experimental_repl_await" id="cli_experimental_repl_await">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>Enable experimental top-level <code>await</code> keyword support in REPL.</p>
<h3><code>--experimental-specifier-resolution=mode</code><span><a class="mark" href="#cli_experimental_specifier_resolution_mode" id="cli_experimental_specifier_resolution_mode">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p>Sets the resolution algorithm for resolving ES module specifiers. Valid options
are <code>explicit</code> and <code>node</code>.</p>
<p>The default is <code>explicit</code>, which requires providing the full path to a
module. The <code>node</code> mode will enable support for optional file extensions and
the ability to import a directory that has an index file.</p>
<p>Please see <a href="#esm_customizing_esm_specifier_resolution_algorithm">customizing ESM specifier resolution</a> for example usage.</p>
<h3><code>--experimental-vm-modules</code><span><a class="mark" href="#cli_experimental_vm_modules" id="cli_experimental_vm_modules">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
</div>
<p>Enable experimental ES Module support in the <code>vm</code> module.</p>
<h3><code>--experimental-wasi-unstable-preview1</code><span><a class="mark" href="#cli_experimental_wasi_unstable_preview1" id="cli_experimental_wasi_unstable_preview1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p>Enable experimental WebAssembly System Interface (WASI) support.</p>
<h3><code>--experimental-wasm-modules</code><span><a class="mark" href="#cli_experimental_wasm_modules" id="cli_experimental_wasm_modules">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.3.0</span>
</div>
<h3><code>--force-context-aware</code><span><a class="mark" href="#cli_force_context_aware" id="cli_force_context_aware">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<p>Disable loading native addons that are not <a href="#addons_context_aware_addons">context-aware</a>.</p>
<p>Enable experimental WebAssembly module support.</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>--frozen-intrinsics</code><span><a class="mark" href="#cli_frozen_intrinsics" id="cli_frozen_intrinsics">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Enable experimental frozen intrinsics like <code>Array</code> and <code>Object</code>.</p>
<p>Support is currently only provided for the root context and no guarantees are
currently provided that <code>global.Array</code> is indeed the default intrinsic
reference. Code may break under this flag.</p>
<p><code>--require</code> runs prior to freezing intrinsics in order to allow polyfills to
be added.</p>
<h3><code>--heapsnapshot-signal=signal</code><span><a class="mark" href="#cli_heapsnapshot_signal_signal" id="cli_heapsnapshot_signal_signal">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Enables a signal handler that causes the Node.js process to write a heap dump
when the specified signal is received. <code>signal</code> must be a valid signal name.
Disabled by default.</p>
<pre><code class="language-console">$ node --heapsnapshot-signal=SIGUSR2 index.js &#x26;
$ ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
node         1  5.5  6.1 787252 247004 ?       Ssl  16:43   0:02 node --heapsnapshot-signal=SIGUSR2 index.js
$ kill -USR2 1
$ ls
Heap.20190718.133405.15554.0.001.heapsnapshot
</code></pre>
<h3><code>--heap-prof</code><span><a class="mark" href="#cli_heap_prof" id="cli_heap_prof">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Starts the V8 heap profiler on start up, and writes the heap profile to disk
before exit.</p>
<p>If <code>--heap-prof-dir</code> is not specified, the generated profile will be placed
in the current working directory.</p>
<p>If <code>--heap-prof-name</code> is not specified, the generated profile will be
named <code>Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile</code>.</p>
<pre><code class="language-console">$ node --heap-prof index.js
$ ls *.heapprofile
Heap.20190409.202950.15293.0.001.heapprofile
</code></pre>
<h3><code>--heap-prof-dir</code><span><a class="mark" href="#cli_heap_prof_dir" id="cli_heap_prof_dir">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Specify the directory where the heap profiles generated by <code>--heap-prof</code> will
be placed.</p>
<h3><code>--heap-prof-interval</code><span><a class="mark" href="#cli_heap_prof_interval" id="cli_heap_prof_interval">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Specify the average sampling interval in bytes for the heap profiles generated
by <code>--heap-prof</code>. The default is 512 * 1024 bytes.</p>
<h3><code>--heap-prof-name</code><span><a class="mark" href="#cli_heap_prof_name" id="cli_heap_prof_name">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Specify the file name of the heap profile generated by <code>--heap-prof</code>.</p>
<h3><code>--http-parser=library</code><span><a class="mark" href="#cli_http_parser_library" id="cli_http_parser_library">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.4.0</span>
</div>
<p>Chooses an HTTP parser library. Available values are:</p>
<ul>
<li><code>llhttp</code> for <a href="https://llhttp.org/">https://llhttp.org/</a></li>
<li><code>legacy</code> for <a href="https://github.com/nodejs/http-parser">https://github.com/nodejs/http-parser</a></li>
</ul>
<p>The default is <code>llhttp</code>, unless otherwise specified when building Node.js.</p>
<p>This flag exists to aid in experimentation with the internal implementation of
the Node.js http parser.
This flag is likely to become a no-op and removed at some point in the future.</p>
<h3><code>--http-server-default-timeout=milliseconds</code><span><a class="mark" href="#cli_http_server_default_timeout_milliseconds" id="cli_http_server_default_timeout_milliseconds">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.4.0</span>
</div>
<p>Overrides the default value of <code>http</code>, <code>https</code> and <code>http2</code> server socket
timeout. Setting the value to 0 disables server socket timeout. Unless
provided, http server sockets timeout after 120s (2 minutes). Programmatic
setting of the timeout takes precedence over the value set through this
flag.</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>--input-type=type</code><span><a class="mark" href="#cli_input_type_type" id="cli_input_type_type">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>This configures Node.js to interpret string input as CommonJS or as an ES
module. String input is input via <code>--eval</code>, <code>--print</code>, or <code>STDIN</code>.</p>
<p>Valid values are <code>"commonjs"</code> and <code>"module"</code>. The default is <code>"commonjs"</code>.</p>
<h3><code>--inspect-brk[=[host:]port]</code><span><a class="mark" href="#cli_inspect_brk_host_port" id="cli_inspect_brk_host_port">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.6.0</span>
</div>
<p>Activate inspector on <code>host:port</code> and break at start of user script.
Default <code>host:port</code> is <code>127.0.0.1:9229</code>.</p>
<h3><code>--inspect-port=[host:]port</code><span><a class="mark" href="#cli_inspect_port_host_port" id="cli_inspect_port_host_port">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.6.0</span>
</div>
<p>Set the <code>host:port</code> to be used when the inspector is activated.
Useful when activating the inspector by sending the <code>SIGUSR1</code> signal.</p>
<p>Default host is <code>127.0.0.1</code>.</p>
<p>See the <a href="#inspector_security">security warning</a> below regarding the <code>host</code>
parameter usage.</p>
<h3><code>--inspect[=[host:]port]</code><span><a class="mark" href="#cli_inspect_host_port" id="cli_inspect_host_port">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.3.0</span>
</div>
<p>Activate inspector on <code>host:port</code>. Default is <code>127.0.0.1:9229</code>.</p>
<p>V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug
and profile Node.js instances. The tools attach to Node.js instances via a
tcp port and communicate using the <a href="https://chromedevtools.github.io/devtools-protocol/">Chrome DevTools Protocol</a>.</p>
<p><a id="inspector_security"></a></p>
<h4>Warning: binding inspector to a public IP:port combination is insecure<span><a class="mark" href="#cli_warning_binding_inspector_to_a_public_ip_port_combination_is_insecure" id="cli_warning_binding_inspector_to_a_public_ip_port_combination_is_insecure">#</a></span></h4>
<p>Binding the inspector to a public IP (including <code>0.0.0.0</code>) with an open port is
insecure, as it allows external hosts to connect to the inspector and perform
a <a href="https://www.owasp.org/index.php/Code_Injection">remote code execution</a> attack.</p>
<p>If specifying a host, make sure that either:</p>
<ul>
<li>The host is not accessible from public networks.</li>
<li>A firewall disallows unwanted connections on the port.</li>
</ul>
<p><strong>More specifically, <code>--inspect=0.0.0.0</code> is insecure if the port (<code>9229</code> by
default) is not firewall-protected.</strong></p>
<p>See the <a href="https://nodejs.org/en/docs/guides/debugging-getting-started/#security-implications">debugging security implications</a> section for more information.</p>
<h3><code>--inspect-publish-uid=stderr,http</code><span><a class="mark" href="#cli_inspect_publish_uid_stderr_http" id="cli_inspect_publish_uid_stderr_http">#</a></span></h3>
<p>Specify ways of the inspector web socket url exposure.</p>
<p>By default inspector websocket url is available in stderr and under <code>/json/list</code>
endpoint on <code>http://host:port/json/list</code>.</p>
<h3><code>--insecure-http-parser</code><span><a class="mark" href="#cli_insecure_http_parser" id="cli_insecure_http_parser">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.15.0</span>
</div>
<p>Use an insecure HTTP parser that accepts invalid HTTP headers. This may allow
interoperability with non-conformant HTTP implementations. It may also allow
request smuggling and other HTTP attacks that rely on invalid headers being
accepted. Avoid using this option.</p>
<h3><code>--jitless</code><span><a class="mark" href="#cli_jitless" id="cli_jitless">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Disable <a href="https://v8.dev/blog/jitless">runtime allocation of executable memory</a>. This may be
required on some platforms for security reasons. It can also reduce attack
surface on other platforms, but the performance impact may be severe.</p>
<p>This flag is inherited from V8 and is subject to change upstream. It may
disappear in a non-semver-major release.</p>
<h3><code>--max-http-header-size=size</code><span><a class="mark" href="#cli_max_http_header_size_size" id="cli_max_http_header_size_size">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.6.0</span>
</div>
<p>Specify the maximum size, in bytes, of HTTP headers. Defaults to 8KB.</p>
<h3><code>--napi-modules</code><span><a class="mark" href="#cli_napi_modules" id="cli_napi_modules">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.10.0</span>
</div>
<p>This option is a no-op. It is kept for compatibility.</p>
<h3><code>--no-deprecation</code><span><a class="mark" href="#cli_no_deprecation" id="cli_no_deprecation">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.8.0</span>
</div>
<p>Silence deprecation warnings.</p>
<h3><code>--no-force-async-hooks-checks</code><span><a class="mark" href="#cli_no_force_async_hooks_checks" id="cli_no_force_async_hooks_checks">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span>
</div>
<p>Disables runtime checks for <code>async_hooks</code>. These will still be enabled
dynamically when <code>async_hooks</code> is enabled.</p>
<h3><code>--no-warnings</code><span><a class="mark" href="#cli_no_warnings" id="cli_no_warnings">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>Silence all process warnings (including deprecations).</p>
<h3><code>--openssl-config=file</code><span><a class="mark" href="#cli_openssl_config_file" id="cli_openssl_config_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.9.0</span>
</div>
<p>Load an OpenSSL configuration file on startup. Among other uses, this can be
used to enable FIPS-compliant crypto if Node.js is built with
<code>./configure --openssl-fips</code>.</p>
<h3><code>--pending-deprecation</code><span><a class="mark" href="#cli_pending_deprecation" id="cli_pending_deprecation">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Emit pending deprecation warnings.</p>
<p>Pending deprecations are generally identical to a runtime deprecation with the
notable exception that they are turned <em>off</em> by default and will not be emitted
unless either the <code>--pending-deprecation</code> command line flag, or the
<code>NODE_PENDING_DEPRECATION=1</code> environment variable, is set. Pending deprecations
are used to provide a kind of selective "early warning" mechanism that
developers may leverage to detect deprecated API usage.</p>
<h3><code>--policy-integrity=sri</code><span><a class="mark" href="#cli_policy_integrity_sri" id="cli_policy_integrity_sri">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.7.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Instructs Node.js to error prior to running any code if the policy does not have
the specified integrity. It expects a <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity">Subresource Integrity</a> string as a
parameter.</p>
<h3><code>--preserve-symlinks</code><span><a class="mark" href="#cli_preserve_symlinks" id="cli_preserve_symlinks">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.3.0</span>
</div>
<p>Instructs the module loader to preserve symbolic links when resolving and
caching modules.</p>
<p>By default, when Node.js loads a module from a path that is symbolically linked
to a different on-disk location, Node.js will dereference the link and use the
actual on-disk "real path" of the module as both an identifier and as a root
path to locate other dependency modules. In most cases, this default behavior
is acceptable. However, when using symbolically linked peer dependencies, as
illustrated in the example below, the default behavior causes an exception to
be thrown if <code>moduleA</code> attempts to require <code>moduleB</code> as a peer dependency:</p>
<pre><code class="language-text">{appDir}
 ├── app
 │   ├── index.js
 │   └── node_modules
 │       ├── moduleA -> {appDir}/moduleA
 │       └── moduleB
 │           ├── index.js
 │           └── package.json
 └── moduleA
     ├── index.js
     └── package.json
</code></pre>
<p>The <code>--preserve-symlinks</code> command line flag instructs Node.js to use the
symlink path for modules as opposed to the real path, allowing symbolically
linked peer dependencies to be found.</p>
<p>Note, however, that using <code>--preserve-symlinks</code> can have other side effects.
Specifically, symbolically linked <em>native</em> modules can fail to load if those
are linked from more than one location in the dependency tree (Node.js would
see those as two separate modules and would attempt to load the module multiple
times, causing an exception to be thrown).</p>
<p>The <code>--preserve-symlinks</code> flag does not apply to the main module, which allows
<code>node --preserve-symlinks node_module/.bin/&#x3C;foo></code> to work. To apply the same
behavior for the main module, also use <code>--preserve-symlinks-main</code>.</p>
<h3><code>--preserve-symlinks-main</code><span><a class="mark" href="#cli_preserve_symlinks_main" id="cli_preserve_symlinks_main">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.2.0</span>
</div>
<p>Instructs the module loader to preserve symbolic links when resolving and
caching the main module (<code>require.main</code>).</p>
<p>This flag exists so that the main module can be opted-in to the same behavior
that <code>--preserve-symlinks</code> gives to all other imports; they are separate flags,
however, for backward compatibility with older Node.js versions.</p>
<p><code>--preserve-symlinks-main</code> does not imply <code>--preserve-symlinks</code>; it
is expected that <code>--preserve-symlinks-main</code> will be used in addition to
<code>--preserve-symlinks</code> when it is not desirable to follow symlinks before
resolving relative paths.</p>
<p>See <code>--preserve-symlinks</code> for more information.</p>
<h3><code>--prof</code><span><a class="mark" href="#cli_prof" id="cli_prof">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div>
<p>Generate V8 profiler output.</p>
<h3><code>--prof-process</code><span><a class="mark" href="#cli_prof_process" id="cli_prof_process">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v5.2.0</span>
</div>
<p>Process V8 profiler output generated using the V8 option <code>--prof</code>.</p>
<h3><code>--redirect-warnings=file</code><span><a class="mark" href="#cli_redirect_warnings_file" id="cli_redirect_warnings_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Write process warnings to the given file instead of printing to stderr. The
file will be created if it does not exist, and will be appended to if it does.
If an error occurs while attempting to write the warning to the file, the
warning will be written to stderr instead.</p>
<h3><code>--report-compact</code><span><a class="mark" href="#cli_report_compact" id="cli_report_compact">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<p>Write reports in a compact format, single-line JSON, more easily consumable
by log processing systems than the default multi-line format designed for
human consumption.</p>
<h3><code>--report-directory=directory</code><span><a class="mark" href="#cli_report_directory_directory" id="cli_report_directory_directory">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This option is no longer considered experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Changed from <code>--diagnostic-report-directory</code> to <code>--report-directory</code></p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Location at which the report will be generated.</p>
<h3><code>--report-filename=filename</code><span><a class="mark" href="#cli_report_filename_filename" id="cli_report_filename_filename">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This option is no longer considered experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>changed from <code>--diagnostic-report-filename</code> to <code>--report-filename</code></p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Name of the file to which the report will be written.</p>
<h3><code>--report-on-fatalerror</code><span><a class="mark" href="#cli_report_on_fatalerror" id="cli_report_on_fatalerror">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This option is no longer considered experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>changed from <code>--diagnostic-report-on-fatalerror</code> to <code>--report-on-fatalerror</code></p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enables the report to be triggered on fatal errors (internal errors within
the Node.js runtime such as out of memory) that lead to termination of the
application. Useful to inspect various diagnostic data elements such as heap,
stack, event loop state, resource consumption etc. to reason about the fatal
error.</p>
<h3><code>--report-on-signal</code><span><a class="mark" href="#cli_report_on_signal" id="cli_report_on_signal">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This option is no longer considered experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>changed from <code>--diagnostic-report-on-signal</code> to <code>--report-on-signal</code></p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enables report to be generated upon receiving the specified (or predefined)
signal to the running Node.js process. The signal to trigger the report is
specified through <code>--report-signal</code>.</p>
<h3><code>--report-signal=signal</code><span><a class="mark" href="#cli_report_signal_signal" id="cli_report_signal_signal">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This option is no longer considered experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>changed from <code>--diagnostic-report-signal</code> to <code>--report-signal</code></p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Sets or resets the signal for report generation (not supported on Windows).
Default signal is <code>SIGUSR2</code>.</p>
<h3><code>--report-uncaught-exception</code><span><a class="mark" href="#cli_report_uncaught_exception" id="cli_report_uncaught_exception">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This option is no longer considered experimental.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>changed from <code>--diagnostic-report-uncaught-exception</code> to <code>--report-uncaught-exception</code></p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enables report to be generated on uncaught exceptions. Useful when inspecting
the JavaScript stack in conjunction with native stack and other runtime
environment data.</p>
<h3><code>--throw-deprecation</code><span><a class="mark" href="#cli_throw_deprecation" id="cli_throw_deprecation">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<p>Throw errors for deprecations.</p>
<h3><code>--title=title</code><span><a class="mark" href="#cli_title_title" id="cli_title_title">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
</div>
<p>Set <code>process.title</code> on startup.</p>
<h3><code>--tls-cipher-list=list</code><span><a class="mark" href="#cli_tls_cipher_list_list" id="cli_tls_cipher_list_list">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v4.0.0</span>
</div>
<p>Specify an alternative default TLS cipher list. Requires Node.js to be built
with crypto support (default).</p>
<h3><code>--tls-keylog=file</code><span><a class="mark" href="#cli_tls_keylog_file" id="cli_tls_keylog_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p>Log TLS key material to a file. The key material is in NSS <code>SSLKEYLOGFILE</code>
format and can be used by software (such as Wireshark) to decrypt the TLS
traffic.</p>
<h3><code>--tls-max-v1.2</code><span><a class="mark" href="#cli_tls_max_v1_2" id="cli_tls_max_v1_2">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Set <a href="#tls_tls_default_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a> to 'TLSv1.2'. Use to disable support for
TLSv1.3.</p>
<h3><code>--tls-max-v1.3</code><span><a class="mark" href="#cli_tls_max_v1_3" id="cli_tls_max_v1_3">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Set default <a href="#tls_tls_default_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a> to 'TLSv1.3'. Use to enable support
for TLSv1.3.</p>
<h3><code>--tls-min-v1.0</code><span><a class="mark" href="#cli_tls_min_v1_0" id="cli_tls_min_v1_0">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Set default <a href="#tls_tls_default_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a> to 'TLSv1'. Use for compatibility with
old TLS clients or servers.</p>
<h3><code>--tls-min-v1.1</code><span><a class="mark" href="#cli_tls_min_v1_1" id="cli_tls_min_v1_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Set default <a href="#tls_tls_default_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a> to 'TLSv1.1'. Use for compatibility
with old TLS clients or servers.</p>
<h3><code>--tls-min-v1.2</code><span><a class="mark" href="#cli_tls_min_v1_2" id="cli_tls_min_v1_2">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.2.0</span>
</div>
<p>Set default <a href="#tls_tls_default_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a> to 'TLSv1.2'. This is the default for
12.x and later, but the option is supported for compatibility with older Node.js
versions.</p>
<h3><code>--tls-min-v1.3</code><span><a class="mark" href="#cli_tls_min_v1_3" id="cli_tls_min_v1_3">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Set default <a href="#tls_tls_default_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a> to 'TLSv1.3'. Use to disable support
for TLSv1.2, which is not as secure as TLSv1.3.</p>
<h3><code>--trace-deprecation</code><span><a class="mark" href="#cli_trace_deprecation" id="cli_trace_deprecation">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.8.0</span>
</div>
<p>Print stack traces for deprecations.</p>
<h3><code>--trace-event-categories</code><span><a class="mark" href="#cli_trace_event_categories" id="cli_trace_event_categories">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<p>A comma separated list of categories that should be traced when trace event
tracing is enabled using <code>--trace-events-enabled</code>.</p>
<h3><code>--trace-event-file-pattern</code><span><a class="mark" href="#cli_trace_event_file_pattern" id="cli_trace_event_file_pattern">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.8.0</span>
</div>
<p>Template string specifying the filepath for the trace event data, it
supports <code>${rotation}</code> and <code>${pid}</code>.</p>
<h3><code>--trace-events-enabled</code><span><a class="mark" href="#cli_trace_events_enabled" id="cli_trace_events_enabled">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<p>Enables the collection of trace event tracing information.</p>
<h3><code>--trace-exit</code><span><a class="mark" href="#cli_trace_exit" id="cli_trace_exit">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p>Prints a stack trace whenever an environment is exited proactively,
i.e. invoking <code>process.exit()</code>.</p>
<h3><code>--trace-sigint</code><span><a class="mark" href="#cli_trace_sigint" id="cli_trace_sigint">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<p>Prints a stack trace on SIGINT.</p>
<h3><code>--trace-sync-io</code><span><a class="mark" href="#cli_trace_sync_io" id="cli_trace_sync_io">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v2.1.0</span>
</div>
<p>Prints a stack trace whenever synchronous I/O is detected after the first turn
of the event loop.</p>
<h3><code>--trace-tls</code><span><a class="mark" href="#cli_trace_tls" id="cli_trace_tls">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.2.0</span>
</div>
<p>Prints TLS packet trace information to <code>stderr</code>. This can be used to debug TLS
connection problems.</p>
<h3><code>--trace-uncaught</code><span><a class="mark" href="#cli_trace_uncaught" id="cli_trace_uncaught">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p>Print stack traces for uncaught exceptions; usually, the stack trace associated
with the creation of an <code>Error</code> is printed, whereas this makes Node.js also
print the stack trace associated with throwing the value (which does not need
to be an <code>Error</code> instance).</p>
<p>Enabling this option may affect garbage collection behavior negatively.</p>
<h3><code>--trace-warnings</code><span><a class="mark" href="#cli_trace_warnings" id="cli_trace_warnings">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>Print stack traces for process warnings (including deprecations).</p>
<h3><code>--track-heap-objects</code><span><a class="mark" href="#cli_track_heap_objects" id="cli_track_heap_objects">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v2.4.0</span>
</div>
<p>Track heap object allocations for heap snapshots.</p>
<h3><code>--unhandled-rejections=mode</code><span><a class="mark" href="#cli_unhandled_rejections_mode" id="cli_unhandled_rejections_mode">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>By default all unhandled rejections trigger a warning plus a deprecation warning
for the very first unhandled rejection in case no <a href="#process_event_unhandledrejection"><code>unhandledRejection</code></a> hook
is used.</p>
<p>Using this flag allows to change what should happen when an unhandled rejection
occurs. One of three modes can be chosen:</p>
<ul>
<li><code>strict</code>: Raise the unhandled rejection as an uncaught exception.</li>
<li><code>warn</code>: Always trigger a warning, no matter if the <a href="#process_event_unhandledrejection"><code>unhandledRejection</code></a>
hook is set or not but do not print the deprecation warning.</li>
<li><code>none</code>: Silence all warnings.</li>
</ul>
<h3><code>--use-bundled-ca</code>, <code>--use-openssl-ca</code><span><a class="mark" href="#cli_use_bundled_ca_use_openssl_ca" id="cli_use_bundled_ca_use_openssl_ca">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.11.0</span>
</div>
<p>Use bundled Mozilla CA store as supplied by current Node.js version
or use OpenSSL's default CA store. The default store is selectable
at build-time.</p>
<p>The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store
that is fixed at release time. It is identical on all supported platforms.</p>
<p>Using OpenSSL store allows for external modifications of the store. For most
Linux and BSD distributions, this store is maintained by the distribution
maintainers and system administrators. OpenSSL CA store location is dependent on
configuration of the OpenSSL library but this can be altered at runtime using
environment variables.</p>
<p>See <code>SSL_CERT_DIR</code> and <code>SSL_CERT_FILE</code>.</p>
<h3><code>--use-largepages=mode</code><span><a class="mark" href="#cli_use_largepages_mode" id="cli_use_largepages_mode">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<p>Re-map the Node.js static code to large memory pages at startup. If supported on
the target system, this will cause the Node.js static code to be moved onto 2
MiB pages instead of 4 KiB pages.</p>
<p>The following values are valid for <code>mode</code>:</p>
<ul>
<li><code>off</code>: No mapping will be attempted. This is the default.</li>
<li><code>on</code>: If supported by the OS, mapping will be attempted. Failure to map will
be ignored and a message will be printed to standard error.</li>
<li><code>silent</code>: If supported by the OS, mapping will be attempted. Failure to map
will be ignored and will not be reported.</li>
</ul>
<h3><code>--v8-options</code><span><a class="mark" href="#cli_v8_options" id="cli_v8_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div>
<p>Print V8 command line options.</p>
<h3><code>--v8-pool-size=num</code><span><a class="mark" href="#cli_v8_pool_size_num" id="cli_v8_pool_size_num">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<p>Set V8's thread pool size which will be used to allocate background jobs.</p>
<p>If set to <code>0</code> then V8 will choose an appropriate size of the thread pool based
on the number of online processors.</p>
<p>If the value provided is larger than V8's maximum, then the largest value
will be chosen.</p>
<h3><code>--zero-fill-buffers</code><span><a class="mark" href="#cli_zero_fill_buffers" id="cli_zero_fill_buffers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>Automatically zero-fills all newly allocated <a href="#buffer_class_buffer"><code>Buffer</code></a> and <a href="#buffer_class_slowbuffer"><code>SlowBuffer</code></a>
instances.</p>
<h3><code>-c</code>, <code>--check</code><span><a class="mark" href="#cli_c_check" id="cli_c_check">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>--require</code> option is now supported when checking a file.</p></td></tr>
<tr><td>v5.0.0, v4.2.0</td>
<td><p><span>Added in: v5.0.0, v4.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Syntax check the script without executing.</p>
<h3><code>-e</code>, <code>--eval "script"</code><span><a class="mark" href="#cli_e_eval_script" id="cli_e_eval_script">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.11.0</td>
<td><p>Built-in libraries are now available as predefined variables.</p></td></tr>
<tr><td>v0.5.2</td>
<td><p><span>Added in: v0.5.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Evaluate the following argument as JavaScript. The modules which are
predefined in the REPL can also be used in <code>script</code>.</p>
<p>On Windows, using <code>cmd.exe</code> a single quote will not work correctly because it
only recognizes double <code>"</code> for quoting. In Powershell or Git bash, both <code>'</code>
and <code>"</code> are usable.</p>
<h3><code>-h</code>, <code>--help</code><span><a class="mark" href="#cli_h_help" id="cli_h_help">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div>
<p>Print node command line options.
The output of this option is less detailed than this document.</p>
<h3><code>-i</code>, <code>--interactive</code><span><a class="mark" href="#cli_i_interactive" id="cli_i_interactive">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>Opens the REPL even if stdin does not appear to be a terminal.</p>
<h3><code>-p</code>, <code>--print "script"</code><span><a class="mark" href="#cli_p_print_script" id="cli_p_print_script">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.11.0</td>
<td><p>Built-in libraries are now available as predefined variables.</p></td></tr>
<tr><td>v0.6.4</td>
<td><p><span>Added in: v0.6.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Identical to <code>-e</code> but prints the result.</p>
<h3><code>-r</code>, <code>--require module</code><span><a class="mark" href="#cli_r_require_module" id="cli_r_require_module">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div>
<p>Preload the specified module at startup.</p>
<p>Follows <code>require()</code>'s module resolution
rules. <code>module</code> may be either a path to a file, or a node module name.</p>
<h3><code>-v</code>, <code>--version</code><span><a class="mark" href="#cli_v_version" id="cli_v_version">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div>
<p>Print node's version.</p>
<h2>Environment variables<span><a class="mark" href="#cli_environment_variables" id="cli_environment_variables">#</a></span></h2>
<h3><code>NODE_DEBUG=module[,…]</code><span><a class="mark" href="#cli_node_debug_module" id="cli_node_debug_module">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.32</span>
</div>
<p><code>','</code>-separated list of core modules that should print debug information.</p>
<h3><code>NODE_DEBUG_NATIVE=module[,…]</code><span><a class="mark" href="#cli_node_debug_native_module" id="cli_node_debug_native_module">#</a></span></h3>
<p><code>','</code>-separated list of core C++ modules that should print debug information.</p>
<h3><code>NODE_DISABLE_COLORS=1</code><span><a class="mark" href="#cli_node_disable_colors_1" id="cli_node_disable_colors_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<p>When set, colors will not be used in the REPL.</p>
<h3><code>NODE_EXTRA_CA_CERTS=file</code><span><a class="mark" href="#cli_node_extra_ca_certs_file" id="cli_node_extra_ca_certs_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.3.0</span>
</div>
<p>When set, the well known "root" CAs (like VeriSign) will be extended with the
extra certificates in <code>file</code>. The file should consist of one or more trusted
certificates in PEM format. A message will be emitted (once) with
<a href="#process_process_emitwarning_warning_type_code_ctor"><code>process.emitWarning()</code></a> if the file is missing or
malformed, but any errors are otherwise ignored.</p>
<p>Neither the well known nor extra certificates are used when the <code>ca</code>
options property is explicitly specified for a TLS or HTTPS client or server.</p>
<p>This environment variable is ignored when <code>node</code> runs as setuid root or
has Linux file capabilities set.</p>
<h3><code>NODE_ICU_DATA=file</code><span><a class="mark" href="#cli_node_icu_data_file" id="cli_node_icu_data_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div>
<p>Data path for ICU (<code>Intl</code> object) data. Will extend linked-in data when compiled
with small-icu support.</p>
<h3><code>NODE_NO_WARNINGS=1</code><span><a class="mark" href="#cli_node_no_warnings_1" id="cli_node_no_warnings_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.11.0</span>
</div>
<p>When set to <code>1</code>, process warnings are silenced.</p>
<h3><code>NODE_OPTIONS=options...</code><span><a class="mark" href="#cli_node_options_options" id="cli_node_options_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>A space-separated list of command line options. <code>options...</code> are interpreted
before command line options, so command line options will override or
compound after anything in <code>options...</code>. Node.js will exit with an error if
an option that is not allowed in the environment is used, such as <code>-p</code> or a
script file.</p>
<p>In case an option value happens to contain a space (for example a path listed
in <code>--require</code>), it must be escaped using double quotes. For example:</p>
<pre><code class="language-bash">NODE_OPTIONS='--require "./my path/file.js"'
</code></pre>
<p>A singleton flag passed as a command line option will override the same flag
passed into <code>NODE_OPTIONS</code>:</p>
<pre><code class="language-bash"># The inspector will be available on port 5555
NODE_OPTIONS='--inspect=localhost:4444' node --inspect=localhost:5555
</code></pre>
<p>A flag that can be passed multiple times will be treated as if its
<code>NODE_OPTIONS</code> instances were passed first, and then its command line
instances afterwards:</p>
<pre><code class="language-bash">NODE_OPTIONS='--require "./a.js"' node --require "./b.js"
# is equivalent to:
node --require "./a.js" --require "./b.js"
</code></pre>
<p>Node.js options that are allowed are:</p>
<!-- node-options-node start -->
<ul>
<li><code>--disable-proto</code></li>
<li><code>--enable-fips</code></li>
<li><code>--enable-source-maps</code></li>
<li><code>--experimental-import-meta-resolve</code></li>
<li><code>--experimental-json-modules</code></li>
<li><code>--experimental-loader</code></li>
<li><code>--experimental-modules</code></li>
<li><code>--experimental-policy</code></li>
<li><code>--experimental-repl-await</code></li>
<li><code>--experimental-specifier-resolution</code></li>
<li><code>--experimental-vm-modules</code></li>
<li><code>--experimental-wasi-unstable-preview1</code></li>
<li><code>--experimental-wasm-modules</code></li>
<li><code>--force-context-aware</code></li>
<li><code>--force-fips</code></li>
<li><code>--frozen-intrinsics</code></li>
<li><code>--heapsnapshot-signal</code></li>
<li><code>--http-parser</code></li>
<li><code>--http-server-default-timeout</code></li>
<li><code>--icu-data-dir</code></li>
<li><code>--input-type</code></li>
<li><code>--insecure-http-parser</code></li>
<li><code>--inspect-brk</code></li>
<li><code>--inspect-port</code>, <code>--debug-port</code></li>
<li><code>--inspect-publish-uid</code></li>
<li><code>--inspect</code></li>
<li><code>--max-http-header-size</code></li>
<li><code>--napi-modules</code></li>
<li><code>--no-deprecation</code></li>
<li><code>--no-force-async-hooks-checks</code></li>
<li><code>--no-warnings</code></li>
<li><code>--openssl-config</code></li>
<li><code>--pending-deprecation</code></li>
<li><code>--policy-integrity</code></li>
<li><code>--preserve-symlinks-main</code></li>
<li><code>--preserve-symlinks</code></li>
<li><code>--prof-process</code></li>
<li><code>--redirect-warnings</code></li>
<li><code>--report-compact</code></li>
<li><code>--report-directory</code></li>
<li><code>--report-filename</code></li>
<li><code>--report-on-fatalerror</code></li>
<li><code>--report-on-signal</code></li>
<li><code>--report-signal</code></li>
<li><code>--report-uncaught-exception</code></li>
<li><code>--require</code>, <code>-r</code></li>
<li><code>--throw-deprecation</code></li>
<li><code>--title</code></li>
<li><code>--tls-cipher-list</code></li>
<li><code>--tls-keylog</code></li>
<li><code>--tls-max-v1.2</code></li>
<li><code>--tls-max-v1.3</code></li>
<li><code>--tls-min-v1.0</code></li>
<li><code>--tls-min-v1.1</code></li>
<li><code>--tls-min-v1.2</code></li>
<li><code>--tls-min-v1.3</code></li>
<li><code>--trace-deprecation</code></li>
<li><code>--trace-event-categories</code></li>
<li><code>--trace-event-file-pattern</code></li>
<li><code>--trace-events-enabled</code></li>
<li><code>--trace-exit</code></li>
<li><code>--trace-sigint</code></li>
<li><code>--trace-sync-io</code></li>
<li><code>--trace-tls</code></li>
<li><code>--trace-uncaught</code></li>
<li><code>--trace-warnings</code></li>
<li><code>--track-heap-objects</code></li>
<li><code>--unhandled-rejections</code></li>
<li><code>--use-bundled-ca</code></li>
<li><code>--use-largepages</code></li>
<li><code>--use-openssl-ca</code></li>
<li><code>--v8-pool-size</code></li>
<li>
<p><code>--zero-fill-buffers</code></p>
<!-- node-options-node end -->
</li>
</ul>
<p>V8 options that are allowed are:</p>
<!-- node-options-v8 start -->
<ul>
<li><code>--abort-on-uncaught-exception</code></li>
<li><code>--disallow-code-generation-from-strings</code></li>
<li><code>--huge-max-old-generation-size</code></li>
<li><code>--interpreted-frames-native-stack</code></li>
<li><code>--jitless</code></li>
<li><code>--max-old-space-size</code></li>
<li><code>--perf-basic-prof-only-functions</code></li>
<li><code>--perf-basic-prof</code></li>
<li><code>--perf-prof-unwinding-info</code></li>
<li><code>--perf-prof</code></li>
<li>
<p><code>--stack-trace-limit</code></p>
<!-- node-options-v8 end -->
</li>
</ul>
<p><code>--perf-basic-prof-only-functions</code>, <code>--perf-basic-prof</code>,
<code>--perf-prof-unwinding-info</code>, and <code>--perf-prof</code> are only available on Linux.</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_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_PENDING_PIPE_INSTANCES=instances</code><span><a class="mark" href="#cli_node_pending_pipe_instances_instances" id="cli_node_pending_pipe_instances_instances">#</a></span></h3>
<p>Set the number of pending pipe instance handles when the pipe server is waiting
for connections. This setting applies to Windows only.</p>
<h3><code>NODE_PRESERVE_SYMLINKS=1</code><span><a class="mark" href="#cli_node_preserve_symlinks_1" id="cli_node_preserve_symlinks_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.1.0</span>
</div>
<p>When set to <code>1</code>, instructs the module loader to preserve symbolic links when
resolving and caching modules.</p>
<h3><code>NODE_REDIRECT_WARNINGS=file</code><span><a class="mark" href="#cli_node_redirect_warnings_file" id="cli_node_redirect_warnings_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>When set, process warnings will be emitted to the given file instead of
printing to stderr. The file will be created if it does not exist, and will be
appended to if it does. If an error occurs while attempting to write the
warning to the file, the warning will be written to stderr instead. This is
equivalent to using the <code>--redirect-warnings=file</code> command-line flag.</p>
<h3><code>NODE_REPL_HISTORY=file</code><span><a class="mark" href="#cli_node_repl_history_file" id="cli_node_repl_history_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<p>Path to the file used to store the persistent REPL history. The default path is
<code>~/.node_repl_history</code>, which is overridden by this variable. Setting the value
to an empty string (<code>''</code> or <code>' '</code>) disables persistent REPL history.</p>
<h3><code>NODE_REPL_EXTERNAL_MODULE=file</code><span><a class="mark" href="#cli_node_repl_external_module_file" id="cli_node_repl_external_module_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p>Path to a Node.js module which will be loaded in place of the built-in REPL.
Overriding this value to an empty string (<code>''</code>) will use the built-in REPL.</p>
<h3><code>NODE_TLS_REJECT_UNAUTHORIZED=value</code><span><a class="mark" href="#cli_node_tls_reject_unauthorized_value" id="cli_node_tls_reject_unauthorized_value">#</a></span></h3>
<p>If <code>value</code> equals <code>'0'</code>, certificate validation is disabled for TLS connections.
This makes TLS, and HTTPS by extension, insecure. The use of this environment
variable is strongly discouraged.</p>
<h3><code>NODE_V8_COVERAGE=dir</code><span><a class="mark" href="#cli_node_v8_coverage_dir" id="cli_node_v8_coverage_dir">#</a></span></h3>
<p>When set, Node.js will begin outputting <a href="https://v8project.blogspot.com/2017/12/javascript-code-coverage.html">V8 JavaScript code coverage</a> and
<a href="https://sourcemaps.info/spec.html">Source Map</a> data to the directory provided as an argument (coverage
information is written as JSON to files with a <code>coverage</code> prefix).</p>
<p><code>NODE_V8_COVERAGE</code> will automatically propagate to subprocesses, making it
easier to instrument applications that call the <code>child_process.spawn()</code> family
of functions. <code>NODE_V8_COVERAGE</code> can be set to an empty string, to prevent
propagation.</p>
<h4>Coverage output<span><a class="mark" href="#cli_coverage_output" id="cli_coverage_output">#</a></span></h4>
<p>Coverage is output as an array of <a href="https://chromedevtools.github.io/devtools-protocol/tot/Profiler#type-ScriptCoverage">ScriptCoverage</a> objects on the top-level
key <code>result</code>:</p>
<pre><code class="language-json">{
  "result": [
    {
      "scriptId": "67",
      "url": "internal/tty.js",
      "functions": []
    }
  ]
}
</code></pre>
<h4>Source map cache<span><a class="mark" href="#cli_source_map_cache" id="cli_source_map_cache">#</a></span></h4>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>If found, source map data is appended to the top-level key <code>source-map-cache</code>
on the JSON coverage object.</p>
<p><code>source-map-cache</code> is an object with keys representing the files source maps
were extracted from, and values which include the raw source-map URL
(in the key <code>url</code>), the parsed Source Map v3 information (in the key <code>data</code>),
and the line lengths of the source file (in the key <code>lineLengths</code>).</p>
<pre><code class="language-json">{
  "result": [
    {
      "scriptId": "68",
      "url": "file:///absolute/path/to/source.js",
      "functions": []
    }
  ],
  "source-map-cache": {
    "file:///absolute/path/to/source.js": {
      "url": "./path-to-map.json",
      "data": {
        "version": 3,
        "sources": [
          "file:///absolute/path/to/original.js"
        ],
        "names": [
          "Foo",
          "console",
          "info"
        ],
        "mappings": "MAAMA,IACJC,YAAaC",
        "sourceRoot": "./"
      },
      "lineLengths": [
        13,
        62,
        38,
        27
      ]
    }
  }
}
</code></pre>
<h3><code>OPENSSL_CONF=file</code><span><a class="mark" href="#cli_openssl_conf_file" id="cli_openssl_conf_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.11.0</span>
</div>
<p>Load an OpenSSL configuration file on startup. Among other uses, this can be
used to enable FIPS-compliant crypto if Node.js is built with <code>./configure --openssl-fips</code>.</p>
<p>If the <a href="#cli_openssl_config_file"><code>--openssl-config</code></a> command line option is used, the environment
variable is ignored.</p>
<h3><code>SSL_CERT_DIR=dir</code><span><a class="mark" href="#cli_ssl_cert_dir_dir" id="cli_ssl_cert_dir_dir">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<p>If <code>--use-openssl-ca</code> is enabled, this overrides and sets OpenSSL's directory
containing trusted certificates.</p>
<p>Be aware that unless the child environment is explicitly set, this environment
variable will be inherited by any child processes, and if they use OpenSSL, it
may cause them to trust the same CAs as node.</p>
<h3><code>SSL_CERT_FILE=file</code><span><a class="mark" href="#cli_ssl_cert_file_file" id="cli_ssl_cert_file_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<p>If <code>--use-openssl-ca</code> is enabled, this overrides and sets OpenSSL's file
containing trusted certificates.</p>
<p>Be aware that unless the child environment is explicitly set, this environment
variable will be inherited by any child processes, and if they use OpenSSL, it
may cause them to trust the same CAs as node.</p>
<h3><code>UV_THREADPOOL_SIZE=size</code><span><a class="mark" href="#cli_uv_threadpool_size_size" id="cli_uv_threadpool_size_size">#</a></span></h3>
<p>Set the number of threads used in libuv's threadpool to <code>size</code> threads.</p>
<p>Asynchronous system APIs are used by Node.js whenever possible, but where they
do not exist, libuv's threadpool is used to create asynchronous node APIs based
on synchronous system APIs. Node.js APIs that use the threadpool are:</p>
<ul>
<li>all <code>fs</code> APIs, other than the file watcher APIs and those that are explicitly
synchronous</li>
<li>asynchronous crypto APIs such as <code>crypto.pbkdf2()</code>, <code>crypto.scrypt()</code>,
<code>crypto.randomBytes()</code>, <code>crypto.randomFill()</code>, <code>crypto.generateKeyPair()</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>
<h2>Useful V8 options<span><a class="mark" href="#cli_useful_v8_options" id="cli_useful_v8_options">#</a></span></h2>
<p>V8 has its own set of CLI options. Any V8 CLI option that is provided to <code>node</code>
will be passed on to V8 to handle. V8's options have <em>no stability guarantee</em>.
The V8 team themselves don't consider them to be part of their formal API,
and reserve the right to change them at any time. Likewise, they are not
covered by the Node.js stability guarantees. Many of the V8
options are of interest only to V8 developers. Despite this, there is a small
set of V8 options that are widely applicable to Node.js, and they are
documented here:</p>
<h3><code>--max-old-space-size=SIZE</code> (in megabytes)<span><a class="mark" href="#cli_max_old_space_size_size_in_megabytes" id="cli_max_old_space_size_size_in_megabytes">#</a></span></h3>
<p>Sets the max memory size of V8's old memory section. As memory
consumption approaches the limit, V8 will spend more time on
garbage collection in an effort to free unused memory.</p>
<p>On a machine with 2GB of memory, consider setting this to
1536 (1.5GB) to leave some memory for other uses and avoid swapping.</p>
<pre><code class="language-console">$ node --max-old-space-size=1536 index.js
</code></pre>
<h1>Console<span><a class="mark" href="#console_console" id="console_console">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>console</code> module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.</p>
<p>The module exports two specific components:</p>
<ul>
<li>A <code>Console</code> class with methods such as <code>console.log()</code>, <code>console.error()</code> and
<code>console.warn()</code> that can be used to write to any Node.js stream.</li>
<li>A global <code>console</code> instance configured to write to <a href="#process_process_stdout"><code>process.stdout</code></a> and
<a href="#process_process_stderr"><code>process.stderr</code></a>. The global <code>console</code> can be used without calling
<code>require('console')</code>.</li>
</ul>
<p><strong><em>Warning</em></strong>: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the <a href="#process_a_note_on_process_i_o">note on process I/O</a> for
more information.</p>
<p>Example using the global <code>console</code>:</p>
<pre><code class="language-js">console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to stderr

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
</code></pre>
<p>Example using the <code>Console</code> class:</p>
<pre><code class="language-js">const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
</code></pre>
<h2>Class: <code>Console</code><span><a class="mark" href="#console_class_console" id="console_class_console">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Errors that occur while writing to the underlying streams will now be ignored by default.</p></td></tr>
</tbody></table>
</details>
</div>

<p>The <code>Console</code> class can be used to create a simple logger with configurable
output streams and can be accessed using either <code>require('console').Console</code>
or <code>console.Console</code> (or their destructured counterparts):</p>
<pre><code class="language-js">const { Console } = require('console');
</code></pre>
<pre><code class="language-js">const { Console } = console;
</code></pre>
<h3><code>new Console(stdout[, stderr][, ignoreErrors])</code><span><a class="mark" href="#console_new_console_stdout_stderr_ignoreerrors" id="console_new_console_stdout_stderr_ignoreerrors">#</a></span></h3>
<h3><code>new Console(options)</code><span><a class="mark" href="#console_new_console_options" id="console_new_console_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>The <code>groupIndentation</code> option was introduced.</p></td></tr>
<tr><td>v11.7.0</td>
<td><p>The <code>inspectOptions</code> option is introduced.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>Console</code> constructor now supports an <code>options</code> argument, and the <code>colorMode</code> option was introduced.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>ignoreErrors</code> option was introduced.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>stdout</code> <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a></li>
<li><code>stderr</code> <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a></li>
<li><code>ignoreErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Ignore errors when writing to the underlying
streams. <strong>Default:</strong> <code>true</code>.</li>
<li><code>colorMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Set color support for this <code>Console</code> instance.
Setting to <code>true</code> enables coloring while inspecting values. Setting to
<code>false</code> disables coloring while inspecting values. Setting to
<code>'auto'</code> makes color support depend on the value of the <code>isTTY</code> property
and the value returned by <code>getColorDepth()</code> on the respective stream. This
option can not be used, if <code>inspectOptions.colors</code> is set as well.
<strong>Default:</strong> <code>'auto'</code>.</li>
<li><code>inspectOptions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Specifies options that are passed along to
<a href="#util_util_inspect_object_options"><code>util.inspect()</code></a>.</li>
<li><code>groupIndentation</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Set group indentation.
<strong>Default:</strong> <code>2</code>.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>Console</code> with one or two writable stream instances. <code>stdout</code> is a
writable stream to print log or info output. <code>stderr</code> is used for warning or
error output. If <code>stderr</code> is not provided, <code>stdout</code> is used for <code>stderr</code>.</p>
<pre><code class="language-js">const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// Custom simple logger
const logger = new Console({ stdout: output, stderr: errorOutput });
// use it like console
const count = 5;
logger.log('count: %d', count);
// In stdout.log: count 5
</code></pre>
<p>The global <code>console</code> is a special <code>Console</code> whose output is sent to
<a href="#process_process_stdout"><code>process.stdout</code></a> and <a href="#process_process_stderr"><code>process.stderr</code></a>. It is equivalent to calling:</p>
<pre><code class="language-js">new Console({ stdout: process.stdout, stderr: process.stderr });
</code></pre>
<h3><code>console.assert(value[, ...message])</code><span><a class="mark" href="#console_console_assert_value_message" id="console_console_assert_value_message">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The implementation is now spec compliant and does not throw anymore.</p></td></tr>
<tr><td>v0.1.101</td>
<td><p><span>Added in: v0.1.101</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The value tested for being truthy.</li>
<li><code>...message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> All arguments besides <code>value</code> are used as error message.</li>
</ul>
<p>A simple assertion test that verifies whether <code>value</code> is truthy. If it is not,
<code>Assertion failed</code> is logged. If provided, the error <code>message</code> is formatted
using <a href="#util_util_format_format_args"><code>util.format()</code></a> by passing along all message arguments. The output is
used as the error message.</p>
<pre><code class="language-js">console.assert(true, 'does nothing');
// OK
console.assert(false, 'Whoops %s work', 'didn\'t');
// Assertion failed: Whoops didn't work
</code></pre>
<p>Calling <code>console.assert()</code> with a falsy assertion will only cause the <code>message</code>
to be printed to the console without interrupting execution of subsequent code.</p>
<h3><code>console.clear()</code><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><code>console.count([label])</code><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">&#x3C;string></a> The display label for the counter. <strong>Default:</strong> <code>'default'</code>.</li>
</ul>
<p>Maintains an internal counter specific to <code>label</code> and outputs to <code>stdout</code> the
number of times <code>console.count()</code> has been called with the given <code>label</code>.</p>
<!-- eslint-skip -->
<pre><code class="language-js">> console.count()
default: 1
undefined
> console.count('default')
default: 2
undefined
> console.count('abc')
abc: 1
undefined
> console.count('xyz')
xyz: 1
undefined
> console.count('abc')
abc: 2
undefined
> console.count()
default: 3
undefined
>
</code></pre>
<h3><code>console.countReset([label])</code><span><a class="mark" href="#console_console_countreset_label" id="console_console_countreset_label">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The display label for the counter. <strong>Default:</strong> <code>'default'</code>.</li>
</ul>
<p>Resets the internal counter specific to <code>label</code>.</p>
<!-- eslint-skip -->
<pre><code class="language-js">> console.count('abc');
abc: 1
undefined
> console.countReset('abc');
undefined
> console.count('abc');
abc: 1
undefined
>
</code></pre>
<h3><code>console.debug(data[, ...args])</code><span><a class="mark" href="#console_console_debug_data_args" id="console_console_debug_data_args">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.10.0</td>
<td><p><code>console.debug</code> is now an alias for <code>console.log</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><span>Added in: v8.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>The <code>console.debug()</code> function is an alias for <a href="#console_console_log_data_args"><code>console.log()</code></a>.</p>
<h3><code>console.dir(obj[, options])</code><span><a class="mark" href="#console_console_dir_obj_options" id="console_console_dir_obj_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.101</span>
</div>
<ul>
<li><code>obj</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>showHidden</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code> then the object's non-enumerable and symbol
properties will be shown too. <strong>Default:</strong> <code>false</code>.</li>
<li><code>depth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Tells <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> how many times to recurse while
formatting the object. This is useful for inspecting large complicated
objects. To make it recurse indefinitely, pass <code>null</code>. <strong>Default:</strong> <code>2</code>.</li>
<li><code>colors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, then the output will be styled with ANSI color
codes. Colors are customizable;
see <a href="#util_customizing_util_inspect_colors">customizing <code>util.inspect()</code> colors</a>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Uses <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> on <code>obj</code> and prints the resulting string to <code>stdout</code>.
This function bypasses any custom <code>inspect()</code> function defined on <code>obj</code>.</p>
<h3><code>console.dirxml(...data)</code><span><a class="mark" href="#console_console_dirxml_data" id="console_console_dirxml_data">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.3.0</td>
<td><p><code>console.dirxml</code> now calls <code>console.log</code> for its arguments.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><span>Added in: v8.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>...data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>This method calls <code>console.log()</code> passing it the arguments received.
This method does not produce any XML formatting.</p>
<h3><code>console.error([data][, ...args])</code><span><a class="mark" href="#console_console_error_data_args" id="console_console_error_data_args">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Prints to <code>stderr</code> with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to <a href="http://man7.org/linux/man-pages/man3/printf.3.html"><code>printf(3)</code></a> (the arguments are all passed to
<a href="#util_util_format_format_args"><code>util.format()</code></a>).</p>
<pre><code class="language-js">const code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
</code></pre>
<p>If formatting elements (e.g. <code>%d</code>) are not found in the first string then
<a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> is called on each argument and the resulting string
values are concatenated. See <a href="#util_util_format_format_args"><code>util.format()</code></a> for more information.</p>
<h3><code>console.group([...label])</code><span><a class="mark" href="#console_console_group_label" id="console_console_group_label">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>...label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Increases indentation of subsequent lines by spaces for <code>groupIndentation</code>
length.</p>
<p>If one or more <code>label</code>s are provided, those are printed first without the
additional indentation.</p>
<h3><code>console.groupCollapsed()</code><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><code>console.groupEnd()</code><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 spaces for <code>groupIndentation</code>
length.</p>
<h3><code>console.info([data][, ...args])</code><span><a class="mark" href="#console_console_info_data_args" id="console_console_info_data_args">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>The <code>console.info()</code> function is an alias for <a href="#console_console_log_data_args"><code>console.log()</code></a>.</p>
<h3><code>console.log([data][, ...args])</code><span><a class="mark" href="#console_console_log_data_args" id="console_console_log_data_args">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Prints to <code>stdout</code> with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to <a href="http://man7.org/linux/man-pages/man3/printf.3.html"><code>printf(3)</code></a> (the arguments are all passed to
<a href="#util_util_format_format_args"><code>util.format()</code></a>).</p>
<pre><code class="language-js">const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
</code></pre>
<p>See <a href="#util_util_format_format_args"><code>util.format()</code></a> for more information.</p>
<h3><code>console.table(tabularData[, properties])</code><span><a class="mark" href="#console_console_table_tabulardata_properties" id="console_console_table_tabulardata_properties">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>tabularData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>properties</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Alternate properties for constructing the table.</li>
</ul>
<p>Try to construct a table with the columns of the properties of <code>tabularData</code>
(or use <code>properties</code>) and rows of <code>tabularData</code> and log it. Falls back to just
logging the argument if it can’t be parsed as tabular.</p>
<pre><code class="language-js">// These can't be parsed as tabular data
console.table(Symbol());
// Symbol()

console.table(undefined);
// undefined

console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
// ┌─────────┬─────┬─────┐
// │ (index) │  a  │  b  │
// ├─────────┼─────┼─────┤
// │    0    │  1  │ 'Y' │
// │    1    │ 'Z' │  2  │
// └─────────┴─────┴─────┘

console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
// ┌─────────┬─────┐
// │ (index) │  a  │
// ├─────────┼─────┤
// │    0    │  1  │
// │    1    │ 'Z' │
// └─────────┴─────┘
</code></pre>
<h3><code>console.time([label])</code><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">&#x3C;string></a> <strong>Default:</strong> <code>'default'</code></li>
</ul>
<p>Starts a timer that can be used to compute the duration of an operation. Timers
are identified by a unique <code>label</code>. Use the same <code>label</code> when calling
<a href="#console_console_timeend_label"><code>console.timeEnd()</code></a> to stop the timer and output the elapsed time in
milliseconds to <code>stdout</code>. Timer durations are accurate to the sub-millisecond.</p>
<h3><code>console.timeEnd([label])</code><span><a class="mark" href="#console_console_timeend_label" id="console_console_timeend_label">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>This method no longer supports multiple calls that don’t map to individual <code>console.time()</code> calls; see below for details.</p></td></tr>
<tr><td>v0.1.104</td>
<td><p><span>Added in: v0.1.104</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'default'</code></li>
</ul>
<p>Stops a timer that was previously started by calling <a href="#console_console_time_label"><code>console.time()</code></a> and
prints the result to <code>stdout</code>:</p>
<pre><code class="language-js">console.time('100-elements');
for (let i = 0; i &#x3C; 100; i++) {}
console.timeEnd('100-elements');
// prints 100-elements: 225.438ms
</code></pre>
<h3><code>console.timeLog([label][, ...data])</code><span><a class="mark" href="#console_console_timelog_label_data" id="console_console_timelog_label_data">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'default'</code></li>
<li><code>...data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>For a timer that was previously started by calling <a href="#console_console_time_label"><code>console.time()</code></a>, prints
the elapsed time and other <code>data</code> arguments to <code>stdout</code>:</p>
<pre><code class="language-js">console.time('process');
const value = expensiveProcess1(); // Returns 42
console.timeLog('process', value);
// Prints "process: 365.227ms 42".
doExpensiveProcess2(value);
console.timeEnd('process');
</code></pre>
<h3><code>console.trace([message][, ...args])</code><span><a class="mark" href="#console_console_trace_message_args" id="console_console_trace_message_args">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Prints to <code>stderr</code> the string <code>'Trace: '</code>, followed by the <a href="#util_util_format_format_args"><code>util.format()</code></a>
formatted message and stack trace to the current position in the code.</p>
<pre><code class="language-js">console.trace('Show me');
// Prints: (stack trace will vary based on where trace is called)
//  Trace: Show me
//    at repl:2:9
//    at REPLServer.defaultEval (repl.js:248:27)
//    at bound (domain.js:287:14)
//    at REPLServer.runBound [as eval] (domain.js:300:12)
//    at REPLServer.&#x3C;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><code>console.warn([data][, ...args])</code><span><a class="mark" href="#console_console_warn_data_args" id="console_console_warn_data_args">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>The <code>console.warn()</code> function is an alias for <a href="#console_console_error_data_args"><code>console.error()</code></a>.</p>
<h2>Inspector only methods<span><a class="mark" href="#console_inspector_only_methods" id="console_inspector_only_methods">#</a></span></h2>
<p>The following methods are exposed by the V8 engine in the general API but do
not display anything unless used in conjunction with the <a href="debugger.html">inspector</a>
(<code>--inspect</code> flag).</p>
<h3><code>console.profile([label])</code><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">&#x3C;string></a></li>
</ul>
<p>This method does not display anything unless used in the inspector. The
<code>console.profile()</code> method starts a JavaScript CPU profile with an optional
label until <a href="#console_console_profileend_label"><code>console.profileEnd()</code></a> is called. The profile is then added to
the <strong>Profile</strong> panel of the inspector.</p>
<pre><code class="language-js">console.profile('MyLabel');
// Some code
console.profileEnd('MyLabel');
// Adds the profile 'MyLabel' to the Profiles panel of the inspector.
</code></pre>
<h3><code>console.profileEnd([label])</code><span><a class="mark" href="#console_console_profileend_label" id="console_console_profileend_label">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>This method does not display anything unless used in the inspector. Stops the
current JavaScript CPU profiling session if one has been started and prints
the report to the <strong>Profiles</strong> panel of the inspector. See
<a href="#console_console_profile_label"><code>console.profile()</code></a> for an example.</p>
<p>If this method is called without a label, the most recently started profile is
stopped.</p>
<h3><code>console.timeStamp([label])</code><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">&#x3C;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>
<h1>Crypto<span><a class="mark" href="#crypto_crypto" id="crypto_crypto">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>crypto</code> module provides cryptographic functionality that includes a set of
wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.</p>
<p>Use <code>require('crypto')</code> to access this module.</p>
<pre><code class="language-js">const crypto = require('crypto');

const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
                   .update('I love cupcakes')
                   .digest('hex');
console.log(hash);
// Prints:
//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
</code></pre>
<h2>Determining if crypto support is unavailable<span><a class="mark" href="#crypto_determining_if_crypto_support_is_unavailable" id="crypto_determining_if_crypto_support_is_unavailable">#</a></span></h2>
<p>It is possible for Node.js to be built without including support for the
<code>crypto</code> module. In such cases, calling <code>require('crypto')</code> will result in an
error being thrown.</p>
<pre><code class="language-js">let crypto;
try {
  crypto = require('crypto');
} catch (err) {
  console.log('crypto support is disabled!');
}
</code></pre>
<h2>Class: <code>Certificate</code><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><code>&#x3C;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>&#x3C;keygen></code> element. Node.js uses <a href="https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html">OpenSSL's SPKAC implementation</a> internally.</p>
<h3><code>Certificate.exportChallenge(spkac)</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The challenge component of the <code>spkac</code> data structure, which
includes a public key and a challenge.</li>
</ul>
<pre><code class="language-js">const { Certificate } = require('crypto');
const spkac = getSpkacSomehow();
const challenge = Certificate.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
</code></pre>
<h3><code>Certificate.exportPublicKey(spkac[, encoding])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>spkac</code> string.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The public key component of the <code>spkac</code> data structure,
which includes a public key and a challenge.</li>
</ul>
<pre><code class="language-js">const { Certificate } = require('crypto');
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as &#x3C;Buffer ...>
</code></pre>
<h3><code>Certificate.verifySpkac(spkac)</code><span><a class="mark" href="#crypto_certificate_verifyspkac_spkac" id="crypto_certificate_verifyspkac_spkac">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span>
</div>
<ul>
<li><code>spkac</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if the given <code>spkac</code> data structure is valid,
<code>false</code> otherwise.</li>
</ul>
<pre><code class="language-js">const { Certificate } = require('crypto');
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
</code></pre>
<h3>Legacy API<span><a class="mark" href="#crypto_legacy_api" id="crypto_legacy_api">#</a></span></h3>
<p>As a still supported legacy interface, it is possible (but not recommended) to
create new instances of the <code>crypto.Certificate</code> class as illustrated in the
examples below.</p>
<h4><code>new crypto.Certificate()</code><span><a class="mark" href="#crypto_new_crypto_certificate" id="crypto_new_crypto_certificate">#</a></span></h4>
<p>Instances of the <code>Certificate</code> class can be created using the <code>new</code> keyword
or by calling <code>crypto.Certificate()</code> as a function:</p>
<pre><code class="language-js">const crypto = require('crypto');

const cert1 = new crypto.Certificate();
const cert2 = crypto.Certificate();
</code></pre>
<h4><code>certificate.exportChallenge(spkac)</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The challenge component of the <code>spkac</code> data structure, which
includes a public key and a challenge.</li>
</ul>
<pre><code class="language-js">const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
</code></pre>
<h4><code>certificate.exportPublicKey(spkac)</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The public key component of the <code>spkac</code> data structure,
which includes a public key and a challenge.</li>
</ul>
<pre><code class="language-js">const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as &#x3C;Buffer ...>
</code></pre>
<h4><code>certificate.verifySpkac(spkac)</code><span><a class="mark" href="#crypto_certificate_verifyspkac_spkac_1" id="crypto_certificate_verifyspkac_spkac_1">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div>
<ul>
<li><code>spkac</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if the given <code>spkac</code> data structure is valid,
<code>false</code> otherwise.</li>
</ul>
<pre><code class="language-js">const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
</code></pre>
<h2>Class: <code>Cipher</code><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>
<ul>
<li>Extends: <a href="#stream_class_stream_transform" class="type">&#x3C;stream.Transform></a></li>
</ul>
<p>Instances of the <code>Cipher</code> class are used to encrypt data. The class can be
used in one of two ways:</p>
<ul>
<li>As a <a href="stream.html">stream</a> that is both readable and writable, where plain unencrypted
data is written to produce encrypted data on the readable side, or</li>
<li>Using the <a href="#crypto_cipher_update_data_inputencoding_outputencoding"><code>cipher.update()</code></a> and <a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> methods to produce
the encrypted data.</li>
</ul>
<p>The <a href="#crypto_crypto_createcipher_algorithm_password_options"><code>crypto.createCipher()</code></a> or <a href="#crypto_crypto_createcipheriv_algorithm_key_iv_options"><code>crypto.createCipheriv()</code></a> methods are
used to create <code>Cipher</code> instances. <code>Cipher</code> objects are not to be created
directly using the <code>new</code> keyword.</p>
<p>Example: Using <code>Cipher</code> objects as streams:</p>
<pre><code class="language-js">const crypto = require('crypto');

const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Key length is dependent on the algorithm. In this case for aes192, it is
// 24 bytes (192 bits).
// Use async `crypto.scrypt()` instead.
const key = crypto.scryptSync(password, 'salt', 24);
// Use `crypto.randomBytes()` to generate a random iv instead of the static iv
// shown here.
const iv = Buffer.alloc(16, 0); // Initialization vector.

const cipher = crypto.createCipheriv(algorithm, key, iv);

let encrypted = '';
cipher.on('readable', () => {
  let chunk;
  while (null !== (chunk = cipher.read())) {
    encrypted += chunk.toString('hex');
  }
});
cipher.on('end', () => {
  console.log(encrypted);
  // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
});

cipher.write('some clear text data');
cipher.end();
</code></pre>
<p>Example: Using <code>Cipher</code> and piped streams:</p>
<pre><code class="language-js">const crypto = require('crypto');
const fs = require('fs');

const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Use the async `crypto.scrypt()` instead.
const key = crypto.scryptSync(password, 'salt', 24);
// Use `crypto.randomBytes()` to generate a random iv instead of the static iv
// shown here.
const iv = Buffer.alloc(16, 0); // Initialization vector.

const cipher = crypto.createCipheriv(algorithm, key, iv);

const input = fs.createReadStream('test.js');
const output = fs.createWriteStream('test.enc');

input.pipe(cipher).pipe(output);
</code></pre>
<p>Example: Using the <a href="#crypto_cipher_update_data_inputencoding_outputencoding"><code>cipher.update()</code></a> and <a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> methods:</p>
<pre><code class="language-js">const crypto = require('crypto');

const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Use the async `crypto.scrypt()` instead.
const key = crypto.scryptSync(password, 'salt', 24);
// Use `crypto.randomBytes` to generate a random iv instead of the static iv
// shown here.
const iv = Buffer.alloc(16, 0); // Initialization vector.

const cipher = crypto.createCipheriv(algorithm, key, iv);

let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);
// Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
</code></pre>
<h3><code>cipher.final([outputEncoding])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Any remaining enciphered contents.
If <code>outputEncoding</code> is specified, a string is
returned. If an <code>outputEncoding</code> is not provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</li>
</ul>
<p>Once the <code>cipher.final()</code> method has been called, the <code>Cipher</code> object can no
longer be used to encrypt data. Attempts to call <code>cipher.final()</code> more than
once will result in an error being thrown.</p>
<h3><code>cipher.setAAD(buffer[, options])</code><span><a class="mark" href="#crypto_cipher_setaad_buffer_options" id="crypto_cipher_setaad_buffer_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></p>
<ul>
<li><code>plaintextLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
<li>Returns: <a href="#crypto_class_cipher" class="type">&#x3C;Cipher></a> for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code> and <code>OCB</code> are
currently supported), the <code>cipher.setAAD()</code> method sets the value used for the
<em>additional authenticated data</em> (AAD) input parameter.</p>
<p>The <code>options</code> argument is optional for <code>GCM</code> and <code>OCB</code>. When using <code>CCM</code>, the
<code>plaintextLength</code> option must be specified and its value must match the length
of the plaintext in bytes. See <a href="#crypto_ccm_mode">CCM mode</a>.</p>
<p>The <code>cipher.setAAD()</code> method must be called before <a href="#crypto_cipher_update_data_inputencoding_outputencoding"><code>cipher.update()</code></a>.</p>
<h3><code>cipher.getAuthTag()</code><span><a class="mark" href="#crypto_cipher_getauthtag" id="crypto_cipher_getauthtag">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div>
<ul>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code>
and <code>OCB</code> are currently supported), the <code>cipher.getAuthTag()</code> method returns a
<a href="buffer.html"><code>Buffer</code></a> containing the <em>authentication tag</em> that has been computed from
the given data.</li>
</ul>
<p>The <code>cipher.getAuthTag()</code> method should only be called after encryption has
been completed using the <a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> method.</p>
<h3><code>cipher.setAutoPadding([autoPadding])</code><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">&#x3C;boolean></a> <strong>Default:</strong> <code>true</code></li>
<li>Returns: <a href="#crypto_class_cipher" class="type">&#x3C;Cipher></a> for method chaining.</li>
</ul>
<p>When using block encryption algorithms, the <code>Cipher</code> class will automatically
add padding to the input data to the appropriate block size. To disable the
default padding call <code>cipher.setAutoPadding(false)</code>.</p>
<p>When <code>autoPadding</code> is <code>false</code>, the length of the entire input data must be a
multiple of the cipher's block size or <a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> will throw an error.
Disabling automatic padding is useful for non-standard padding, for instance
using <code>0x0</code> instead of PKCS padding.</p>
<p>The <code>cipher.setAutoPadding()</code> method must be called before
<a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a>.</p>
<h3><code>cipher.update(data[, inputEncoding][, outputEncoding])</code><span><a class="mark" href="#crypto_cipher_update_data_inputencoding_outputencoding" id="crypto_cipher_update_data_inputencoding_outputencoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the data.</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Updates the cipher with <code>data</code>. If the <code>inputEncoding</code> argument is given,
the <code>data</code>
argument is a string using the specified encoding. If the <code>inputEncoding</code>
argument is not given, <code>data</code> must be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>, then
<code>inputEncoding</code> is ignored.</p>
<p>The <code>outputEncoding</code> specifies the output format of the enciphered
data. If the <code>outputEncoding</code>
is specified, a string using the specified encoding is returned. If no
<code>outputEncoding</code> is provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<p>The <code>cipher.update()</code> method can be called multiple times with new data until
<a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> is called. Calling <code>cipher.update()</code> after
<a href="#crypto_cipher_final_outputencoding"><code>cipher.final()</code></a> will result in an error being thrown.</p>
<h2>Class: <code>Decipher</code><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>
<ul>
<li>Extends: <a href="#stream_class_stream_transform" class="type">&#x3C;stream.Transform></a></li>
</ul>
<p>Instances of the <code>Decipher</code> class are used to decrypt data. The class can be
used in one of two ways:</p>
<ul>
<li>As a <a href="stream.html">stream</a> that is both readable and writable, where plain encrypted
data is written to produce unencrypted data on the readable side, or</li>
<li>Using the <a href="#crypto_decipher_update_data_inputencoding_outputencoding"><code>decipher.update()</code></a> and <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> methods to
produce the unencrypted data.</li>
</ul>
<p>The <a href="#crypto_crypto_createdecipher_algorithm_password_options"><code>crypto.createDecipher()</code></a> or <a href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options"><code>crypto.createDecipheriv()</code></a> methods are
used to create <code>Decipher</code> instances. <code>Decipher</code> objects are not to be created
directly using the <code>new</code> keyword.</p>
<p>Example: Using <code>Decipher</code> objects as streams:</p>
<pre><code class="language-js">const crypto = require('crypto');

const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Key length is dependent on the algorithm. In this case for aes192, it is
// 24 bytes (192 bits).
// Use the async `crypto.scrypt()` instead.
const key = crypto.scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.

const decipher = crypto.createDecipheriv(algorithm, key, iv);

let decrypted = '';
decipher.on('readable', () => {
  while (null !== (chunk = decipher.read())) {
    decrypted += chunk.toString('utf8');
  }
});
decipher.on('end', () => {
  console.log(decrypted);
  // Prints: some clear text data
});

// Encrypted with same algorithm, key and iv.
const encrypted =
  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
decipher.write(encrypted, 'hex');
decipher.end();
</code></pre>
<p>Example: Using <code>Decipher</code> and piped streams:</p>
<pre><code class="language-js">const crypto = require('crypto');
const fs = require('fs');

const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Use the async `crypto.scrypt()` instead.
const key = crypto.scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.

const decipher = crypto.createDecipheriv(algorithm, key, iv);

const input = fs.createReadStream('test.enc');
const output = fs.createWriteStream('test.js');

input.pipe(decipher).pipe(output);
</code></pre>
<p>Example: Using the <a href="#crypto_decipher_update_data_inputencoding_outputencoding"><code>decipher.update()</code></a> and <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> methods:</p>
<pre><code class="language-js">const crypto = require('crypto');

const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Use the async `crypto.scrypt()` instead.
const key = crypto.scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.

const decipher = crypto.createDecipheriv(algorithm, key, iv);

// Encrypted using same algorithm, key and iv.
const encrypted =
  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
// Prints: some clear text data
</code></pre>
<h3><code>decipher.final([outputEncoding])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Any remaining deciphered contents.
If <code>outputEncoding</code> is specified, a string is
returned. If an <code>outputEncoding</code> is not provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</li>
</ul>
<p>Once the <code>decipher.final()</code> method has been called, the <code>Decipher</code> object can
no longer be used to decrypt data. Attempts to call <code>decipher.final()</code> more
than once will result in an error being thrown.</p>
<h3><code>decipher.setAAD(buffer[, options])</code><span><a class="mark" href="#crypto_decipher_setaad_buffer_options" id="crypto_decipher_setaad_buffer_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.2.0</td>
<td><p>This method now returns a reference to <code>decipher</code>.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p><span>Added in: v1.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></p>
<ul>
<li><code>plaintextLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
<li>Returns: <a href="#crypto_class_decipher" class="type">&#x3C;Decipher></a> for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code> and <code>OCB</code> are
currently supported), the <code>decipher.setAAD()</code> method sets the value used for the
<em>additional authenticated data</em> (AAD) input parameter.</p>
<p>The <code>options</code> argument is optional for <code>GCM</code>. When using <code>CCM</code>, the
<code>plaintextLength</code> option must be specified and its value must match the length
of the ciphertext in bytes. See <a href="#crypto_ccm_mode">CCM mode</a>.</p>
<p>The <code>decipher.setAAD()</code> method must be called before <a href="#crypto_decipher_update_data_inputencoding_outputencoding"><code>decipher.update()</code></a>.</p>
<h3><code>decipher.setAuthTag(buffer)</code><span><a class="mark" href="#crypto_decipher_setauthtag_buffer" id="crypto_decipher_setauthtag_buffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>This method now throws if the GCM tag length is invalid.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>This method now returns a reference to <code>decipher</code>.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p><span>Added in: v1.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="#crypto_class_decipher" class="type">&#x3C;Decipher></a> for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code> and <code>OCB</code> are
currently supported), the <code>decipher.setAuthTag()</code> method is used to pass in the
received <em>authentication tag</em>. If no tag is provided, or if the cipher text
has been tampered with, <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> will throw, indicating that the
cipher text should be discarded due to failed authentication. If the tag length
is invalid according to <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf">NIST SP 800-38D</a> or does not match the value of the
<code>authTagLength</code> option, <code>decipher.setAuthTag()</code> will throw an error.</p>
<p>The <code>decipher.setAuthTag()</code> method must be called before <a href="#crypto_decipher_update_data_inputencoding_outputencoding"><code>decipher.update()</code></a>
for <code>CCM</code> mode or before <a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> for <code>GCM</code> and <code>OCB</code> modes.
<code>decipher.setAuthTag()</code> can only be called once.</p>
<h3><code>decipher.setAutoPadding([autoPadding])</code><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">&#x3C;boolean></a> <strong>Default:</strong> <code>true</code></li>
<li>Returns: <a href="#crypto_class_decipher" class="type">&#x3C;Decipher></a> for method chaining.</li>
</ul>
<p>When data has been encrypted without standard block padding, calling
<code>decipher.setAutoPadding(false)</code> will disable automatic padding to prevent
<a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> from checking for and removing padding.</p>
<p>Turning auto padding off will only work if the input data's length is a
multiple of the ciphers block size.</p>
<p>The <code>decipher.setAutoPadding()</code> method must be called before
<a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a>.</p>
<h3><code>decipher.update(data[, inputEncoding][, outputEncoding])</code><span><a class="mark" href="#crypto_decipher_update_data_inputencoding_outputencoding" id="crypto_decipher_update_data_inputencoding_outputencoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>data</code> string.</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Updates the decipher with <code>data</code>. If the <code>inputEncoding</code> argument is given,
the <code>data</code>
argument is a string using the specified encoding. If the <code>inputEncoding</code>
argument is not given, <code>data</code> must be a <a href="buffer.html"><code>Buffer</code></a>. If <code>data</code> is a
<a href="buffer.html"><code>Buffer</code></a> then <code>inputEncoding</code> is ignored.</p>
<p>The <code>outputEncoding</code> specifies the output format of the enciphered
data. If the <code>outputEncoding</code>
is specified, a string using the specified encoding is returned. If no
<code>outputEncoding</code> is provided, a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<p>The <code>decipher.update()</code> method can be called multiple times with new data until
<a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> is called. Calling <code>decipher.update()</code> after
<a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> will result in an error being thrown.</p>
<h2>Class: <code>DiffieHellman</code><span><a class="mark" href="#crypto_class_diffiehellman" id="crypto_class_diffiehellman">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<p>The <code>DiffieHellman</code> class is a utility for creating Diffie-Hellman key
exchanges.</p>
<p>Instances of the <code>DiffieHellman</code> class can be created using the
<a href="#crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding"><code>crypto.createDiffieHellman()</code></a> function.</p>
<pre><code class="language-js">const crypto = require('crypto');
const assert = require('assert');

// Generate Alice's keys...
const alice = crypto.createDiffieHellman(2048);
const aliceKey = alice.generateKeys();

// Generate Bob's keys...
const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
const bobKey = bob.generateKeys();

// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);

// OK
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
</code></pre>
<h3><code>diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of an <code>otherPublicKey</code> string.</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Computes the shared secret using <code>otherPublicKey</code> as the other
party's public key and returns the computed shared secret. The supplied
key is interpreted using the specified <code>inputEncoding</code>, and secret is
encoded using specified <code>outputEncoding</code>.
If the <code>inputEncoding</code> is not
provided, <code>otherPublicKey</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>,
<code>TypedArray</code>, or <code>DataView</code>.</p>
<p>If <code>outputEncoding</code> is given a string is returned; otherwise, a
<a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<h3><code>diffieHellman.generateKeys([encoding])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Generates private and public Diffie-Hellman key values, and returns
the public key in the specified <code>encoding</code>. This key should be
transferred to the other party.
If <code>encoding</code> is provided a string is returned; otherwise a
<a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<h3><code>diffieHellman.getGenerator([encoding])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the Diffie-Hellman generator in the specified <code>encoding</code>.
If <code>encoding</code> is provided a string is
returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<h3><code>diffieHellman.getPrime([encoding])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the Diffie-Hellman prime in the specified <code>encoding</code>.
If <code>encoding</code> is provided a string is
returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<h3><code>diffieHellman.getPrivateKey([encoding])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the Diffie-Hellman private key in the specified <code>encoding</code>.
If <code>encoding</code> is provided a
string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<h3><code>diffieHellman.getPublicKey([encoding])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the Diffie-Hellman public key in the specified <code>encoding</code>.
If <code>encoding</code> is provided a
string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<h3><code>diffieHellman.setPrivateKey(privateKey[, encoding])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>privateKey</code> string.</li>
</ul>
<p>Sets the Diffie-Hellman private key. If the <code>encoding</code> argument is provided,
<code>privateKey</code> is expected
to be a string. If no <code>encoding</code> is provided, <code>privateKey</code> is expected
to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p>
<h3><code>diffieHellman.setPublicKey(publicKey[, encoding])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>publicKey</code> string.</li>
</ul>
<p>Sets the Diffie-Hellman public key. If the <code>encoding</code> argument is provided,
<code>publicKey</code> is expected
to be a string. If no <code>encoding</code> is provided, <code>publicKey</code> is expected
to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p>
<h3><code>diffieHellman.verifyError</code><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: <code>DiffieHellmanGroup</code><span><a class="mark" href="#crypto_class_diffiehellmangroup" id="crypto_class_diffiehellmangroup">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div>
<p>The <code>DiffieHellmanGroup</code> class takes a well-known modp group as its argument but
otherwise works the same as <code>DiffieHellman</code>.</p>
<pre><code class="language-js">const name = 'modp1';
const dh = crypto.createDiffieHellmanGroup(name);
</code></pre>
<p><code>name</code> is taken from <a href="https://www.rfc-editor.org/rfc/rfc2412.txt">RFC 2412</a> (modp1 and 2) and <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a>:</p>
<pre><code class="language-console">$ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h
modp1  #  768 bits
modp2  # 1024 bits
modp5  # 1536 bits
modp14 # 2048 bits
modp15 # etc.
modp16
modp17
modp18
</code></pre>
<h2>Class: <code>ECDH</code><span><a class="mark" href="#crypto_class_ecdh" id="crypto_class_ecdh">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<p>The <code>ECDH</code> class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
key exchanges.</p>
<p>Instances of the <code>ECDH</code> class can be created using the
<a href="#crypto_crypto_createecdh_curvename"><code>crypto.createECDH()</code></a> function.</p>
<pre><code class="language-js">const crypto = require('crypto');
const assert = require('assert');

// Generate Alice's keys...
const alice = crypto.createECDH('secp521r1');
const aliceKey = alice.generateKeys();

// Generate Bob's keys...
const bob = crypto.createECDH('secp521r1');
const bobKey = bob.generateKeys();

// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);

assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
// OK
</code></pre>
<h3>Class Method: <code>ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])</code><span><a class="mark" href="#crypto_class_method_ecdh_convertkey_key_curve_inputencoding_outputencoding_format" id="crypto_class_method_ecdh_convertkey_key_curve_inputencoding_outputencoding_format">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>curve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>key</code> string.</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'uncompressed'</code></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Converts the EC Diffie-Hellman public key specified by <code>key</code> and <code>curve</code> to the
format specified by <code>format</code>. The <code>format</code> argument specifies point encoding
and can be <code>'compressed'</code>, <code>'uncompressed'</code> or <code>'hybrid'</code>. The supplied key is
interpreted using the specified <code>inputEncoding</code>, and the returned key is encoded
using the specified <code>outputEncoding</code>.</p>
<p>Use <a href="#crypto_crypto_getcurves"><code>crypto.getCurves()</code></a> to obtain a list of available curve names.
On recent OpenSSL releases, <code>openssl ecparam -list_curves</code> will also display
the name and description of each available elliptic curve.</p>
<p>If <code>format</code> is not specified the point will be returned in <code>'uncompressed'</code>
format.</p>
<p>If the <code>inputEncoding</code> is not provided, <code>key</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>,
<code>TypedArray</code>, or <code>DataView</code>.</p>
<p>Example (uncompressing a key):</p>
<pre><code class="language-js">const { createECDH, ECDH } = require('crypto');

const ecdh = createECDH('secp256k1');
ecdh.generateKeys();

const compressedKey = ecdh.getPublicKey('hex', 'compressed');

const uncompressedKey = ECDH.convertKey(compressedKey,
                                        'secp256k1',
                                        'hex',
                                        'hex',
                                        'uncompressed');

// The converted key and the uncompressed public key should be the same
console.log(uncompressedKey === ecdh.getPublicKey('hex'));
</code></pre>
<h3><code>ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code><span><a class="mark" href="#crypto_ecdh_computesecret_otherpublickey_inputencoding_outputencoding" id="crypto_ecdh_computesecret_otherpublickey_inputencoding_outputencoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Changed error format to better support invalid public key error</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code></p></td></tr>
<tr><td>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>otherPublicKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>otherPublicKey</code> string.</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Computes the shared secret using <code>otherPublicKey</code> as the other
party's public key and returns the computed shared secret. The supplied
key is interpreted using specified <code>inputEncoding</code>, and the returned secret
is encoded using the specified <code>outputEncoding</code>.
If the <code>inputEncoding</code> is not
provided, <code>otherPublicKey</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>.</p>
<p>If <code>outputEncoding</code> is given a string will be returned; otherwise a
<a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<p><code>ecdh.computeSecret</code> will throw an
<code>ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY</code> error when <code>otherPublicKey</code>
lies outside of the elliptic curve. Since <code>otherPublicKey</code> is
usually supplied from a remote user over an insecure network,
its recommended for developers to handle this exception accordingly.</p>
<h3><code>ecdh.generateKeys([encoding[, format]])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'uncompressed'</code></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Generates private and public EC Diffie-Hellman key values, and returns
the public key in the specified <code>format</code> and <code>encoding</code>. This key should be
transferred to the other party.</p>
<p>The <code>format</code> argument specifies point encoding and can be <code>'compressed'</code> or
<code>'uncompressed'</code>. If <code>format</code> is not specified, the point will be returned in
<code>'uncompressed'</code> format.</p>
<p>If <code>encoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a>
is returned.</p>
<h3><code>ecdh.getPrivateKey([encoding])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The EC Diffie-Hellman in the specified <code>encoding</code>.</li>
</ul>
<p>If <code>encoding</code> is specified, a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is
returned.</p>
<h3><code>ecdh.getPublicKey([encoding][, format])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'uncompressed'</code></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The EC Diffie-Hellman public key in the specified
<code>encoding</code> and <code>format</code>.</li>
</ul>
<p>The <code>format</code> argument specifies point encoding and can be <code>'compressed'</code> or
<code>'uncompressed'</code>. If <code>format</code> is not specified the point will be returned in
<code>'uncompressed'</code> format.</p>
<p>If <code>encoding</code> is specified, a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is
returned.</p>
<h3><code>ecdh.setPrivateKey(privateKey[, encoding])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>privateKey</code> string.</li>
</ul>
<p>Sets the EC Diffie-Hellman private key.
If <code>encoding</code> is provided, <code>privateKey</code> is expected
to be a string; otherwise <code>privateKey</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>,
<code>TypedArray</code>, or <code>DataView</code>.</p>
<p>If <code>privateKey</code> is not valid for the curve specified when the <code>ECDH</code> object was
created, an error is thrown. Upon setting the private key, the associated
public point (key) is also generated and set in the <code>ECDH</code> object.</p>
<h3><code>ecdh.setPublicKey(publicKey[, encoding])</code><span><a class="mark" href="#crypto_ecdh_setpublickey_publickey_encoding" id="crypto_ecdh_setpublickey_publickey_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span><span>Deprecated since: v5.2.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p>
<ul>
<li><code>publicKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>publicKey</code> string.</li>
</ul>
<p>Sets the EC Diffie-Hellman public key.
If <code>encoding</code> is provided <code>publicKey</code> is expected to
be a string; otherwise a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p>
<p>There is not normally a reason to call this method because <code>ECDH</code>
only requires a private key and the other party's public key to compute the
shared secret. Typically either <a href="#crypto_ecdh_generatekeys_encoding_format"><code>ecdh.generateKeys()</code></a> or
<a href="#crypto_ecdh_setprivatekey_privatekey_encoding"><code>ecdh.setPrivateKey()</code></a> will be called. The <a href="#crypto_ecdh_setprivatekey_privatekey_encoding"><code>ecdh.setPrivateKey()</code></a> method
attempts to generate the public point/key associated with the private key being
set.</p>
<p>Example (obtaining a shared secret):</p>
<pre><code class="language-js">const crypto = require('crypto');
const alice = crypto.createECDH('secp256k1');
const bob = crypto.createECDH('secp256k1');

// This is a shortcut way of specifying one of Alice's previous private
// keys. It would be unwise to use such a predictable private key in a real
// application.
alice.setPrivateKey(
  crypto.createHash('sha256').update('alice', 'utf8').digest()
);

// Bob uses a newly generated cryptographically strong
// pseudorandom key pair
bob.generateKeys();

const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

// aliceSecret and bobSecret should be the same shared secret value
console.log(aliceSecret === bobSecret);
</code></pre>
<h2>Class: <code>Hash</code><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>
<ul>
<li>Extends: <a href="#stream_class_stream_transform" class="type">&#x3C;stream.Transform></a></li>
</ul>
<p>The <code>Hash</code> class is a utility for creating hash digests of data. It can be
used in one of two ways:</p>
<ul>
<li>As a <a href="stream.html">stream</a> that is both readable and writable, where data is written
to produce a computed hash digest on the readable side, or</li>
<li>Using the <a href="#crypto_hash_update_data_inputencoding"><code>hash.update()</code></a> and <a href="#crypto_hash_digest_encoding"><code>hash.digest()</code></a> methods to produce the
computed hash.</li>
</ul>
<p>The <a href="#crypto_crypto_createhash_algorithm_options"><code>crypto.createHash()</code></a> method is used to create <code>Hash</code> instances. <code>Hash</code>
objects are not to be created directly using the <code>new</code> keyword.</p>
<p>Example: Using <code>Hash</code> objects as streams:</p>
<pre><code class="language-js">const crypto = require('crypto');
const hash = crypto.createHash('sha256');

hash.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = hash.read();
  if (data) {
    console.log(data.toString('hex'));
    // Prints:
    //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
  }
});

hash.write('some data to hash');
hash.end();
</code></pre>
<p>Example: Using <code>Hash</code> and piped streams:</p>
<pre><code class="language-js">const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('sha256');

const input = fs.createReadStream('test.js');
input.pipe(hash).pipe(process.stdout);
</code></pre>
<p>Example: Using the <a href="#crypto_hash_update_data_inputencoding"><code>hash.update()</code></a> and <a href="#crypto_hash_digest_encoding"><code>hash.digest()</code></a> methods:</p>
<pre><code class="language-js">const crypto = require('crypto');
const hash = crypto.createHash('sha256');

hash.update('some data to hash');
console.log(hash.digest('hex'));
// Prints:
//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
</code></pre>
<h3><code>hash.copy([options])</code><span><a class="mark" href="#crypto_hash_copy_options" id="crypto_hash_copy_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.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">&#x3C;Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#crypto_class_hash" class="type">&#x3C;Hash></a></li>
</ul>
<p>Creates a new <code>Hash</code> object that contains a deep copy of the internal state
of the current <code>Hash</code> object.</p>
<p>The optional <code>options</code> argument controls stream behavior. For XOF hash
functions such as <code>'shake256'</code>, the <code>outputLength</code> option can be used to
specify the desired output length in bytes.</p>
<p>An error is thrown when an attempt is made to copy the <code>Hash</code> object after
its <a href="#crypto_hash_digest_encoding"><code>hash.digest()</code></a> method has been called.</p>
<pre><code class="language-js">// Calculate a rolling hash.
const crypto = require('crypto');
const hash = crypto.createHash('sha256');

hash.update('one');
console.log(hash.copy().digest('hex'));

hash.update('two');
console.log(hash.copy().digest('hex'));

hash.update('three');
console.log(hash.copy().digest('hex'));

// Etc.
</code></pre>
<h3><code>hash.digest([encoding])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Calculates the digest of all of the data passed to be hashed (using the
<a href="#crypto_hash_update_data_inputencoding"><code>hash.update()</code></a> method).
If <code>encoding</code> is provided a string will be returned; otherwise
a <a href="buffer.html"><code>Buffer</code></a> is returned.</p>
<p>The <code>Hash</code> object can not be used again after <code>hash.digest()</code> method has been
called. Multiple calls will cause an error to be thrown.</p>
<h3><code>hash.update(data[, inputEncoding])</code><span><a class="mark" href="#crypto_hash_update_data_inputencoding" id="crypto_hash_update_data_inputencoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>data</code> string.</li>
</ul>
<p>Updates the hash content with the given <code>data</code>, the encoding of which
is given in <code>inputEncoding</code>.
If <code>encoding</code> is not provided, and the <code>data</code> is a string, an
encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
<h2>Class: <code>Hmac</code><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>
<ul>
<li>Extends: <a href="#stream_class_stream_transform" class="type">&#x3C;stream.Transform></a></li>
</ul>
<p>The <code>Hmac</code> class is a utility for creating cryptographic HMAC digests. It can
be used in one of two ways:</p>
<ul>
<li>As a <a href="stream.html">stream</a> that is both readable and writable, where data is written
to produce a computed HMAC digest on the readable side, or</li>
<li>Using the <a href="#crypto_hmac_update_data_inputencoding"><code>hmac.update()</code></a> and <a href="#crypto_hmac_digest_encoding"><code>hmac.digest()</code></a> methods to produce the
computed HMAC digest.</li>
</ul>
<p>The <a href="#crypto_crypto_createhmac_algorithm_key_options"><code>crypto.createHmac()</code></a> method is used to create <code>Hmac</code> instances. <code>Hmac</code>
objects are not to be created directly using the <code>new</code> keyword.</p>
<p>Example: Using <code>Hmac</code> objects as streams:</p>
<pre><code class="language-js">const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret');

hmac.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = hmac.read();
  if (data) {
    console.log(data.toString('hex'));
    // Prints:
    //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
  }
});

hmac.write('some data to hash');
hmac.end();
</code></pre>
<p>Example: Using <code>Hmac</code> and piped streams:</p>
<pre><code class="language-js">const crypto = require('crypto');
const fs = require('fs');
const hmac = crypto.createHmac('sha256', 'a secret');

const input = fs.createReadStream('test.js');
input.pipe(hmac).pipe(process.stdout);
</code></pre>
<p>Example: Using the <a href="#crypto_hmac_update_data_inputencoding"><code>hmac.update()</code></a> and <a href="#crypto_hmac_digest_encoding"><code>hmac.digest()</code></a> methods:</p>
<pre><code class="language-js">const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret');

hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
</code></pre>
<h3><code>hmac.digest([encoding])</code><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">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Calculates the HMAC digest of all of the data passed using <a href="#crypto_hmac_update_data_inputencoding"><code>hmac.update()</code></a>.
If <code>encoding</code> is
provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a> is returned;</p>
<p>The <code>Hmac</code> object can not be used again after <code>hmac.digest()</code> has been
called. Multiple calls to <code>hmac.digest()</code> will result in an error being thrown.</p>
<h3><code>hmac.update(data[, inputEncoding])</code><span><a class="mark" href="#crypto_hmac_update_data_inputencoding" id="crypto_hmac_update_data_inputencoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>data</code> string.</li>
</ul>
<p>Updates the <code>Hmac</code> content with the given <code>data</code>, the encoding of which
is given in <code>inputEncoding</code>.
If <code>encoding</code> is not provided, and the <code>data</code> is a string, an
encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
<h2>Class: <code>KeyObject</code><span><a class="mark" href="#crypto_class_keyobject" id="crypto_class_keyobject">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.13.0</td>
<td><p>This class is now exported.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p><span>Added in: v11.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Node.js uses a <code>KeyObject</code> class to represent a symmetric or asymmetric key,
and each kind of key exposes different functions. The
<a href="#crypto_crypto_createsecretkey_key"><code>crypto.createSecretKey()</code></a>, <a href="#crypto_crypto_createpublickey_key"><code>crypto.createPublicKey()</code></a> and
<a href="#crypto_crypto_createprivatekey_key"><code>crypto.createPrivateKey()</code></a> methods are used to create <code>KeyObject</code>
instances. <code>KeyObject</code> objects are not to be created directly using the <code>new</code>
keyword.</p>
<p>Most applications should consider using the new <code>KeyObject</code> API instead of
passing keys as strings or <code>Buffer</code>s due to improved security features.</p>
<h3><code>keyObject.asymmetricKeyType</code><span><a class="mark" href="#crypto_keyobject_asymmetrickeytype" id="crypto_keyobject_asymmetrickeytype">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>Added support for <code>'dh'</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Added support for <code>'rsa-pss'</code></p></td></tr>
<tr><td>v12.0.0</td>
<td><p>This property now returns <code>undefined</code> for KeyObject instances of unrecognized type instead of aborting.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Added support for <code>'x25519'</code> and <code>'x448'</code></p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Added support for <code>'ed25519'</code> and <code>'ed448'</code>.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p><span>Added in: v11.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>For asymmetric keys, this property represents the type of the key. Supported key
types are:</p>
<ul>
<li><code>'rsa'</code> (OID 1.2.840.113549.1.1.1)</li>
<li><code>'rsa-pss'</code> (OID 1.2.840.113549.1.1.10)</li>
<li><code>'dsa'</code> (OID 1.2.840.10040.4.1)</li>
<li><code>'ec'</code> (OID 1.2.840.10045.2.1)</li>
<li><code>'x25519'</code> (OID 1.3.101.110)</li>
<li><code>'x448'</code> (OID 1.3.101.111)</li>
<li><code>'ed25519'</code> (OID 1.3.101.112)</li>
<li><code>'ed448'</code> (OID 1.3.101.113)</li>
<li><code>'dh'</code> (OID 1.2.840.113549.1.3.1)</li>
</ul>
<p>This property is <code>undefined</code> for unrecognized <code>KeyObject</code> types and symmetric
keys.</p>
<h3><code>keyObject.export([options])</code><span><a class="mark" href="#crypto_keyobject_export_options" id="crypto_keyobject_export_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.6.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">&#x3C;Object></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>For symmetric keys, this function allocates a <code>Buffer</code> containing the key
material and ignores any options.</p>
<p>For asymmetric keys, the <code>options</code> parameter is used to determine the export
format.</p>
<p>For public keys, the following encoding options can be used:</p>
<ul>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be one of <code>'pkcs1'</code> (RSA only) or <code>'spki'</code>.</li>
<li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'pem'</code> or <code>'der'</code>.</li>
</ul>
<p>For private keys, the following encoding options can be used:</p>
<ul>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be one of <code>'pkcs1'</code> (RSA only), <code>'pkcs8'</code> or
<code>'sec1'</code> (EC only).</li>
<li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'pem'</code> or <code>'der'</code>.</li>
<li><code>cipher</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If specified, the private key will be encrypted with
 the given <code>cipher</code> and <code>passphrase</code> using PKCS#5 v2.0 password based
encryption.</li>
<li><code>passphrase</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The passphrase to use for encryption, see
<code>cipher</code>.</li>
</ul>
<p>When PEM encoding was selected, the result will be a string, otherwise it will
be a buffer containing the data encoded as DER.</p>
<p>PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
the <code>cipher</code> and <code>format</code> options. The PKCS#8 <code>type</code> can be used with any
<code>format</code> to encrypt any key algorithm (RSA, EC, or DH) by specifying a
<code>cipher</code>. PKCS#1 and SEC1 can only be encrypted by specifying a <code>cipher</code>
when the PEM <code>format</code> is used. For maximum compatibility, use PKCS#8 for
encrypted private keys. Since PKCS#8 defines its own
encryption mechanism, PEM-level encryption is not supported when encrypting
a PKCS#8 key. See <a href="https://www.rfc-editor.org/rfc/rfc5208.txt">RFC 5208</a> for PKCS#8 encryption and <a href="https://www.rfc-editor.org/rfc/rfc1421.txt">RFC 1421</a> for
PKCS#1 and SEC1 encryption.</p>
<h3><code>keyObject.symmetricKeySize</code><span><a class="mark" href="#crypto_keyobject_symmetrickeysize" id="crypto_keyobject_symmetrickeysize">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.6.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>For secret keys, this property represents the size of the key in bytes. This
property is <code>undefined</code> for asymmetric keys.</p>
<h3><code>keyObject.type</code><span><a class="mark" href="#crypto_keyobject_type" id="crypto_keyobject_type">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.6.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Depending on the type of this <code>KeyObject</code>, this property is either
<code>'secret'</code> for secret (symmetric) keys, <code>'public'</code> for public (asymmetric) keys
or <code>'private'</code> for private (asymmetric) keys.</p>
<h2>Class: <code>Sign</code><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>
<ul>
<li>Extends: <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a></li>
</ul>
<p>The <code>Sign</code> class is a utility for generating signatures. It can be used in one
of two ways:</p>
<ul>
<li>As a writable <a href="stream.html">stream</a>, where data to be signed is written and the
<a href="#crypto_sign_sign_privatekey_outputencoding"><code>sign.sign()</code></a> method is used to generate and return the signature, or</li>
<li>Using the <a href="#crypto_sign_update_data_inputencoding"><code>sign.update()</code></a> and <a href="#crypto_sign_sign_privatekey_outputencoding"><code>sign.sign()</code></a> methods to produce the
signature.</li>
</ul>
<p>The <a href="#crypto_crypto_createsign_algorithm_options"><code>crypto.createSign()</code></a> method is used to create <code>Sign</code> instances. The
argument is the string name of the hash function to use. <code>Sign</code> objects are not
to be created directly using the <code>new</code> keyword.</p>
<p>Example: Using <code>Sign</code> and <a href="#crypto_class_verify"><code>Verify</code></a> objects as streams:</p>
<pre><code class="language-js">const crypto = require('crypto');

const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
  namedCurve: 'sect239k1'
});

const sign = crypto.createSign('SHA256');
sign.write('some data to sign');
sign.end();
const signature = sign.sign(privateKey, 'hex');

const verify = crypto.createVerify('SHA256');
verify.write('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature, 'hex'));
// Prints: true
</code></pre>
<p>Example: Using the <a href="#crypto_sign_update_data_inputencoding"><code>sign.update()</code></a> and <a href="#crypto_verify_update_data_inputencoding"><code>verify.update()</code></a> methods:</p>
<pre><code class="language-js">const crypto = require('crypto');

const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

const sign = crypto.createSign('SHA256');
sign.update('some data to sign');
sign.end();
const signature = sign.sign(privateKey);

const verify = crypto.createVerify('SHA256');
verify.update('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature));
// Prints: true
</code></pre>
<h3><code>sign.sign(privateKey[, outputEncoding])</code><span><a class="mark" href="#crypto_sign_sign_privatekey_outputencoding" id="crypto_sign_sign_privatekey_outputencoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>This function now supports RSA-PSS keys.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>This function now supports key objects.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Support for RSASSA-PSS and additional options was added.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>privateKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></p>
<ul>
<li><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
</li>
<li><code>outputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Calculates the signature on all the data passed through using either
<a href="#crypto_sign_update_data_inputencoding"><code>sign.update()</code></a> or <a href="#stream_writable_write_chunk_encoding_callback"><code>sign.write()</code></a>.</p>
<p>If <code>privateKey</code> is not a <a href="#crypto_class_keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>privateKey</code> had been passed to <a href="#crypto_crypto_createprivatekey_key"><code>crypto.createPrivateKey()</code></a>. If it is an
object, the following additional properties can be passed:</p>
<ul>
<li>
<p><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> For DSA and ECDSA, this option specifies the
format of the generated signature. It can be one of the following:</p>
<ul>
<li><code>'der'</code> (default): DER-encoded ASN.1 signature structure encoding <code>(r, s)</code>.</li>
<li><code>'ieee-p1363'</code>: Signature format <code>r || s</code> as proposed in IEEE-P1363.</li>
</ul>
</li>
<li>
<p><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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><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>, unless
an MGF1 hash function has been specified as part of the key in compliance with
section 3.3 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>.</p>
</li>
<li>
<p><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Salt length for when padding is
<code>RSA_PKCS1_PSS_PADDING</code>. The special value
<code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest
size, <code>crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN</code> (default) sets it to the
maximum permissible value.</p>
</li>
</ul>
<p>If <code>outputEncoding</code> is provided a string is returned; otherwise a <a href="buffer.html"><code>Buffer</code></a>
is returned.</p>
<p>The <code>Sign</code> object can not be again used after <code>sign.sign()</code> method has been
called. Multiple calls to <code>sign.sign()</code> will result in an error being thrown.</p>
<h3><code>sign.update(data[, inputEncoding])</code><span><a class="mark" href="#crypto_sign_update_data_inputencoding" id="crypto_sign_update_data_inputencoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>data</code> string.</li>
</ul>
<p>Updates the <code>Sign</code> content with the given <code>data</code>, the encoding of which
is given in <code>inputEncoding</code>.
If <code>encoding</code> is not provided, and the <code>data</code> is a string, an
encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
<h2>Class: <code>Verify</code><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>
<ul>
<li>Extends: <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a></li>
</ul>
<p>The <code>Verify</code> class is a utility for verifying signatures. It can be used in one
of two ways:</p>
<ul>
<li>As a writable <a href="stream.html">stream</a> where written data is used to validate against the
supplied signature, or</li>
<li>Using the <a href="#crypto_verify_update_data_inputencoding"><code>verify.update()</code></a> and <a href="#crypto_verify_verify_object_signature_signatureencoding"><code>verify.verify()</code></a> methods to verify
the signature.</li>
</ul>
<p>The <a href="#crypto_crypto_createverify_algorithm_options"><code>crypto.createVerify()</code></a> method is used to create <code>Verify</code> instances.
<code>Verify</code> objects are not to be created directly using the <code>new</code> keyword.</p>
<p>See <a href="#crypto_class_sign"><code>Sign</code></a> for examples.</p>
<h3><code>verify.update(data[, inputEncoding])</code><span><a class="mark" href="#crypto_verify_update_data_inputencoding" id="crypto_verify_update_data_inputencoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The default <code>inputEncoding</code> changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>inputEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>data</code> string.</li>
</ul>
<p>Updates the <code>Verify</code> content with the given <code>data</code>, the encoding of which
is given in <code>inputEncoding</code>.
If <code>inputEncoding</code> is not provided, and the <code>data</code> is a string, an
encoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or
<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
<h3><code>verify.verify(object, signature[, signatureEncoding])</code><span><a class="mark" href="#crypto_verify_verify_object_signature_signatureencoding" id="crypto_verify_verify_object_signature_signatureencoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>This function now supports RSA-PSS keys.</p></td></tr>
<tr><td>v11.7.0</td>
<td><p>The key can now be a private key.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Support for RSASSA-PSS and additional options was added.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></p>
<ul>
<li><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
</li>
<li><code>signature</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>signatureEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>signature</code> string.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> or <code>false</code> depending on the validity of the
signature for the data and public key.</li>
</ul>
<p>Verifies the provided data using the given <code>object</code> and <code>signature</code>.</p>
<p>If <code>object</code> is not a <a href="#crypto_class_keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>object</code> had been passed to <a href="#crypto_crypto_createpublickey_key"><code>crypto.createPublicKey()</code></a>. If it is an
object, the following additional properties can be passed:</p>
<ul>
<li>
<p><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> For DSA and ECDSA, this option specifies the
format of the generated signature. It can be one of the following:</p>
<ul>
<li><code>'der'</code> (default): DER-encoded ASN.1 signature structure encoding <code>(r, s)</code>.</li>
<li><code>'ieee-p1363'</code>: Signature format <code>r || s</code> as proposed in IEEE-P1363.</li>
</ul>
</li>
<li>
<p><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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><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>, unless
an MGF1 hash function has been specified as part of the key in compliance with
section 3.3 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>.</p>
</li>
<li>
<p><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Salt length for when padding is
<code>RSA_PKCS1_PSS_PADDING</code>. The special value
<code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest
size, <code>crypto.constants.RSA_PSS_SALTLEN_AUTO</code> (default) causes it to be
determined automatically.</p>
</li>
</ul>
<p>The <code>signature</code> argument is the previously calculated signature for the data, in
the <code>signatureEncoding</code>.
If a <code>signatureEncoding</code> is specified, the <code>signature</code> is expected to be a
string; otherwise <code>signature</code> is expected to be a <a href="buffer.html"><code>Buffer</code></a>,
<code>TypedArray</code>, or <code>DataView</code>.</p>
<p>The <code>verify</code> object can not be used again after <code>verify.verify()</code> has been
called. Multiple calls to <code>verify.verify()</code> will result in an error being
thrown.</p>
<p>Because public keys can be derived from private keys, a private key may
be passed instead of a public key.</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><code>crypto.constants</code><span><a class="mark" href="#crypto_crypto_constants" id="crypto_crypto_constants">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.3.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object containing commonly used constants for crypto and
security related operations. The specific constants currently defined are
described in <a href="#crypto_crypto_constants_1">Crypto constants</a>.</li>
</ul>
<h3><code>crypto.DEFAULT_ENCODING</code><span><a class="mark" href="#crypto_crypto_default_encoding" id="crypto_crypto_default_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span><span>Deprecated since: v10.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p>
<p>The default encoding to use for functions that can take either strings
or <a href="buffer.html">buffers</a>. The default value is <code>'buffer'</code>, which makes methods
default to <a href="buffer.html"><code>Buffer</code></a> objects.</p>
<p>The <code>crypto.DEFAULT_ENCODING</code> mechanism is provided for backwards compatibility
with legacy programs that expect <code>'latin1'</code> to be the default encoding.</p>
<p>New applications should expect the default to be <code>'buffer'</code>.</p>
<p>This property is deprecated.</p>
<h3><code>crypto.fips</code><span><a class="mark" href="#crypto_crypto_fips" id="crypto_crypto_fips">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.0.0</span><span>Deprecated since: v10.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p>
<p>Property for checking and controlling whether a FIPS compliant crypto provider
is currently in use. Setting to true requires a FIPS build of Node.js.</p>
<p>This property is deprecated. Please use <code>crypto.setFips()</code> and
<code>crypto.getFips()</code> instead.</p>
<h3><code>crypto.createCipher(algorithm, password[, options])</code><span><a class="mark" href="#crypto_crypto_createcipher_algorithm_password_options" id="crypto_crypto_createcipher_algorithm_password_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>Ciphers in OCB mode are now supported.</p></td></tr>
<tr><td>v10.2.0</td>
<td><p>The <code>authTagLength</code> option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Deprecated since: v10.0.0</span></p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#crypto_crypto_createcipheriv_algorithm_key_iv_options"><code>crypto.createCipheriv()</code></a> instead.</div><p></p>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#crypto_class_cipher" class="type">&#x3C;Cipher></a></li>
</ul>
<p>Creates and returns a <code>Cipher</code> object that uses the given <code>algorithm</code> and
<code>password</code>.</p>
<p>The <code>options</code> argument controls stream behavior and is optional except when a
cipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#crypto_ccm_mode">CCM mode</a>. In GCM mode, the <code>authTagLength</code>
option is not required but can be used to set the length of the authentication
tag that will be returned by <code>getAuthTag()</code> and defaults to 16 bytes.</p>
<p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On
recent OpenSSL releases, <code>openssl list -cipher-algorithms</code>
(<code>openssl list-cipher-algorithms</code> for older versions of OpenSSL) will
display the available cipher algorithms.</p>
<p>The <code>password</code> is used to derive the cipher key and initialization vector (IV).
The value must be either a <code>'latin1'</code> encoded string, a <a href="buffer.html"><code>Buffer</code></a>, a
<code>TypedArray</code>, or a <code>DataView</code>.</p>
<p>The implementation of <code>crypto.createCipher()</code> derives keys using the OpenSSL
function <a href="https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> with the digest algorithm set to MD5, one
iteration, and no salt. The lack of salt allows dictionary attacks as the same
password always creates the same key. The low iteration count and
non-cryptographically secure hash algorithm allow passwords to be tested very
rapidly.</p>
<p>In line with OpenSSL's recommendation to use a more modern algorithm instead of
<a href="https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on
their own using <a href="#crypto_crypto_scrypt_password_salt_keylen_options_callback"><code>crypto.scrypt()</code></a> and to use <a href="#crypto_crypto_createcipheriv_algorithm_key_iv_options"><code>crypto.createCipheriv()</code></a>
to create the <code>Cipher</code> object. Users should not use ciphers with counter mode
(e.g. CTR, GCM, or CCM) in <code>crypto.createCipher()</code>. A warning is emitted when
they are used in order to avoid the risk of IV reuse that causes
vulnerabilities. For the case when IV is reused in GCM, see <a href="https://github.com/nonce-disrespect/nonce-disrespect">Nonce-Disrespecting
Adversaries</a> for details.</p>
<h3><code>crypto.createCipheriv(algorithm, key, iv[, options])</code><span><a class="mark" href="#crypto_crypto_createcipheriv_algorithm_key_iv_options" id="crypto_crypto_createcipheriv_algorithm_key_iv_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.6.0</td>
<td><p>The <code>key</code> argument can now be a <code>KeyObject</code>.</p></td></tr>
<tr><td>v11.2.0</td>
<td><p>The cipher <code>chacha20-poly1305</code> is now supported.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>Ciphers in OCB mode are now supported.</p></td></tr>
<tr><td>v10.2.0</td>
<td><p>The <code>authTagLength</code> option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>iv</code> parameter may now be <code>null</code> for ciphers which do not need an initialization vector.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
<li><code>iv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#crypto_class_cipher" class="type">&#x3C;Cipher></a></li>
</ul>
<p>Creates and returns a <code>Cipher</code> object, with the given <code>algorithm</code>, <code>key</code> and
initialization vector (<code>iv</code>).</p>
<p>The <code>options</code> argument controls stream behavior and is optional except when a
cipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#crypto_ccm_mode">CCM mode</a>. In GCM mode, the <code>authTagLength</code>
option is not required but can be used to set the length of the authentication
tag that will be returned by <code>getAuthTag()</code> and defaults to 16 bytes.</p>
<p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On
recent OpenSSL releases, <code>openssl list -cipher-algorithms</code>
(<code>openssl list-cipher-algorithms</code> for older versions of OpenSSL) will
display the available cipher algorithms.</p>
<p>The <code>key</code> is the raw key used by the <code>algorithm</code> and <code>iv</code> is an
<a href="https://en.wikipedia.org/wiki/Initialization_vector">initialization vector</a>. Both arguments must be <code>'utf8'</code> encoded strings,
<a href="buffer.html">Buffers</a>, <code>TypedArray</code>, or <code>DataView</code>s. The <code>key</code> may optionally be
a <a href="#crypto_class_keyobject"><code>KeyObject</code></a> of type <code>secret</code>. If the cipher does not need
an initialization vector, <code>iv</code> may be <code>null</code>.</p>
<p>Initialization vectors should be unpredictable and unique; ideally, they will be
cryptographically random. They do not have to be secret: IVs are typically just
added to ciphertext messages unencrypted. It may sound contradictory that
something has to be unpredictable and unique, but does not have to be secret;
remember that an attacker must not be able to predict ahead of time what a
given IV will be.</p>
<h3><code>crypto.createDecipher(algorithm, password[, options])</code><span><a class="mark" href="#crypto_crypto_createdecipher_algorithm_password_options" id="crypto_crypto_createdecipher_algorithm_password_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>Ciphers in OCB mode are now supported.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Deprecated since: v10.0.0</span></p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options"><code>crypto.createDecipheriv()</code></a> instead.</div><p></p>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#crypto_class_decipher" class="type">&#x3C;Decipher></a></li>
</ul>
<p>Creates and returns a <code>Decipher</code> object that uses the given <code>algorithm</code> and
<code>password</code> (key).</p>
<p>The <code>options</code> argument controls stream behavior and is optional except when a
cipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#crypto_ccm_mode">CCM mode</a>.</p>
<p>The implementation of <code>crypto.createDecipher()</code> derives keys using the OpenSSL
function <a href="https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> with the digest algorithm set to MD5, one
iteration, and no salt. The lack of salt allows dictionary attacks as the same
password always creates the same key. The low iteration count and
non-cryptographically secure hash algorithm allow passwords to be tested very
rapidly.</p>
<p>In line with OpenSSL's recommendation to use a more modern algorithm instead of
<a href="https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on
their own using <a href="#crypto_crypto_scrypt_password_salt_keylen_options_callback"><code>crypto.scrypt()</code></a> and to use <a href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options"><code>crypto.createDecipheriv()</code></a>
to create the <code>Decipher</code> object.</p>
<h3><code>crypto.createDecipheriv(algorithm, key, iv[, options])</code><span><a class="mark" href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options" id="crypto_crypto_createdecipheriv_algorithm_key_iv_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.6.0</td>
<td><p>The <code>key</code> argument can now be a <code>KeyObject</code>.</p></td></tr>
<tr><td>v11.2.0</td>
<td><p>The cipher <code>chacha20-poly1305</code> is now supported.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p>Ciphers in OCB mode are now supported.</p></td></tr>
<tr><td>v10.2.0</td>
<td><p>The <code>authTagLength</code> option can now be used to restrict accepted GCM authentication tag lengths.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>iv</code> parameter may now be <code>null</code> for ciphers which do not need an initialization vector.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
<li><code>iv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#crypto_class_decipher" class="type">&#x3C;Decipher></a></li>
</ul>
<p>Creates and returns a <code>Decipher</code> object that uses the given <code>algorithm</code>, <code>key</code>
and initialization vector (<code>iv</code>).</p>
<p>The <code>options</code> argument controls stream behavior and is optional except when a
cipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#crypto_ccm_mode">CCM mode</a>. In GCM mode, the <code>authTagLength</code>
option is not required but can be used to restrict accepted authentication tags
to those with the specified length.</p>
<p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On
recent OpenSSL releases, <code>openssl list -cipher-algorithms</code>
(<code>openssl list-cipher-algorithms</code> for older versions of OpenSSL) will
display the available cipher algorithms.</p>
<p>The <code>key</code> is the raw key used by the <code>algorithm</code> and <code>iv</code> is an
<a href="https://en.wikipedia.org/wiki/Initialization_vector">initialization vector</a>. Both arguments must be <code>'utf8'</code> encoded strings,
<a href="buffer.html">Buffers</a>, <code>TypedArray</code>, or <code>DataView</code>s. The <code>key</code> may optionally be
a <a href="#crypto_class_keyobject"><code>KeyObject</code></a> of type <code>secret</code>. If the cipher does not need
an initialization vector, <code>iv</code> may be <code>null</code>.</p>
<p>Initialization vectors should be unpredictable and unique; ideally, they will be
cryptographically random. They do not have to be secret: IVs are typically just
added to ciphertext messages unencrypted. It may sound contradictory that
something has to be unpredictable and unique, but does not have to be secret;
remember that an attacker must not be able to predict ahead of time what a given
IV will be.</p>
<h3><code>crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])</code><span><a class="mark" href="#crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding" id="crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>prime</code> argument can be any <code>TypedArray</code> or <code>DataView</code> now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>prime</code> argument can be a <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The default for the encoding parameters changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>prime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>primeEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>prime</code> string.</li>
<li><code>generator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> <strong>Default:</strong>
<code>2</code></li>
<li><code>generatorEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The <a href="#buffer_buffers_and_character_encodings">encoding</a> of the <code>generator</code> string.</li>
<li>Returns: <a href="#crypto_class_diffiehellman" class="type">&#x3C;DiffieHellman></a></li>
</ul>
<p>Creates a <code>DiffieHellman</code> key exchange object using the supplied <code>prime</code> and an
optional specific <code>generator</code>.</p>
<p>The <code>generator</code> argument can be a number, string, or <a href="buffer.html"><code>Buffer</code></a>. If
<code>generator</code> is not specified, the value <code>2</code> is used.</p>
<p>If <code>primeEncoding</code> is specified, <code>prime</code> is expected to be a string; otherwise
a <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p>
<p>If <code>generatorEncoding</code> is specified, <code>generator</code> is expected to be a string;
otherwise a number, <a href="buffer.html"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p>
<h3><code>crypto.createDiffieHellman(primeLength[, generator])</code><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">&#x3C;number></a></li>
<li><code>generator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <strong>Default:</strong> <code>2</code></li>
<li>Returns: <a href="#crypto_class_diffiehellman" class="type">&#x3C;DiffieHellman></a></li>
</ul>
<p>Creates a <code>DiffieHellman</code> key exchange object and generates a prime of
<code>primeLength</code> bits using an optional specific numeric <code>generator</code>.
If <code>generator</code> is not specified, the value <code>2</code> is used.</p>
<h3><code>crypto.createDiffieHellmanGroup(name)</code><span><a class="mark" href="#crypto_crypto_creatediffiehellmangroup_name" id="crypto_crypto_creatediffiehellmangroup_name">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="#crypto_class_diffiehellmangroup" class="type">&#x3C;DiffieHellmanGroup></a></li>
</ul>
<p>An alias for <a href="#crypto_crypto_getdiffiehellman_groupname"><code>crypto.getDiffieHellman()</code></a></p>
<h3><code>crypto.createECDH(curveName)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="#crypto_class_ecdh" class="type">&#x3C;ECDH></a></li>
</ul>
<p>Creates an Elliptic Curve Diffie-Hellman (<code>ECDH</code>) key exchange object using a
predefined curve specified by the <code>curveName</code> string. Use
<a href="#crypto_crypto_getcurves"><code>crypto.getCurves()</code></a> to obtain a list of available curve names. On recent
OpenSSL releases, <code>openssl ecparam -list_curves</code> will also display the name
and description of each available elliptic curve.</p>
<h3><code>crypto.createHash(algorithm[, options])</code><span><a class="mark" href="#crypto_crypto_createhash_algorithm_options" id="crypto_crypto_createhash_algorithm_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.8.0</td>
<td><p>The <code>outputLength</code> option was added for XOF hash functions.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#crypto_class_hash" class="type">&#x3C;Hash></a></li>
</ul>
<p>Creates and returns a <code>Hash</code> object that can be used to generate hash digests
using the given <code>algorithm</code>. Optional <code>options</code> argument controls stream
behavior. For XOF hash functions such as <code>'shake256'</code>, the <code>outputLength</code> option
can be used to specify the desired output length in bytes.</p>
<p>The <code>algorithm</code> is dependent on the available algorithms supported by the
version of OpenSSL on the platform. Examples are <code>'sha256'</code>, <code>'sha512'</code>, etc.
On recent releases of OpenSSL, <code>openssl list -digest-algorithms</code>
(<code>openssl list-message-digest-algorithms</code> for older versions of OpenSSL) will
display the available digest algorithms.</p>
<p>Example: generating the sha256 sum of a file</p>
<pre><code class="language-js">const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');

const hash = crypto.createHash('sha256');

const input = fs.createReadStream(filename);
input.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = input.read();
  if (data)
    hash.update(data);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});
</code></pre>
<h3><code>crypto.createHmac(algorithm, key[, options])</code><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">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.6.0</td>
<td><p>The <code>key</code> argument can now be a <code>KeyObject</code>.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> <a href="#stream_new_stream_transform_options"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#crypto_class_hmac" class="type">&#x3C;Hmac></a></li>
</ul>
<p>Creates and returns an <code>Hmac</code> object that uses the given <code>algorithm</code> and <code>key</code>.
Optional <code>options</code> argument controls stream behavior.</p>
<p>The <code>algorithm</code> is dependent on the available algorithms supported by the
version of OpenSSL on the platform. Examples are <code>'sha256'</code>, <code>'sha512'</code>, etc.
On recent releases of OpenSSL, <code>openssl list -digest-algorithms</code>
(<code>openssl list-message-digest-algorithms</code> for older versions of OpenSSL) will
display the available digest algorithms.</p>
<p>The <code>key</code> is the HMAC key used to generate the cryptographic HMAC hash. If it is
a <a href="#crypto_class_keyobject"><code>KeyObject</code></a>, its type must be <code>secret</code>.</p>
<p>Example: generating the sha256 HMAC of a file</p>
<pre><code class="language-js">const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');

const hmac = crypto.createHmac('sha256', 'a secret');

const input = fs.createReadStream(filename);
input.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = input.read();
  if (data)
    hmac.update(data);
  else {
    console.log(`${hmac.digest('hex')} ${filename}`);
  }
});
</code></pre>
<h3><code>crypto.createPrivateKey(key)</code><span><a class="mark" href="#crypto_crypto_createprivatekey_key" id="crypto_crypto_createprivatekey_key">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.6.0</span>
</div>
<ul>
<li>
<p><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></p>
<ul>
<li><code>key</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The key material, either in PEM or DER format.</li>
<li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'pem'</code> or <code>'der'</code>. <strong>Default:</strong> <code>'pem'</code>.</li>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'pkcs1'</code>, <code>'pkcs8'</code> or <code>'sec1'</code>. This option is
required only if the <code>format</code> is <code>'der'</code> and ignored if it is <code>'pem'</code>.</li>
<li><code>passphrase</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The passphrase to use for decryption.</li>
</ul>
</li>
<li>Returns: <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
<p>Creates and returns a new key object containing a private key. If <code>key</code> is a
string or <code>Buffer</code>, <code>format</code> is assumed to be <code>'pem'</code>; otherwise, <code>key</code>
must be an object with the properties described above.</p>
<p>If the private key is encrypted, a <code>passphrase</code> must be specified. The length
of the passphrase is limited to 1024 bytes.</p>
<h3><code>crypto.createPublicKey(key)</code><span><a class="mark" href="#crypto_crypto_createpublickey_key" id="crypto_crypto_createpublickey_key">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.13.0</td>
<td><p>The <code>key</code> argument can now be a <code>KeyObject</code> with type <code>private</code>.</p></td></tr>
<tr><td>v11.7.0</td>
<td><p>The <code>key</code> argument can now be a private key.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p><span>Added in: v11.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></p>
<ul>
<li><code>key</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li><code>format</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'pem'</code> or <code>'der'</code>. <strong>Default:</strong> <code>'pem'</code>.</li>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'pkcs1'</code> or <code>'spki'</code>. This option is required
only if the <code>format</code> is <code>'der'</code>.</li>
</ul>
</li>
<li>Returns: <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
<p>Creates and returns a new key object containing a public key. If <code>key</code> is a
string or <code>Buffer</code>, <code>format</code> is assumed to be <code>'pem'</code>; if <code>key</code> is a <code>KeyObject</code>
with type <code>'private'</code>, the public key is derived from the given private key;
otherwise, <code>key</code> must be an object with the properties described above.</p>
<p>If the format is <code>'pem'</code>, the <code>'key'</code> may also be an X.509 certificate.</p>
<p>Because public keys can be derived from private keys, a private key may be
passed instead of a public key. In that case, this function behaves as if
<a href="#crypto_crypto_createprivatekey_key"><code>crypto.createPrivateKey()</code></a> had been called, except that the type of the
returned <code>KeyObject</code> will be <code>'public'</code> and that the private key cannot be
extracted from the returned <code>KeyObject</code>. Similarly, if a <code>KeyObject</code> with type
<code>'private'</code> is given, a new <code>KeyObject</code> with type <code>'public'</code> will be returned
and it will be impossible to extract the private key from the returned object.</p>
<h3><code>crypto.createSecretKey(key)</code><span><a class="mark" href="#crypto_crypto_createsecretkey_key" id="crypto_crypto_createsecretkey_key">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.6.0</span>
</div>
<ul>
<li><code>key</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li>Returns: <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
<p>Creates and returns a new key object containing a secret key for symmetric
encryption or <code>Hmac</code>.</p>
<h3><code>crypto.createSign(algorithm[, options])</code><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">&#x3C;string></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> <a href="#stream_constructor_new_stream_writable_options"><code>stream.Writable</code> options</a></li>
<li>Returns: <a href="#crypto_class_sign" class="type">&#x3C;Sign></a></li>
</ul>
<p>Creates and returns a <code>Sign</code> object that uses the given <code>algorithm</code>. Use
<a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a> to obtain the names of the available digest algorithms.
Optional <code>options</code> argument controls the <code>stream.Writable</code> behavior.</p>
<p>In some cases, a <code>Sign</code> instance can be created using the name of a signature
algorithm, such as <code>'RSA-SHA256'</code>, instead of a digest algorithm. This will use
the corresponding digest algorithm. This does not work for all signature
algorithms, such as <code>'ecdsa-with-SHA256'</code>, so it is best to always use digest
algorithm names.</p>
<h3><code>crypto.createVerify(algorithm[, options])</code><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">&#x3C;string></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> <a href="#stream_constructor_new_stream_writable_options"><code>stream.Writable</code> options</a></li>
<li>Returns: <a href="#crypto_class_verify" class="type">&#x3C;Verify></a></li>
</ul>
<p>Creates and returns a <code>Verify</code> object that uses the given algorithm.
Use <a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a> to obtain an array of names of the available
signing algorithms. Optional <code>options</code> argument controls the
<code>stream.Writable</code> behavior.</p>
<p>In some cases, a <code>Verify</code> instance can be created using the name of a signature
algorithm, such as <code>'RSA-SHA256'</code>, instead of a digest algorithm. This will use
the corresponding digest algorithm. This does not work for all signature
algorithms, such as <code>'ecdsa-with-SHA256'</code>, so it is best to always use digest
algorithm names.</p>
<h3><code>crypto.diffieHellman(options)</code><span><a class="mark" href="#crypto_crypto_diffiehellman_options" id="crypto_crypto_diffiehellman_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li>
<p><code>options</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>privateKey</code>: <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
<li><code>publicKey</code>: <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Computes the Diffie-Hellman secret based on a <code>privateKey</code> and a <code>publicKey</code>.
Both keys must have the same <code>asymmetricKeyType</code>, which must be one of <code>'dh'</code>
(for Diffie-Hellman), <code>'ec'</code> (for ECDH), <code>'x448'</code>, or <code>'x25519'</code> (for ECDH-ES).</p>
<h3><code>crypto.generateKeyPair(type, options, callback)</code><span><a class="mark" href="#crypto_crypto_generatekeypair_type_options_callback" id="crypto_crypto_generatekeypair_type_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>Add support for Diffie-Hellman.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add ability to generate X25519 and X448 key pairs.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add ability to generate Ed25519 and Ed448 key pairs.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>The <code>generateKeyPair</code> and <code>generateKeyPairSync</code> functions now produce key objects if no encoding was specified.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p><span>Added in: v10.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'rsa'</code>, <code>'dsa'</code>, <code>'ec'</code>, <code>'ed25519'</code>, <code>'ed448'</code>,
<code>'x25519'</code>, <code>'x448'</code>, or <code>'dh'</code>.</li>
<li>
<p><code>options</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>modulusLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Key size in bits (RSA, DSA).</li>
<li><code>publicExponent</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Public exponent (RSA). <strong>Default:</strong> <code>0x10001</code>.</li>
<li><code>divisorLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Size of <code>q</code> in bits (DSA).</li>
<li><code>namedCurve</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of the curve to use (EC).</li>
<li><code>prime</code>: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The prime parameter (DH).</li>
<li><code>primeLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Prime length in bits (DH).</li>
<li><code>generator</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Custom generator (DH). <strong>Default:</strong> <code>2</code>.</li>
<li><code>groupName</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Diffie-Hellman group name (DH). See
<a href="#crypto_crypto_getdiffiehellman_groupname"><code>crypto.getDiffieHellman()</code></a>.</li>
<li><code>publicKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> See <a href="#crypto_keyobject_export_options"><code>keyObject.export()</code></a>.</li>
<li><code>privateKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> See <a href="#crypto_keyobject_export_options"><code>keyObject.export()</code></a>.</li>
</ul>
</li>
<li>
<p><code>callback</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>publicKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
<li><code>privateKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
</li>
</ul>
<p>Generates a new asymmetric key pair of the given <code>type</code>. RSA, DSA, EC, Ed25519,
Ed448, X25519, X448, and DH are currently supported.</p>
<p>If a <code>publicKeyEncoding</code> or <code>privateKeyEncoding</code> was specified, this function
behaves as if <a href="#crypto_keyobject_export_options"><code>keyObject.export()</code></a> had been called on its result. Otherwise,
the respective part of the key is returned as a <a href="#crypto_class_keyobject"><code>KeyObject</code></a>.</p>
<p>It is recommended to encode public keys as <code>'spki'</code> and private keys as
<code>'pkcs8'</code> with encryption for long-term storage:</p>
<pre><code class="language-js">const { generateKeyPair } = require('crypto');
generateKeyPair('rsa', {
  modulusLength: 4096,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: 'top secret'
  }
}, (err, publicKey, privateKey) => {
  // Handle errors and use the generated key pair.
});
</code></pre>
<p>On completion, <code>callback</code> will be called with <code>err</code> set to <code>undefined</code> and
<code>publicKey</code> / <code>privateKey</code> representing the generated key pair.</p>
<p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns
a <code>Promise</code> for an <code>Object</code> with <code>publicKey</code> and <code>privateKey</code> properties.</p>
<h3><code>crypto.generateKeyPairSync(type, options)</code><span><a class="mark" href="#crypto_crypto_generatekeypairsync_type_options" id="crypto_crypto_generatekeypairsync_type_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>Add support for Diffie-Hellman.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add ability to generate Ed25519 and Ed448 key pairs.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>The <code>generateKeyPair</code> and <code>generateKeyPairSync</code> functions now produce key objects if no encoding was specified.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p><span>Added in: v10.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>type</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'rsa'</code>, <code>'dsa'</code>, <code>'ec'</code>, <code>'ed25519'</code>, <code>'ed448'</code>,
<code>'x25519'</code>, <code>'x448'</code>, or <code>'dh'</code>.</li>
<li>
<p><code>options</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>modulusLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Key size in bits (RSA, DSA).</li>
<li><code>publicExponent</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Public exponent (RSA). <strong>Default:</strong> <code>0x10001</code>.</li>
<li><code>divisorLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Size of <code>q</code> in bits (DSA).</li>
<li><code>namedCurve</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of the curve to use (EC).</li>
<li><code>prime</code>: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The prime parameter (DH).</li>
<li><code>primeLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Prime length in bits (DH).</li>
<li><code>generator</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Custom generator (DH). <strong>Default:</strong> <code>2</code>.</li>
<li><code>groupName</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Diffie-Hellman group name (DH). See
<a href="#crypto_crypto_getdiffiehellman_groupname"><code>crypto.getDiffieHellman()</code></a>.</li>
<li><code>publicKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> See <a href="#crypto_keyobject_export_options"><code>keyObject.export()</code></a>.</li>
<li><code>privateKeyEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> See <a href="#crypto_keyobject_export_options"><code>keyObject.export()</code></a>.</li>
</ul>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>publicKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
<li><code>privateKey</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
</li>
</ul>
<p>Generates a new asymmetric key pair of the given <code>type</code>. RSA, DSA, EC, Ed25519,
Ed448, X25519, X448, and DH are currently supported.</p>
<p>If a <code>publicKeyEncoding</code> or <code>privateKeyEncoding</code> was specified, this function
behaves as if <a href="#crypto_keyobject_export_options"><code>keyObject.export()</code></a> had been called on its result. Otherwise,
the respective part of the key is returned as a <a href="#crypto_class_keyobject"><code>KeyObject</code></a>.</p>
<p>When encoding public keys, it is recommended to use <code>'spki'</code>. When encoding
private keys, it is recommended to use <code>'pkcs8'</code> with a strong passphrase,
and to keep the passphrase confidential.</p>
<pre><code class="language-js">const { generateKeyPairSync } = require('crypto');
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
  modulusLength: 4096,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: 'top secret'
  }
});
</code></pre>
<p>The return value <code>{ publicKey, privateKey }</code> represents the generated key pair.
When PEM encoding was selected, the respective key will be a string, otherwise
it will be a buffer containing the data encoded as DER.</p>
<h3><code>crypto.getCiphers()</code><span><a class="mark" href="#crypto_crypto_getciphers" id="crypto_crypto_getciphers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> An array with the names of the supported cipher
algorithms.</li>
</ul>
<pre><code class="language-js">const ciphers = crypto.getCiphers();
console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
</code></pre>
<h3><code>crypto.getCurves()</code><span><a class="mark" href="#crypto_crypto_getcurves" id="crypto_crypto_getcurves">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v2.3.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> An array with the names of the supported elliptic curves.</li>
</ul>
<pre><code class="language-js">const curves = crypto.getCurves();
console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
</code></pre>
<h3><code>crypto.getDiffieHellman(groupName)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="#crypto_class_diffiehellmangroup" class="type">&#x3C;DiffieHellmanGroup></a></li>
</ul>
<p>Creates a predefined <code>DiffieHellmanGroup</code> key exchange object. The
supported groups are: <code>'modp1'</code>, <code>'modp2'</code>, <code>'modp5'</code> (defined in
<a href="https://www.rfc-editor.org/rfc/rfc2412.txt">RFC 2412</a>, but see <a href="#crypto_support_for_weak_or_compromised_algorithms">Caveats</a>) and <code>'modp14'</code>, <code>'modp15'</code>,
<code>'modp16'</code>, <code>'modp17'</code>, <code>'modp18'</code> (defined in <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a>). The
returned object mimics the interface of objects created by
<a href="#crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding"><code>crypto.createDiffieHellman()</code></a>, but will not allow changing
the keys (with <a href="#crypto_diffiehellman_setpublickey_publickey_encoding"><code>diffieHellman.setPublicKey()</code></a>, for example). The
advantage of using this method is that the parties do not have to
generate nor exchange a group modulus beforehand, saving both processor
and communication time.</p>
<p>Example (obtaining a shared secret):</p>
<pre><code class="language-js">const crypto = require('crypto');
const alice = crypto.getDiffieHellman('modp14');
const bob = crypto.getDiffieHellman('modp14');

alice.generateKeys();
bob.generateKeys();

const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

/* aliceSecret and bobSecret should be the same */
console.log(aliceSecret === bobSecret);
</code></pre>
<h3><code>crypto.getFips()</code><span><a class="mark" href="#crypto_crypto_getfips" id="crypto_crypto_getfips">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <code>1</code> if and only if a FIPS compliant crypto provider is
currently in use, <code>0</code> otherwise. A future semver-major release may change
the return type of this API to a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a>.</li>
</ul>
<h3><code>crypto.getHashes()</code><span><a class="mark" href="#crypto_crypto_gethashes" id="crypto_crypto_gethashes">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> An array of the names of the supported hash algorithms,
such as <code>'RSA-SHA256'</code>. Hash algorithms are also called "digest" algorithms.</li>
</ul>
<pre><code class="language-js">const hashes = crypto.getHashes();
console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
</code></pre>
<h3><code>crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)</code><span><a class="mark" href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback" id="crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>digest</code> parameter is always required now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Calling this function without passing the <code>digest</code> parameter is deprecated now and will emit a warning.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The default encoding for <code>password</code> if it is a string changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.5.5</td>
<td><p><span>Added in: v0.5.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>salt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>iterations</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>digest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>derivedKey</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
</ul>
<p>Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
implementation. A selected HMAC digest algorithm specified by <code>digest</code> is
applied to derive a key of the requested byte length (<code>keylen</code>) from the
<code>password</code>, <code>salt</code> and <code>iterations</code>.</p>
<p>The supplied <code>callback</code> function is called with two arguments: <code>err</code> and
<code>derivedKey</code>. If an error occurs while deriving the key, <code>err</code> will be set;
otherwise <code>err</code> will be <code>null</code>. By default, the successfully generated
<code>derivedKey</code> will be passed to the callback as a <a href="buffer.html"><code>Buffer</code></a>. An error will be
thrown if any of the input arguments specify invalid values or types.</p>
<p>If <code>digest</code> is <code>null</code>, <code>'sha1'</code> will be used. This behavior is deprecated,
please specify a <code>digest</code> explicitly.</p>
<p>The <code>iterations</code> argument must be a number set as high as possible. The
higher the number of iterations, the more secure the derived key will be,
but will take a longer amount of time to complete.</p>
<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p>
<pre><code class="language-js">const crypto = require('crypto');
crypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
});
</code></pre>
<p>The <code>crypto.DEFAULT_ENCODING</code> property can be used to change the way the
<code>derivedKey</code> is passed to the callback. This property, however, has been
deprecated and use should be avoided.</p>
<pre><code class="language-js">const crypto = require('crypto');
crypto.DEFAULT_ENCODING = 'hex';
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey);  // '3745e48...aa39b34'
});
</code></pre>
<p>An array of supported digest functions can be retrieved using
<a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a>.</p>
<p>This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the
<a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>
<h3><code>crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)</code><span><a class="mark" href="#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest" id="crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>Calling this function without passing the <code>digest</code> parameter is deprecated now and will emit a warning.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The default encoding for <code>password</code> if it is a string changed from <code>binary</code> to <code>utf8</code>.</p></td></tr>
<tr><td>v0.9.3</td>
<td><p><span>Added in: v0.9.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>salt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>iterations</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>digest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
implementation. A selected HMAC digest algorithm specified by <code>digest</code> is
applied to derive a key of the requested byte length (<code>keylen</code>) from the
<code>password</code>, <code>salt</code> and <code>iterations</code>.</p>
<p>If an error occurs an <code>Error</code> will be thrown, otherwise the derived key will be
returned as a <a href="buffer.html"><code>Buffer</code></a>.</p>
<p>If <code>digest</code> is <code>null</code>, <code>'sha1'</code> will be used. This behavior is deprecated,
please specify a <code>digest</code> explicitly.</p>
<p>The <code>iterations</code> argument must be a number set as high as possible. The
higher the number of iterations, the more secure the derived key will be,
but will take a longer amount of time to complete.</p>
<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p>
<pre><code class="language-js">const crypto = require('crypto');
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex'));  // '3745e48...08d59ae'
</code></pre>
<p>The <code>crypto.DEFAULT_ENCODING</code> property may be used to change the way the
<code>derivedKey</code> is returned. This property, however, is deprecated and use
should be avoided.</p>
<pre><code class="language-js">const crypto = require('crypto');
crypto.DEFAULT_ENCODING = 'hex';
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
console.log(key);  // '3745e48...aa39b34'
</code></pre>
<p>An array of supported digest functions can be retrieved using
<a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a>.</p>
<h3><code>crypto.privateDecrypt(privateKey, buffer)</code><span><a class="mark" href="#crypto_crypto_privatedecrypt_privatekey_buffer" id="crypto_crypto_privatedecrypt_privatekey_buffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.11.0</td>
<td><p>The <code>oaepLabel</code> option was added.</p></td></tr>
<tr><td>v12.9.0</td>
<td><p>The <code>oaepHash</code> option was added.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>This function now supports key objects.</p></td></tr>
<tr><td>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>privateKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></p>
<ul>
<li><code>oaepHash</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The hash function to use for OAEP padding and MGF1.
<strong>Default:</strong> <code>'sha1'</code></li>
<li><code>oaepLabel</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> The label to use for OAEP
 padding. If not specified, no label is used.</li>
<li><code>padding</code> <a href="#crypto_crypto_constants_1" class="type">&#x3C;crypto.constants></a> An optional padding value defined in
<code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code>,
<code>crypto.constants.RSA_PKCS1_PADDING</code>, or
<code>crypto.constants.RSA_PKCS1_OAEP_PADDING</code>.</li>
</ul>
</li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A new <code>Buffer</code> with the decrypted content.</li>
</ul>
<p>Decrypts <code>buffer</code> with <code>privateKey</code>. <code>buffer</code> was previously encrypted using
the corresponding public key, for example using <a href="#crypto_crypto_publicencrypt_key_buffer"><code>crypto.publicEncrypt()</code></a>.</p>
<p>If <code>privateKey</code> is not a <a href="#crypto_class_keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>privateKey</code> had been passed to <a href="#crypto_crypto_createprivatekey_key"><code>crypto.createPrivateKey()</code></a>. If it is an
object, the <code>padding</code> property can be passed. Otherwise, this function uses
<code>RSA_PKCS1_OAEP_PADDING</code>.</p>
<h3><code>crypto.privateEncrypt(privateKey, buffer)</code><span><a class="mark" href="#crypto_crypto_privateencrypt_privatekey_buffer" id="crypto_crypto_privateencrypt_privatekey_buffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.6.0</td>
<td><p>This function now supports key objects.</p></td></tr>
<tr><td>v1.1.0</td>
<td><p><span>Added in: v1.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>privateKey</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></p>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> An optional passphrase for the private key.</li>
<li><code>padding</code> <a href="#crypto_crypto_constants_1" class="type">&#x3C;crypto.constants></a> An optional padding value defined in
<code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code> or
<code>crypto.constants.RSA_PKCS1_PADDING</code>.</li>
</ul>
</li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A new <code>Buffer</code> with the encrypted content.</li>
</ul>
<p>Encrypts <code>buffer</code> with <code>privateKey</code>. The returned data can be decrypted using
the corresponding public key, for example using <a href="#crypto_crypto_publicdecrypt_key_buffer"><code>crypto.publicDecrypt()</code></a>.</p>
<p>If <code>privateKey</code> is not a <a href="#crypto_class_keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>privateKey</code> had been passed to <a href="#crypto_crypto_createprivatekey_key"><code>crypto.createPrivateKey()</code></a>. If it is an
object, the <code>padding</code> property can be passed. Otherwise, this function uses
<code>RSA_PKCS1_PADDING</code>.</p>
<h3><code>crypto.publicDecrypt(key, buffer)</code><span><a class="mark" href="#crypto_crypto_publicdecrypt_key_buffer" id="crypto_crypto_publicdecrypt_key_buffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.6.0</td>
<td><p>This function now supports key objects.</p></td></tr>
<tr><td>v1.1.0</td>
<td><p><span>Added in: v1.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></p>
<ul>
<li><code>passphrase</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> An optional passphrase for the private key.</li>
<li><code>padding</code> <a href="#crypto_crypto_constants_1" class="type">&#x3C;crypto.constants></a> An optional padding value defined in
<code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code> or
<code>crypto.constants.RSA_PKCS1_PADDING</code>.</li>
</ul>
</li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A new <code>Buffer</code> with the decrypted content.</li>
</ul>
<p>Decrypts <code>buffer</code> with <code>key</code>.<code>buffer</code> was previously encrypted using
the corresponding private key, for example using <a href="#crypto_crypto_privateencrypt_privatekey_buffer"><code>crypto.privateEncrypt()</code></a>.</p>
<p>If <code>key</code> is not a <a href="#crypto_class_keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>key</code> had been passed to <a href="#crypto_crypto_createpublickey_key"><code>crypto.createPublicKey()</code></a>. If it is an
object, the <code>padding</code> property can be passed. Otherwise, this function uses
<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><code>crypto.publicEncrypt(key, buffer)</code><span><a class="mark" href="#crypto_crypto_publicencrypt_key_buffer" id="crypto_crypto_publicencrypt_key_buffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.11.0</td>
<td><p>The <code>oaepLabel</code> option was added.</p></td></tr>
<tr><td>v12.9.0</td>
<td><p>The <code>oaepHash</code> option was added.</p></td></tr>
<tr><td>v11.6.0</td>
<td><p>This function now supports key objects.</p></td></tr>
<tr><td>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></p>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a> A PEM encoded public or private key.</li>
<li><code>oaepHash</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The hash function to use for OAEP padding and MGF1.
<strong>Default:</strong> <code>'sha1'</code></li>
<li><code>oaepLabel</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> The label to use for OAEP
 padding. If not specified, no label is used.</li>
<li><code>passphrase</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> An optional passphrase for the private key.</li>
<li><code>padding</code> <a href="#crypto_crypto_constants_1" class="type">&#x3C;crypto.constants></a> An optional padding value defined in
<code>crypto.constants</code>, which may be: <code>crypto.constants.RSA_NO_PADDING</code>,
<code>crypto.constants.RSA_PKCS1_PADDING</code>, or
<code>crypto.constants.RSA_PKCS1_OAEP_PADDING</code>.</li>
</ul>
</li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A new <code>Buffer</code> with the encrypted content.</li>
</ul>
<p>Encrypts the content of <code>buffer</code> with <code>key</code> and returns a new
<a href="buffer.html"><code>Buffer</code></a> with encrypted content. The returned data can be decrypted using
the corresponding private key, for example using <a href="#crypto_crypto_privatedecrypt_privatekey_buffer"><code>crypto.privateDecrypt()</code></a>.</p>
<p>If <code>key</code> is not a <a href="#crypto_class_keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>key</code> had been passed to <a href="#crypto_crypto_createpublickey_key"><code>crypto.createPublicKey()</code></a>. If it is an
object, the <code>padding</code> property can be passed. Otherwise, this function uses
<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><code>crypto.randomBytes(size[, callback])</code><span><a class="mark" href="#crypto_crypto_randombytes_size_callback" id="crypto_crypto_randombytes_size_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Passing <code>null</code> as the <code>callback</code> argument now throws <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>buf</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> if the <code>callback</code> function is not provided.</li>
</ul>
<p>Generates cryptographically strong pseudo-random data. The <code>size</code> argument
is a number indicating the number of bytes to generate.</p>
<p>If a <code>callback</code> function is provided, the bytes are generated asynchronously
and the <code>callback</code> function is invoked with two arguments: <code>err</code> and <code>buf</code>.
If an error occurs, <code>err</code> will be an <code>Error</code> object; otherwise it is <code>null</code>. The
<code>buf</code> argument is a <a href="buffer.html"><code>Buffer</code></a> containing the generated bytes.</p>
<pre><code class="language-js">// Asynchronous
const crypto = require('crypto');
crypto.randomBytes(256, (err, buf) => {
  if (err) throw err;
  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});
</code></pre>
<p>If the <code>callback</code> function is not provided, the random bytes are generated
synchronously and returned as a <a href="buffer.html"><code>Buffer</code></a>. An error will be thrown if
there is a problem generating the bytes.</p>
<pre><code class="language-js">// Synchronous
const buf = crypto.randomBytes(256);
console.log(
  `${buf.length} bytes of random data: ${buf.toString('hex')}`);
</code></pre>
<p>The <code>crypto.randomBytes()</code> method will not complete until there is
sufficient entropy available.
This should normally never take longer than a few milliseconds. The only time
when generating the random bytes may conceivably block for a longer period of
time is right after boot, when the whole system is still low on entropy.</p>
<p>This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the
<a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>
<p>The asynchronous version of <code>crypto.randomBytes()</code> is carried out in a single
threadpool request. To minimize threadpool task length variation, partition
large <code>randomBytes</code> requests when doing so as part of fulfilling a client
request.</p>
<h3><code>crypto.randomFillSync(buffer[, offset][, size])</code><span><a class="mark" href="#crypto_crypto_randomfillsync_buffer_offset_size" id="crypto_crypto_randomfillsync_buffer_offset_size">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>buffer</code> argument may be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v7.10.0, v6.13.0</td>
<td><p><span>Added in: v7.10.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;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">&#x3C;number></a> <strong>Default:</strong> <code>0</code></li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <strong>Default:</strong> <code>buffer.length - offset</code></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> The object passed as <code>buffer</code> argument.</li>
</ul>
<p>Synchronous version of <a href="#crypto_crypto_randomfill_buffer_offset_size_callback"><code>crypto.randomFill()</code></a>.</p>
<pre><code class="language-js">const buf = Buffer.alloc(10);
console.log(crypto.randomFillSync(buf).toString('hex'));

crypto.randomFillSync(buf, 5);
console.log(buf.toString('hex'));

// The above is equivalent to the following:
crypto.randomFillSync(buf, 5, 5);
console.log(buf.toString('hex'));
</code></pre>
<p>Any <code>TypedArray</code> or <code>DataView</code> instance may be passed as <code>buffer</code>.</p>
<pre><code class="language-js">const a = new Uint32Array(10);
console.log(Buffer.from(crypto.randomFillSync(a).buffer,
                        a.byteOffset, a.byteLength).toString('hex'));

const b = new Float64Array(10);
console.log(Buffer.from(crypto.randomFillSync(b).buffer,
                        b.byteOffset, b.byteLength).toString('hex'));

const c = new DataView(new ArrayBuffer(10));
console.log(Buffer.from(crypto.randomFillSync(c).buffer,
                        c.byteOffset, c.byteLength).toString('hex'));
</code></pre>
<h3><code>crypto.randomFill(buffer[, offset][, size], callback)</code><span><a class="mark" href="#crypto_crypto_randomfill_buffer_offset_size_callback" id="crypto_crypto_randomfill_buffer_offset_size_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>buffer</code> argument may be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v7.10.0, v6.13.0</td>
<td><p><span>Added in: v7.10.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;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">&#x3C;number></a> <strong>Default:</strong> <code>0</code></li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <strong>Default:</strong> <code>buffer.length - offset</code></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> <code>function(err, buf) {}</code>.</li>
</ul>
<p>This function is similar to <a href="#crypto_crypto_randombytes_size_callback"><code>crypto.randomBytes()</code></a> but requires the first
argument to be a <a href="buffer.html"><code>Buffer</code></a> that will be filled. It also
requires that a callback is passed in.</p>
<p>If the <code>callback</code> function is not provided, an error will be thrown.</p>
<pre><code class="language-js">const buf = Buffer.alloc(10);
crypto.randomFill(buf, (err, buf) => {
  if (err) throw err;
  console.log(buf.toString('hex'));
});

crypto.randomFill(buf, 5, (err, buf) => {
  if (err) throw err;
  console.log(buf.toString('hex'));
});

// The above is equivalent to the following:
crypto.randomFill(buf, 5, 5, (err, buf) => {
  if (err) throw err;
  console.log(buf.toString('hex'));
});
</code></pre>
<p>Any <code>TypedArray</code> or <code>DataView</code> instance may be passed as <code>buffer</code>.</p>
<pre><code class="language-js">const a = new Uint32Array(10);
crypto.randomFill(a, (err, buf) => {
  if (err) throw err;
  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
    .toString('hex'));
});

const b = new Float64Array(10);
crypto.randomFill(b, (err, buf) => {
  if (err) throw err;
  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
    .toString('hex'));
});

const c = new DataView(new ArrayBuffer(10));
crypto.randomFill(c, (err, buf) => {
  if (err) throw err;
  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
    .toString('hex'));
});
</code></pre>
<p>This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the
<a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>
<p>The asynchronous version of <code>crypto.randomFill()</code> is carried out in a single
threadpool request. To minimize threadpool task length variation, partition
large <code>randomFill</code> requests when doing so as part of fulfilling a client
request.</p>
<h3><code>crypto.scrypt(password, salt, keylen[, options], callback)</code><span><a class="mark" href="#crypto_crypto_scrypt_password_salt_keylen_options_callback" id="crypto_crypto_scrypt_password_salt_keylen_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.8.0</td>
<td><p>The <code>maxmem</code> value can now be any safe integer.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>cost</code>, <code>blockSize</code> and <code>parallelization</code> option names have been added.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>salt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>cost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> CPU/memory cost parameter. Must be a power of two greater
than one. <strong>Default:</strong> <code>16384</code>.</li>
<li><code>blockSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Block size parameter. <strong>Default:</strong> <code>8</code>.</li>
<li><code>parallelization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Parallelization parameter. <strong>Default:</strong> <code>1</code>.</li>
<li><code>N</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Alias for <code>cost</code>. Only one of both may be specified.</li>
<li><code>r</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Alias for <code>blockSize</code>. Only one of both may be specified.</li>
<li><code>p</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Alias for <code>parallelization</code>. Only one of both may be specified.</li>
<li><code>maxmem</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Memory upper bound. It is an error when (approximately)
<code>128 * N * r > maxmem</code>. <strong>Default:</strong> <code>32 * 1024 * 1024</code>.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>derivedKey</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
</ul>
<p>Provides an asynchronous <a href="https://en.wikipedia.org/wiki/Scrypt">scrypt</a> implementation. Scrypt is a password-based
key derivation function that is designed to be expensive computationally and
memory-wise in order to make brute-force attacks unrewarding.</p>
<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p>
<p>The <code>callback</code> function is called with two arguments: <code>err</code> and <code>derivedKey</code>.
<code>err</code> is an exception object when key derivation fails, otherwise <code>err</code> is
<code>null</code>. <code>derivedKey</code> is passed to the callback as a <a href="buffer.html"><code>Buffer</code></a>.</p>
<p>An exception is thrown when any of the input arguments specify invalid values
or types.</p>
<pre><code class="language-js">const crypto = require('crypto');
// Using the factory defaults.
crypto.scrypt('secret', 'salt', 64, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
});
// Using a custom N parameter. Must be a power of two.
crypto.scrypt('secret', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'
});
</code></pre>
<h3><code>crypto.scryptSync(password, salt, keylen[, options])</code><span><a class="mark" href="#crypto_crypto_scryptsync_password_salt_keylen_options" id="crypto_crypto_scryptsync_password_salt_keylen_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.8.0</td>
<td><p>The <code>maxmem</code> value can now be any safe integer.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>cost</code>, <code>blockSize</code> and <code>parallelization</code> option names have been added.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>salt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>keylen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>cost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> CPU/memory cost parameter. Must be a power of two greater
than one. <strong>Default:</strong> <code>16384</code>.</li>
<li><code>blockSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Block size parameter. <strong>Default:</strong> <code>8</code>.</li>
<li><code>parallelization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Parallelization parameter. <strong>Default:</strong> <code>1</code>.</li>
<li><code>N</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Alias for <code>cost</code>. Only one of both may be specified.</li>
<li><code>r</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Alias for <code>blockSize</code>. Only one of both may be specified.</li>
<li><code>p</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Alias for <code>parallelization</code>. Only one of both may be specified.</li>
<li><code>maxmem</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Memory upper bound. It is an error when (approximately)
<code>128 * N * r > maxmem</code>. <strong>Default:</strong> <code>32 * 1024 * 1024</code>.</li>
</ul>
</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Provides a synchronous <a href="https://en.wikipedia.org/wiki/Scrypt">scrypt</a> implementation. Scrypt is a password-based
key derivation function that is designed to be expensive computationally and
memory-wise in order to make brute-force attacks unrewarding.</p>
<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is
random and at least 16 bytes long. See <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf">NIST SP 800-132</a> for details.</p>
<p>An exception is thrown when key derivation fails, otherwise the derived key is
returned as a <a href="buffer.html"><code>Buffer</code></a>.</p>
<p>An exception is thrown when any of the input arguments specify invalid values
or types.</p>
<pre><code class="language-js">const crypto = require('crypto');
// Using the factory defaults.
const key1 = crypto.scryptSync('secret', 'salt', 64);
console.log(key1.toString('hex'));  // '3745e48...08d59ae'
// Using a custom N parameter. Must be a power of two.
const key2 = crypto.scryptSync('secret', 'salt', 64, { N: 1024 });
console.log(key2.toString('hex'));  // '3745e48...aa39b34'
</code></pre>
<h3><code>crypto.setEngine(engine[, flags])</code><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">&#x3C;string></a></li>
<li><code>flags</code> <a href="#crypto_crypto_constants_1" class="type">&#x3C;crypto.constants></a> <strong>Default:</strong> <code>crypto.constants.ENGINE_METHOD_ALL</code></li>
</ul>
<p>Load and set the <code>engine</code> for some or all OpenSSL functions (selected by flags).</p>
<p><code>engine</code> could be either an id or a path to the engine's shared library.</p>
<p>The optional <code>flags</code> argument uses <code>ENGINE_METHOD_ALL</code> by default. The <code>flags</code>
is a bit field taking one of or a mix of the following flags (defined in
<code>crypto.constants</code>):</p>
<ul>
<li><code>crypto.constants.ENGINE_METHOD_RSA</code></li>
<li><code>crypto.constants.ENGINE_METHOD_DSA</code></li>
<li><code>crypto.constants.ENGINE_METHOD_DH</code></li>
<li><code>crypto.constants.ENGINE_METHOD_RAND</code></li>
<li><code>crypto.constants.ENGINE_METHOD_EC</code></li>
<li><code>crypto.constants.ENGINE_METHOD_CIPHERS</code></li>
<li><code>crypto.constants.ENGINE_METHOD_DIGESTS</code></li>
<li><code>crypto.constants.ENGINE_METHOD_PKEY_METHS</code></li>
<li><code>crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS</code></li>
<li><code>crypto.constants.ENGINE_METHOD_ALL</code></li>
<li><code>crypto.constants.ENGINE_METHOD_NONE</code></li>
</ul>
<p>The flags below are deprecated in OpenSSL-1.1.0.</p>
<ul>
<li><code>crypto.constants.ENGINE_METHOD_ECDH</code></li>
<li><code>crypto.constants.ENGINE_METHOD_ECDSA</code></li>
<li><code>crypto.constants.ENGINE_METHOD_STORE</code></li>
</ul>
<h3><code>crypto.setFips(bool)</code><span><a class="mark" href="#crypto_crypto_setfips_bool" id="crypto_crypto_setfips_bool">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>bool</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> to enable FIPS mode.</li>
</ul>
<p>Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.
Throws an error if FIPS mode is not available.</p>
<h3><code>crypto.sign(algorithm, data, key)</code><span><a class="mark" href="#crypto_crypto_sign_algorithm_data_key" id="crypto_crypto_sign_algorithm_data_key">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
<li><code>data</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Calculates and returns the signature for <code>data</code> using the given private key and
algorithm. If <code>algorithm</code> is <code>null</code> or <code>undefined</code>, then the algorithm is
dependent upon the key type (especially Ed25519 and Ed448).</p>
<p>If <code>key</code> is not a <a href="#crypto_class_keyobject"><code>KeyObject</code></a>, this function behaves as if <code>key</code> had been
passed to <a href="#crypto_crypto_createprivatekey_key"><code>crypto.createPrivateKey()</code></a>. If it is an object, the following
additional properties can be passed:</p>
<ul>
<li>
<p><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> For DSA and ECDSA, this option specifies the
format of the generated signature. It can be one of the following:</p>
<ul>
<li><code>'der'</code> (default): DER-encoded ASN.1 signature structure encoding <code>(r, s)</code>.</li>
<li><code>'ieee-p1363'</code>: Signature format <code>r || s</code> as proposed in IEEE-P1363.</li>
</ul>
</li>
<li>
<p><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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><code>RSA_PKCS1_PSS_PADDING</code> will use MGF1 with the same hash function
used to sign the message as specified in section 3.1 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>.</p>
</li>
<li>
<p><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Salt length for when padding is
<code>RSA_PKCS1_PSS_PADDING</code>. The special value
<code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest
size, <code>crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN</code> (default) sets it to the
maximum permissible value.</p>
</li>
</ul>
<h3><code>crypto.timingSafeEqual(a, b)</code><span><a class="mark" href="#crypto_crypto_timingsafeequal_a_b" id="crypto_crypto_timingsafeequal_a_b">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.6.0</span>
</div>
<ul>
<li><code>a</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>b</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>This function is based on a constant-time algorithm.
Returns true if <code>a</code> is equal to <code>b</code>, without leaking timing information that
would allow an attacker to guess one of the values. This is suitable for
comparing HMAC digests or secret values like authentication cookies or
<a href="https://www.w3.org/TR/capability-urls/">capability urls</a>.</p>
<p><code>a</code> and <code>b</code> must both be <code>Buffer</code>s, <code>TypedArray</code>s, or <code>DataView</code>s, and they
must have the same length.</p>
<p>Use of <code>crypto.timingSafeEqual</code> does not guarantee that the <em>surrounding</em> code
is timing-safe. Care should be taken to ensure that the surrounding code does
not introduce timing vulnerabilities.</p>
<h3><code>crypto.verify(algorithm, data, key, signature)</code><span><a class="mark" href="#crypto_crypto_verify_algorithm_data_key_signature" id="crypto_crypto_verify_algorithm_data_key_signature">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<ul>
<li><code>algorithm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
<li><code>data</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#crypto_class_keyobject" class="type">&#x3C;KeyObject></a></li>
<li><code>signature</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Verifies the given signature for <code>data</code> using the given key and algorithm. If
<code>algorithm</code> is <code>null</code> or <code>undefined</code>, then the algorithm is dependent upon the
key type (especially Ed25519 and Ed448).</p>
<p>If <code>key</code> is not a <a href="#crypto_class_keyobject"><code>KeyObject</code></a>, this function behaves as if <code>key</code> had been
passed to <a href="#crypto_crypto_createpublickey_key"><code>crypto.createPublicKey()</code></a>. If it is an object, the following
additional properties can be passed:</p>
<ul>
<li>
<p><code>dsaEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> For DSA and ECDSA, this option specifies the
format of the generated signature. It can be one of the following:</p>
<ul>
<li><code>'der'</code> (default): DER-encoded ASN.1 signature structure encoding <code>(r, s)</code>.</li>
<li><code>'ieee-p1363'</code>: Signature format <code>r || s</code> as proposed in IEEE-P1363.</li>
</ul>
</li>
<li>
<p><code>padding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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><code>RSA_PKCS1_PSS_PADDING</code> will use MGF1 with the same hash function
used to sign the message as specified in section 3.1 of <a href="https://www.rfc-editor.org/rfc/rfc4055.txt">RFC 4055</a>.</p>
</li>
<li>
<p><code>saltLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Salt length for when padding is
<code>RSA_PKCS1_PSS_PADDING</code>. The special value
<code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest
size, <code>crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN</code> (default) sets it to the
maximum permissible value.</p>
</li>
</ul>
<p>The <code>signature</code> argument is the previously calculated signature for the <code>data</code>.</p>
<p>Because public keys can be derived from private keys, a private key or a public
key may be passed for <code>key</code>.</p>
<h2>Notes<span><a class="mark" href="#crypto_notes" id="crypto_notes">#</a></span></h2>
<h3>Legacy Streams API (prior to Node.js 0.10)<span><a class="mark" href="#crypto_legacy_streams_api_prior_to_node_js_0_10" id="crypto_legacy_streams_api_prior_to_node_js_0_10">#</a></span></h3>
<p>The Crypto module was added to Node.js before there was the concept of a
unified Stream API, and before there were <a href="buffer.html"><code>Buffer</code></a> objects for handling
binary data. As such, the many of the <code>crypto</code> defined classes have methods not
typically found on other Node.js classes that implement the <a href="stream.html">streams</a>
API (e.g. <code>update()</code>, <code>final()</code>, or <code>digest()</code>). Also, many methods accepted
and returned <code>'latin1'</code> encoded strings by default rather than <code>Buffer</code>s. This
default was changed after Node.js v0.8 to use <a href="buffer.html"><code>Buffer</code></a> objects by default
instead.</p>
<h3>Recent ECDH changes<span><a class="mark" href="#crypto_recent_ecdh_changes" id="crypto_recent_ecdh_changes">#</a></span></h3>
<p>Usage of <code>ECDH</code> with non-dynamically generated key pairs has been simplified.
Now, <a href="#crypto_ecdh_setprivatekey_privatekey_encoding"><code>ecdh.setPrivateKey()</code></a> can be called with a preselected private key
and the associated public point (key) will be computed and stored in the object.
This allows code to only store and provide the private part of the EC key pair.
<a href="#crypto_ecdh_setprivatekey_privatekey_encoding"><code>ecdh.setPrivateKey()</code></a> now also validates that the private key is valid for
the selected curve.</p>
<p>The <a href="#crypto_ecdh_setpublickey_publickey_encoding"><code>ecdh.setPublicKey()</code></a> method is now deprecated as its inclusion in the
API is not useful. Either a previously stored private key should be set, which
automatically generates the associated public key, or <a href="#crypto_ecdh_generatekeys_encoding_format"><code>ecdh.generateKeys()</code></a>
should be called. The main drawback of using <a href="#crypto_ecdh_setpublickey_publickey_encoding"><code>ecdh.setPublicKey()</code></a> is that
it can be used to put the ECDH key pair into an inconsistent state.</p>
<h3>Support for weak or compromised algorithms<span><a class="mark" href="#crypto_support_for_weak_or_compromised_algorithms" id="crypto_support_for_weak_or_compromised_algorithms">#</a></span></h3>
<p>The <code>crypto</code> module still supports some algorithms which are already
compromised and are not currently recommended for use. The API also allows
the use of ciphers and hashes with a small key size that are too weak for safe
use.</p>
<p>Users should take full responsibility for selecting the crypto
algorithm and key size according to their security requirements.</p>
<p>Based on the recommendations of <a href="https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf">NIST SP 800-131A</a>:</p>
<ul>
<li>MD5 and SHA-1 are no longer acceptable where collision resistance is
required such as digital signatures.</li>
<li>The key used with RSA, DSA, and DH algorithms is recommended to have
at least 2048 bits and that of the curve of ECDSA and ECDH at least
224 bits, to be safe to use for several years.</li>
<li>The DH groups of <code>modp1</code>, <code>modp2</code> and <code>modp5</code> have a key size
smaller than 2048 bits and are not recommended.</li>
</ul>
<p>See the reference for other recommendations and details.</p>
<h3>CCM mode<span><a class="mark" href="#crypto_ccm_mode" id="crypto_ccm_mode">#</a></span></h3>
<p>CCM is one of the supported <a href="https://en.wikipedia.org/wiki/Authenticated_encryption">AEAD algorithms</a>. Applications which use this
mode must adhere to certain restrictions when using the cipher API:</p>
<ul>
<li>The authentication tag length must be specified during cipher creation by
setting the <code>authTagLength</code> option and must be one of 4, 6, 8, 10, 12, 14 or
16 bytes.</li>
<li>The length of the initialization vector (nonce) <code>N</code> must be between 7 and 13
bytes (<code>7 ≤ N ≤ 13</code>).</li>
<li>The length of the plaintext is limited to <code>2 ** (8 * (15 - N))</code> bytes.</li>
<li>When decrypting, the authentication tag must be set via <code>setAuthTag()</code> before
calling <code>update()</code>.
Otherwise, decryption will fail and <code>final()</code> will throw an error in
compliance with section 2.6 of <a href="https://www.rfc-editor.org/rfc/rfc3610.txt">RFC 3610</a>.</li>
<li>Using stream methods such as <code>write(data)</code>, <code>end(data)</code> or <code>pipe()</code> in CCM
mode might fail as CCM cannot handle more than one chunk of data per instance.</li>
<li>When passing additional authenticated data (AAD), the length of the actual
message in bytes must be passed to <code>setAAD()</code> via the <code>plaintextLength</code>
option.
Many crypto libraries include the authentication tag in the ciphertext,
which means that they produce ciphertexts of the length
<code>plaintextLength + authTagLength</code>. Node.js does not include the authentication
tag, so the ciphertext length is always <code>plaintextLength</code>.
This is not necessary if no AAD is used.</li>
<li>As CCM processes the whole message at once, <code>update()</code> can only be called
once.</li>
<li>Even though calling <code>update()</code> is sufficient to encrypt/decrypt the message,
applications <em>must</em> call <code>final()</code> to compute or verify the
authentication tag.</li>
</ul>
<pre><code class="language-js">const crypto = require('crypto');

const key = 'keykeykeykeykeykeykeykey';
const nonce = crypto.randomBytes(12);

const aad = Buffer.from('0123456789', 'hex');

const cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, {
  authTagLength: 16
});
const plaintext = 'Hello world';
cipher.setAAD(aad, {
  plaintextLength: Buffer.byteLength(plaintext)
});
const ciphertext = cipher.update(plaintext, 'utf8');
cipher.final();
const tag = cipher.getAuthTag();

// Now transmit { ciphertext, nonce, tag }.

const decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, {
  authTagLength: 16
});
decipher.setAuthTag(tag);
decipher.setAAD(aad, {
  plaintextLength: ciphertext.length
});
const receivedPlaintext = decipher.update(ciphertext, null, 'utf8');

try {
  decipher.final();
} catch (err) {
  console.error('Authentication failed!');
  return;
}

console.log(receivedPlaintext);
</code></pre>
<h2>Crypto constants<span><a class="mark" href="#crypto_crypto_constants_1" id="crypto_crypto_constants_1">#</a></span></h2>
<p>The following constants exported by <code>crypto.constants</code> apply to various uses of
the <code>crypto</code>, <code>tls</code>, and <code>https</code> modules and are generally specific to OpenSSL.</p>
<h3>OpenSSL options<span><a class="mark" href="#crypto_openssl_options" id="crypto_openssl_options">#</a></span></h3>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>SSL_OP_ALL</code></td>
    <td>Applies multiple bug workarounds within OpenSSL. See
    <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a>
    for detail.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION</code></td>
    <td>Allows legacy insecure renegotiation between OpenSSL and unpatched
    clients or servers. See
    <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a>.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_CIPHER_SERVER_PREFERENCE</code></td>
    <td>Attempts to use the server's preferences instead of the client's when
    selecting a cipher. Behavior depends on protocol version. See
    <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a>.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_CISCO_ANYCONNECT</code></td>
    <td>Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_COOKIE_EXCHANGE</code></td>
    <td>Instructs OpenSSL to turn on cookie exchange.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_CRYPTOPRO_TLSEXT_BUG</code></td>
    <td>Instructs OpenSSL to add server-hello extension from an early version
    of the cryptopro draft.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS</code></td>
    <td>Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability
    workaround added in OpenSSL 0.9.6d.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_EPHEMERAL_RSA</code></td>
    <td>Instructs OpenSSL to always use the tmp_rsa key when performing RSA
    operations.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_LEGACY_SERVER_CONNECT</code></td>
    <td>Allows initial connection to servers that do not support RI.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_MICROSOFT_SESS_ID_BUG</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_MSIE_SSLV2_RSA_PADDING</code></td>
    <td>Instructs OpenSSL to disable the workaround for a man-in-the-middle
    protocol-version vulnerability in the SSL 2.0 server implementation.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_NETSCAPE_CA_DN_BUG</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_NETSCAPE_CHALLENGE_BUG</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_NO_COMPRESSION</code></td>
    <td>Instructs OpenSSL to disable support for SSL/TLS compression.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_NO_QUERY_MTU</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION</code></td>
    <td>Instructs OpenSSL to always start a new session when performing
    renegotiation.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_NO_SSLv2</code></td>
    <td>Instructs OpenSSL to turn off SSL v2</td>
  </tr>
  <tr>
    <td><code>SSL_OP_NO_SSLv3</code></td>
    <td>Instructs OpenSSL to turn off SSL v3</td>
  </tr>
  <tr>
    <td><code>SSL_OP_NO_TICKET</code></td>
    <td>Instructs OpenSSL to disable use of RFC4507bis tickets.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_NO_TLSv1</code></td>
    <td>Instructs OpenSSL to turn off TLS v1</td>
  </tr>
  <tr>
    <td><code>SSL_OP_NO_TLSv1_1</code></td>
    <td>Instructs OpenSSL to turn off TLS v1.1</td>
  </tr>
  <tr>
    <td><code>SSL_OP_NO_TLSv1_2</code></td>
    <td>Instructs OpenSSL to turn off TLS v1.2</td>
  </tr>
    <tr><td><code>SSL_OP_PKCS1_CHECK_1</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_PKCS1_CHECK_2</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_SINGLE_DH_USE</code></td>
    <td>Instructs OpenSSL to always create a new key when using
    temporary/ephemeral DH parameters.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_SINGLE_ECDH_USE</code></td>
    <td>Instructs OpenSSL to always create a new key when using
    temporary/ephemeral ECDH parameters.</td>
  </tr>
    <tr><td><code>SSL_OP_SSLEAY_080_CLIENT_DH_BUG</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_TLS_BLOCK_PADDING_BUG</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_TLS_D5_BUG</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_TLS_ROLLBACK_BUG</code></td>
    <td>Instructs OpenSSL to disable version rollback attack detection.</td>
  </tr>
</tbody></table>
<h3>OpenSSL engine constants<span><a class="mark" href="#crypto_openssl_engine_constants" id="crypto_openssl_engine_constants">#</a></span></h3>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>ENGINE_METHOD_RSA</code></td>
    <td>Limit engine usage to RSA</td>
  </tr>
  <tr>
    <td><code>ENGINE_METHOD_DSA</code></td>
    <td>Limit engine usage to DSA</td>
  </tr>
  <tr>
    <td><code>ENGINE_METHOD_DH</code></td>
    <td>Limit engine usage to DH</td>
  </tr>
  <tr>
    <td><code>ENGINE_METHOD_RAND</code></td>
    <td>Limit engine usage to RAND</td>
  </tr>
  <tr>
    <td><code>ENGINE_METHOD_EC</code></td>
    <td>Limit engine usage to EC</td>
  </tr>
  <tr>
    <td><code>ENGINE_METHOD_CIPHERS</code></td>
    <td>Limit engine usage to CIPHERS</td>
  </tr>
  <tr>
    <td><code>ENGINE_METHOD_DIGESTS</code></td>
    <td>Limit engine usage to DIGESTS</td>
  </tr>
  <tr>
    <td><code>ENGINE_METHOD_PKEY_METHS</code></td>
    <td>Limit engine usage to PKEY_METHDS</td>
  </tr>
  <tr>
    <td><code>ENGINE_METHOD_PKEY_ASN1_METHS</code></td>
    <td>Limit engine usage to PKEY_ASN1_METHS</td>
  </tr>
  <tr>
    <td><code>ENGINE_METHOD_ALL</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>ENGINE_METHOD_NONE</code></td>
    <td></td>
  </tr>
</tbody></table>
<h3>Other OpenSSL constants<span><a class="mark" href="#crypto_other_openssl_constants" id="crypto_other_openssl_constants">#</a></span></h3>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>DH_CHECK_P_NOT_SAFE_PRIME</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>DH_CHECK_P_NOT_PRIME</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>DH_UNABLE_TO_CHECK_GENERATOR</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>DH_NOT_SUITABLE_GENERATOR</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>ALPN_ENABLED</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>RSA_PKCS1_PADDING</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>RSA_SSLV23_PADDING</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>RSA_NO_PADDING</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>RSA_PKCS1_OAEP_PADDING</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>RSA_X931_PADDING</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>RSA_PKCS1_PSS_PADDING</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>RSA_PSS_SALTLEN_DIGEST</code></td>
    <td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the
        digest size when signing or verifying.</td>
  </tr>
  <tr>
    <td><code>RSA_PSS_SALTLEN_MAX_SIGN</code></td>
    <td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the
        maximum permissible value when signing data.</td>
  </tr>
  <tr>
    <td><code>RSA_PSS_SALTLEN_AUTO</code></td>
    <td>Causes the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to be
        determined automatically when verifying a signature.</td>
  </tr>
  <tr>
    <td><code>POINT_CONVERSION_COMPRESSED</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>POINT_CONVERSION_UNCOMPRESSED</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>POINT_CONVERSION_HYBRID</code></td>
    <td></td>
  </tr>
</tbody></table>
<h3>Node.js crypto constants<span><a class="mark" href="#crypto_node_js_crypto_constants" id="crypto_node_js_crypto_constants">#</a></span></h3>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>defaultCoreCipherList</code></td>
    <td>Specifies the built-in default cipher list used by Node.js.</td>
  </tr>
  <tr>
    <td><code>defaultCipherList</code></td>
    <td>Specifies the active default cipher list used by the current Node.js
    process.</td>
  </tr>
</tbody></table>
<h1>Debugger<span><a class="mark" href="#debugger_debugger" id="debugger_debugger">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>

<p>Node.js includes an out-of-process debugging utility accessible via a
<a href="#debugger_v8_inspector_integration_for_node_js">V8 Inspector</a> and built-in debugging client. To use it, start Node.js
with the <code>inspect</code> argument followed by the path to the script to debug; a
prompt will be displayed indicating successful launch of the debugger:</p>
<pre><code class="language-console">$ node inspect myscript.js
&#x3C; Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba
&#x3C; For help, see: https://nodejs.org/en/docs/inspector
&#x3C; 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>The Node.js debugger client is not a full-featured debugger, but simple step and
inspection are possible.</p>
<p>Inserting the statement <code>debugger;</code> into the source code of a script will
enable a breakpoint at that position in the code:</p>
<!-- eslint-disable no-debugger -->
<pre><code class="language-js">// myscript.js
global.x = 5;
setTimeout(() => {
  debugger;
  console.log('world');
}, 1000);
console.log('hello');
</code></pre>
<p>Once the debugger is run, a breakpoint will occur at line 3:</p>
<pre><code class="language-console">$ node inspect myscript.js
&#x3C; Debugger listening on ws://127.0.0.1:9229/80e7a814-7cd3-49fb-921a-2e02228cd5ba
&#x3C; For help, see: https://nodejs.org/en/docs/inspector
&#x3C; 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
&#x3C; 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
&#x3C; world
break in myscript.js:5
  3   debugger;
  4   console.log('world');
> 5 }, 1000);
  6 console.log('hello');
  7
debug> .exit
</code></pre>
<p>The <code>repl</code> command allows code to be evaluated remotely. The <code>next</code> command
steps to the next line. Type <code>help</code> to see what other commands are available.</p>
<p>Pressing <code>enter</code> without typing a command will repeat the previous debugger
command.</p>
<h2>Watchers<span><a class="mark" href="#debugger_watchers" id="debugger_watchers">#</a></span></h2>
<p>It is possible to watch expression and variable values while debugging. On
every breakpoint, each expression from the watchers list will be evaluated
in the current context and displayed immediately before the breakpoint's
source code listing.</p>
<p>To begin watching an expression, type <code>watch('my_expression')</code>. The command
<code>watchers</code> will print the active watchers. To remove a watcher, type
<code>unwatch('my_expression')</code>.</p>
<h2>Command reference<span><a class="mark" href="#debugger_command_reference" id="debugger_command_reference">#</a></span></h2>
<h3>Stepping<span><a class="mark" href="#debugger_stepping" id="debugger_stepping">#</a></span></h3>
<ul>
<li><code>cont</code>, <code>c</code>: Continue execution</li>
<li><code>next</code>, <code>n</code>: Step next</li>
<li><code>step</code>, <code>s</code>: Step in</li>
<li><code>out</code>, <code>o</code>: Step out</li>
<li><code>pause</code>: Pause running code (like pause button in Developer Tools)</li>
</ul>
<h3>Breakpoints<span><a class="mark" href="#debugger_breakpoints" id="debugger_breakpoints">#</a></span></h3>
<ul>
<li><code>setBreakpoint()</code>, <code>sb()</code>: Set breakpoint on current line</li>
<li><code>setBreakpoint(line)</code>, <code>sb(line)</code>: Set breakpoint on specific line</li>
<li><code>setBreakpoint('fn()')</code>, <code>sb(...)</code>: Set breakpoint on a first statement in
functions body</li>
<li><code>setBreakpoint('script.js', 1)</code>, <code>sb(...)</code>: Set breakpoint on first line of
<code>script.js</code></li>
<li><code>clearBreakpoint('script.js', 1)</code>, <code>cb(...)</code>: Clear breakpoint in <code>script.js</code>
on line 1</li>
</ul>
<p>It is also possible to set a breakpoint in a file (module) that
is not loaded yet:</p>
<pre><code class="language-console">$ node inspect main.js
&#x3C; Debugger listening on ws://127.0.0.1:9229/4e3db158-9791-4274-8909-914f7facf3bd
&#x3C; For help, see: https://nodejs.org/en/docs/inspector
&#x3C; Debugger attached.
Break on start in main.js:1
> 1 (function (exports, require, module, __filename, __dirname) { const mod = require('./mod.js');
  2 mod.hello();
  3 mod.hello();
debug> setBreakpoint('mod.js', 22)
Warning: script 'mod.js' was not loaded yet.
debug> c
break in mod.js:22
 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
 21
>22 exports.hello = function() {
 23   return 'hello from module';
 24 };
debug>
</code></pre>
<h3>Information<span><a class="mark" href="#debugger_information" id="debugger_information">#</a></span></h3>
<ul>
<li><code>backtrace</code>, <code>bt</code>: Print backtrace of current execution frame</li>
<li><code>list(5)</code>: List scripts source code with 5 line context (5 lines before and
after)</li>
<li><code>watch(expr)</code>: Add expression to watch list</li>
<li><code>unwatch(expr)</code>: Remove expression from watch list</li>
<li><code>watchers</code>: List all watchers and their values (automatically listed on each
breakpoint)</li>
<li><code>repl</code>: Open debugger's repl for evaluation in debugging script's context</li>
<li><code>exec expr</code>: Execute an expression in debugging script's context</li>
</ul>
<h3>Execution control<span><a class="mark" href="#debugger_execution_control" id="debugger_execution_control">#</a></span></h3>
<ul>
<li><code>run</code>: Run script (automatically runs on debugger's start)</li>
<li><code>restart</code>: Restart script</li>
<li><code>kill</code>: Kill script</li>
</ul>
<h3>Various<span><a class="mark" href="#debugger_various" id="debugger_various">#</a></span></h3>
<ul>
<li><code>scripts</code>: List all loaded scripts</li>
<li><code>version</code>: Display V8's version</li>
</ul>
<h2>Advanced usage<span><a class="mark" href="#debugger_advanced_usage" id="debugger_advanced_usage">#</a></span></h2>
<h3>V8 inspector integration for Node.js<span><a class="mark" href="#debugger_v8_inspector_integration_for_node_js" id="debugger_v8_inspector_integration_for_node_js">#</a></span></h3>
<p>V8 Inspector integration allows attaching Chrome DevTools to Node.js
instances for debugging and profiling. It uses the
<a href="https://chromedevtools.github.io/devtools-protocol/">Chrome DevTools Protocol</a>.</p>
<p>V8 Inspector can be enabled by passing the <code>--inspect</code> flag when starting a
Node.js application. It is also possible to supply a custom port with that flag,
e.g. <code>--inspect=9222</code> will accept DevTools connections on port 9222.</p>
<p>To break on the first line of the application code, pass the <code>--inspect-brk</code>
flag instead of <code>--inspect</code>.</p>
<pre><code class="language-console">$ node --inspect index.js
Debugger listening on ws://127.0.0.1:9229/dc9010dd-f8b8-4ac5-a510-c1a114ec7d29
For help, see: https://nodejs.org/en/docs/inspector
</code></pre>
<p>(In the example above, the UUID dc9010dd-f8b8-4ac5-a510-c1a114ec7d29
at the end of the URL is generated on the fly, it varies in different
debugging sessions.)</p>
<p>If the Chrome browser is older than 66.0.3345.0,
use <code>inspector.html</code> instead of <code>js_app.html</code> in the above URL.</p>
<p>Chrome DevTools doesn't support debugging <a href="worker_threads.html">worker threads</a> yet.
<a href="https://github.com/GoogleChromeLabs/ndb/">ndb</a> can be used to debug them.</p>
<h1>Deprecated APIs<span><a class="mark" href="#deprecations_deprecated_apis" id="deprecations_deprecated_apis">#</a></span></h1>


<p>Node.js may deprecate APIs for any of the following reasons:</p>
<ul>
<li>Use of the API is unsafe.</li>
<li>An improved alternative API is available.</li>
<li>Breaking changes to the API are expected in a future major release.</li>
</ul>
<p>Node.js utilizes three kinds of Deprecations:</p>
<ul>
<li>Documentation-only</li>
<li>Runtime</li>
<li>End-of-Life</li>
</ul>
<p>A Documentation-only deprecation is one that is expressed only within the
Node.js API docs. These generate no side-effects while running Node.js.
Some Documentation-only deprecations trigger a runtime warning when launched
with <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a> flag (or its alternative,
<code>NODE_PENDING_DEPRECATION=1</code> environment variable), similarly to Runtime
deprecations below. Documentation-only deprecations that support that flag
are explicitly labeled as such in the
<a href="#deprecations_list_of_deprecated_apis">list of Deprecated APIs</a>.</p>
<p>A Runtime deprecation will, by default, generate a process warning that will
be printed to <code>stderr</code> the first time the deprecated API is used. When the
<a href="#cli_throw_deprecation"><code>--throw-deprecation</code></a> command-line flag is used, a Runtime deprecation will
cause an error to be thrown.</p>
<p>An End-of-Life deprecation is used when functionality is or will soon be removed
from Node.js.</p>
<h2>Revoking deprecations<span><a class="mark" href="#deprecations_revoking_deprecations" id="deprecations_revoking_deprecations">#</a></span></h2>
<p>Occasionally, the deprecation of an API may be reversed. In such situations,
this document will be updated with information relevant to the decision.
However, the deprecation identifier will not be modified.</p>
<h2>List of deprecated APIs<span><a class="mark" href="#deprecations_list_of_deprecated_apis" id="deprecations_list_of_deprecated_apis">#</a></span></h2>
<p><a id="DEP0001"></a></p>
<h3>DEP0001: <code>http.OutgoingMessage.prototype.flush</code><span><a class="mark" href="#deprecations_dep0001_http_outgoingmessage_prototype_flush" id="deprecations_dep0001_http_outgoingmessage_prototype_flush">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v1.6.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>OutgoingMessage.prototype.flush()</code> method is deprecated. Use
<code>OutgoingMessage.prototype.flushHeaders()</code> instead.</p>
<p><a id="DEP0002"></a></p>
<h3>DEP0002: <code>require('_linklist')</code><span><a class="mark" href="#deprecations_dep0002_require_linklist" id="deprecations_dep0002_require_linklist">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>_linklist</code> module is deprecated. Please use a userland alternative.</p>
<p><a id="DEP0003"></a></p>
<h3>DEP0003: <code>_writableState.buffer</code><span><a class="mark" href="#deprecations_dep0003_writablestate_buffer" id="deprecations_dep0003_writablestate_buffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>_writableState.buffer</code> property is deprecated. Use the
<code>_writableState.getBuffer()</code> method instead.</p>
<p><a id="DEP0004"></a></p>
<h3>DEP0004: <code>CryptoStream.prototype.readyState</code><span><a class="mark" href="#deprecations_dep0004_cryptostream_prototype_readystate" id="deprecations_dep0004_cryptostream_prototype_readystate">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>0.4.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>CryptoStream.prototype.readyState</code> property was removed.</p>
<p><a id="DEP0005"></a></p>
<h3>DEP0005: <code>Buffer()</code> constructor<span><a class="mark" href="#deprecations_dep0005_buffer_constructor" id="deprecations_dep0005_buffer_constructor">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime (supports <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a>)</p>
<p>The <code>Buffer()</code> function and <code>new Buffer()</code> constructor are deprecated due to
API usability issues that can lead to accidental security issues.</p>
<p>As an alternative, use one of the following methods of constructing <code>Buffer</code>
objects:</p>
<ul>
<li><a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc(size[, fill[, encoding]])</code></a>: Create a <code>Buffer</code> with
<em>initialized</em> memory.</li>
<li><a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe(size)</code></a>: Create a <code>Buffer</code> with
<em>uninitialized</em> memory.</li>
<li><a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow(size)</code></a>: Create a <code>Buffer</code> with <em>uninitialized</em>
memory.</li>
<li><a href="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a>: Create a <code>Buffer</code> with a copy of <code>array</code></li>
<li><a href="#buffer_class_method_buffer_from_arraybuffer_byteoffset_length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a> -
Create a <code>Buffer</code> that wraps the given <code>arrayBuffer</code>.</li>
<li><a href="#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a>: Create a <code>Buffer</code> that copies <code>buffer</code>.</li>
<li><a href="#buffer_class_method_buffer_from_string_encoding"><code>Buffer.from(string[, encoding])</code></a>: Create a <code>Buffer</code>
that copies <code>string</code>.</li>
</ul>
<p>Without <code>--pending-deprecation</code>, runtime warnings occur only for code not in
<code>node_modules</code>. This means there will not be deprecation warnings for
<code>Buffer()</code> usage in dependencies. With <code>--pending-deprecation</code>, a runtime
warning results no matter where the <code>Buffer()</code> usage occurs.</p>
<p><a id="DEP0006"></a></p>
<h3>DEP0006: <code>child_process</code> <code>options.customFds</code><span><a class="mark" href="#deprecations_dep0006_child_process_options_customfds" id="deprecations_dep0006_child_process_options_customfds">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.14</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v0.5.11</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</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 <code>cluster</code> <code>worker.suicide</code> with <code>worker.exitedAfterDisconnect</code><span><a class="mark" href="#deprecations_dep0007_replace_cluster_worker_suicide_with_worker_exitedafterdisconnect" id="deprecations_dep0007_replace_cluster_worker_suicide_with_worker_exitedafterdisconnect">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>In an earlier version of the Node.js <code>cluster</code>, a boolean property with the name
<code>suicide</code> was added to the <code>Worker</code> object. The intent of this property was to
provide an indication of how and why the <code>Worker</code> instance exited. In Node.js
6.0.0, the old property was deprecated and replaced with a new
<a href="#cluster_worker_exitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a> property. The old property name did not
precisely describe the actual semantics and was unnecessarily emotion-laden.</p>
<p><a id="DEP0008"></a></p>
<h3>DEP0008: <code>require('constants')</code><span><a class="mark" href="#deprecations_dep0008_require_constants" id="deprecations_dep0008_require_constants">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>constants</code> module is deprecated. When requiring access to constants
relevant to specific Node.js builtin modules, developers should instead refer
to the <code>constants</code> property exposed by the relevant module. For instance,
<code>require('fs').constants</code> and <code>require('os').constants</code>.</p>
<p><a id="DEP0009"></a></p>
<h3>DEP0009: <code>crypto.pbkdf2</code> without digest<span><a class="mark" href="#deprecations_dep0009_crypto_pbkdf2_without_digest" id="deprecations_dep0009_crypto_pbkdf2_without_digest">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation (for <code>digest === null</code>).</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>End-of-Life (for <code>digest === undefined</code>).</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Runtime deprecation (for <code>digest === undefined</code>).</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Use of the <a href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback"><code>crypto.pbkdf2()</code></a> API without specifying a digest was deprecated
in Node.js 6.0 because the method defaulted to using the non-recommended
<code>'SHA1'</code> digest. Previously, a deprecation warning was printed. Starting in
Node.js 8.0.0, calling <code>crypto.pbkdf2()</code> or <code>crypto.pbkdf2Sync()</code> with
<code>digest</code> set to <code>undefined</code> will throw a <code>TypeError</code>.</p>
<p>Beginning in Node.js v11.0.0, calling these functions with <code>digest</code> set to
<code>null</code> will print a deprecation warning to align with the behavior when <code>digest</code>
is <code>undefined</code>.</p>
<p><a id="DEP0010"></a></p>
<h3>DEP0010: <code>crypto.createCredentials</code><span><a class="mark" href="#deprecations_dep0010_crypto_createcredentials" id="deprecations_dep0010_crypto_createcredentials">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>crypto.createCredentials()</code> API was removed. Please use
<a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> instead.</p>
<p><a id="DEP0011"></a></p>
<h3>DEP0011: <code>crypto.Credentials</code><span><a class="mark" href="#deprecations_dep0011_crypto_credentials" id="deprecations_dep0011_crypto_credentials">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>crypto.Credentials</code> class was removed. Please use <a href="#tls_tls_createsecurecontext_options"><code>tls.SecureContext</code></a>
instead.</p>
<p><a id="DEP0012"></a></p>
<h3>DEP0012: <code>Domain.dispose</code><span><a class="mark" href="#deprecations_dep0012_domain_dispose" id="deprecations_dep0012_domain_dispose">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.7</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>Domain.dispose()</code> has been removed. Recover from failed I/O actions
explicitly via error event handlers set on the domain instead.</p>
<p><a id="DEP0013"></a></p>
<h3>DEP0013: <code>fs</code> asynchronous function without callback<span><a class="mark" href="#deprecations_dep0013_fs_asynchronous_function_without_callback" id="deprecations_dep0013_fs_asynchronous_function_without_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Calling an asynchronous function without a callback throws a <code>TypeError</code>
in Node.js 10.0.0 onwards. See <a href="https://github.com/nodejs/node/pull/12562">https://github.com/nodejs/node/pull/12562</a>.</p>
<p><a id="DEP0014"></a></p>
<h3>DEP0014: <code>fs.read</code> legacy String interface<span><a class="mark" href="#deprecations_dep0014_fs_read_legacy_string_interface" id="deprecations_dep0014_fs_read_legacy_string_interface">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.1.96</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <a href="#fs_fs_read_fd_buffer_offset_length_position_callback"><code>fs.read()</code></a> legacy <code>String</code> interface is deprecated. Use the <code>Buffer</code>
API as mentioned in the documentation instead.</p>
<p><a id="DEP0015"></a></p>
<h3>DEP0015: <code>fs.readSync</code> legacy String interface<span><a class="mark" href="#deprecations_dep0015_fs_readsync_legacy_string_interface" id="deprecations_dep0015_fs_readsync_legacy_string_interface">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.1.96</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <a href="#fs_fs_readsync_fd_buffer_offset_length_position"><code>fs.readSync()</code></a> legacy <code>String</code> interface is deprecated. Use the
<code>Buffer</code> API as mentioned in the documentation instead.</p>
<p><a id="DEP0016"></a></p>
<h3>DEP0016: <code>GLOBAL</code>/<code>root</code><span><a class="mark" href="#deprecations_dep0016_global_root" id="deprecations_dep0016_global_root">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>GLOBAL</code> and <code>root</code> aliases for the <code>global</code> property are deprecated
and should no longer be used.</p>
<p><a id="DEP0017"></a></p>
<h3>DEP0017: <code>Intl.v8BreakIterator</code><span><a class="mark" href="#deprecations_dep0017_intl_v8breakiterator" id="deprecations_dep0017_intl_v8breakiterator">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>Intl.v8BreakIterator</code> was a non-standard extension and has been removed.
See <a href="https://github.com/tc39/proposal-intl-segmenter"><code>Intl.Segmenter</code></a>.</p>
<p><a id="DEP0018"></a></p>
<h3>DEP0018: Unhandled promise rejections<span><a class="mark" href="#deprecations_dep0018_unhandled_promise_rejections" id="deprecations_dep0018_unhandled_promise_rejections">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Unhandled promise rejections are deprecated. In the future, promise rejections
that are not handled will terminate the Node.js process with a non-zero exit
code.</p>
<p><a id="DEP0019"></a></p>
<h3>DEP0019: <code>require('.')</code> resolved outside directory<span><a class="mark" href="#deprecations_dep0019_require_resolved_outside_directory" id="deprecations_dep0019_require_resolved_outside_directory">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Removed functionality.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v1.8.1</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>In certain cases, <code>require('.')</code> could resolve outside the package directory.
This behavior has been removed.</p>
<p><a id="DEP0020"></a></p>
<h3>DEP0020: <code>Server.connections</code><span><a class="mark" href="#deprecations_dep0020_server_connections" id="deprecations_dep0020_server_connections">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.9.7</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <a href="#net_server_connections"><code>Server.connections</code></a> property is deprecated. Please use the
<a href="#net_server_getconnections_callback"><code>Server.getConnections()</code></a> method instead.</p>
<p><a id="DEP0021"></a></p>
<h3>DEP0021: <code>Server.listenFD</code><span><a class="mark" href="#deprecations_dep0021_server_listenfd" id="deprecations_dep0021_server_listenfd">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.7.12</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>Server.listenFD()</code> method was deprecated and removed. Please use
<a href="#net_server_listen_handle_backlog_callback"><code>Server.listen({fd: &#x3C;number>})</code></a> instead.</p>
<p><a id="DEP0022"></a></p>
<h3>DEP0022: <code>os.tmpDir()</code><span><a class="mark" href="#deprecations_dep0022_os_tmpdir" id="deprecations_dep0022_os_tmpdir">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>os.tmpDir()</code> API is deprecated. Please use <a href="#os_os_tmpdir"><code>os.tmpdir()</code></a> instead.</p>
<p><a id="DEP0023"></a></p>
<h3>DEP0023: <code>os.getNetworkInterfaces()</code><span><a class="mark" href="#deprecations_dep0023_os_getnetworkinterfaces" id="deprecations_dep0023_os_getnetworkinterfaces">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>os.getNetworkInterfaces()</code> method is deprecated. Please use the
<a href="#os_os_networkinterfaces"><code>os.networkInterfaces()</code></a> method instead.</p>
<p><a id="DEP0024"></a></p>
<h3>DEP0024: <code>REPLServer.prototype.convertToContext()</code><span><a class="mark" href="#deprecations_dep0024_replserver_prototype_converttocontext" id="deprecations_dep0024_replserver_prototype_converttocontext">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>REPLServer.prototype.convertToContext()</code> API has been removed.</p>
<p><a id="DEP0025"></a></p>
<h3>DEP0025: <code>require('sys')</code><span><a class="mark" href="#deprecations_dep0025_require_sys" id="deprecations_dep0025_require_sys">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>sys</code> module is deprecated. Please use the <a href="util.html"><code>util</code></a> module instead.</p>
<p><a id="DEP0026"></a></p>
<h3>DEP0026: <code>util.print()</code><span><a class="mark" href="#deprecations_dep0026_util_print" id="deprecations_dep0026_util_print">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>util.print()</code> has been removed. Please use <a href="#console_console_log_data_args"><code>console.log()</code></a> instead.</p>
<p><a id="DEP0027"></a></p>
<h3>DEP0027: <code>util.puts()</code><span><a class="mark" href="#deprecations_dep0027_util_puts" id="deprecations_dep0027_util_puts">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>util.puts()</code> has been removed. Please use <a href="#console_console_log_data_args"><code>console.log()</code></a> instead.</p>
<p><a id="DEP0028"></a></p>
<h3>DEP0028: <code>util.debug()</code><span><a class="mark" href="#deprecations_dep0028_util_debug" id="deprecations_dep0028_util_debug">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>util.debug()</code> has been removed. Please use <a href="#console_console_error_data_args"><code>console.error()</code></a> instead.</p>
<p><a id="DEP0029"></a></p>
<h3>DEP0029: <code>util.error()</code><span><a class="mark" href="#deprecations_dep0029_util_error" id="deprecations_dep0029_util_error">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>util.error()</code> has been removed. Please use <a href="#console_console_error_data_args"><code>console.error()</code></a> instead.</p>
<p><a id="DEP0030"></a></p>
<h3>DEP0030: <code>SlowBuffer</code><span><a class="mark" href="#deprecations_dep0030_slowbuffer" id="deprecations_dep0030_slowbuffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#buffer_class_slowbuffer"><code>SlowBuffer</code></a> class is deprecated. Please use
<a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow(size)</code></a> instead.</p>
<p><a id="DEP0031"></a></p>
<h3>DEP0031: <code>ecdh.setPublicKey()</code><span><a class="mark" href="#deprecations_dep0031_ecdh_setpublickey" id="deprecations_dep0031_ecdh_setpublickey">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v5.2.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#crypto_ecdh_setpublickey_publickey_encoding"><code>ecdh.setPublicKey()</code></a> method is now deprecated as its inclusion in the
API is not useful.</p>
<p><a id="DEP0032"></a></p>
<h3>DEP0032: <code>domain</code> module<span><a class="mark" href="#deprecations_dep0032_domain_module" id="deprecations_dep0032_domain_module">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v1.4.2</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="domain.html"><code>domain</code></a> module is deprecated and should not be used.</p>
<p><a id="DEP0033"></a></p>
<h3>DEP0033: <code>EventEmitter.listenerCount()</code><span><a class="mark" href="#deprecations_dep0033_eventemitter_listenercount" id="deprecations_dep0033_eventemitter_listenercount">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.2.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#events_eventemitter_listenercount_emitter_eventname"><code>EventEmitter.listenerCount(emitter, eventName)</code></a> API is
deprecated. Please use <a href="#events_emitter_listenercount_eventname"><code>emitter.listenerCount(eventName)</code></a> instead.</p>
<p><a id="DEP0034"></a></p>
<h3>DEP0034: <code>fs.exists(path, callback)</code><span><a class="mark" href="#deprecations_dep0034_fs_exists_path_callback" id="deprecations_dep0034_fs_exists_path_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#fs_fs_exists_path_callback"><code>fs.exists(path, callback)</code></a> API is deprecated. Please use
<a href="#fs_fs_stat_path_options_callback"><code>fs.stat()</code></a> or <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a> instead.</p>
<p><a id="DEP0035"></a></p>
<h3>DEP0035: <code>fs.lchmod(path, mode, callback)</code><span><a class="mark" href="#deprecations_dep0035_fs_lchmod_path_mode_callback" id="deprecations_dep0035_fs_lchmod_path_mode_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#fs_fs_lchmod_path_mode_callback"><code>fs.lchmod(path, mode, callback)</code></a> API is deprecated.</p>
<p><a id="DEP0036"></a></p>
<h3>DEP0036: <code>fs.lchmodSync(path, mode)</code><span><a class="mark" href="#deprecations_dep0036_fs_lchmodsync_path_mode" id="deprecations_dep0036_fs_lchmodsync_path_mode">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#fs_fs_lchmodsync_path_mode"><code>fs.lchmodSync(path, mode)</code></a> API is deprecated.</p>
<p><a id="DEP0037"></a></p>
<h3>DEP0037: <code>fs.lchown(path, uid, gid, callback)</code><span><a class="mark" href="#deprecations_dep0037_fs_lchown_path_uid_gid_callback" id="deprecations_dep0037_fs_lchown_path_uid_gid_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.6.0</td>
<td><p>Deprecation revoked.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Deprecation revoked</p>
<p>The <a href="#fs_fs_lchown_path_uid_gid_callback"><code>fs.lchown(path, uid, gid, callback)</code></a> API was deprecated. The
deprecation was revoked because the requisite supporting APIs were added in
libuv.</p>
<p><a id="DEP0038"></a></p>
<h3>DEP0038: <code>fs.lchownSync(path, uid, gid)</code><span><a class="mark" href="#deprecations_dep0038_fs_lchownsync_path_uid_gid" id="deprecations_dep0038_fs_lchownsync_path_uid_gid">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.6.0</td>
<td><p>Deprecation revoked.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Deprecation revoked</p>
<p>The <a href="#fs_fs_lchownsync_path_uid_gid"><code>fs.lchownSync(path, uid, gid)</code></a> API was deprecated. The deprecation was
revoked because the requisite supporting APIs were added in libuv.</p>
<p><a id="DEP0039"></a></p>
<h3>DEP0039: <code>require.extensions</code><span><a class="mark" href="#deprecations_dep0039_require_extensions" id="deprecations_dep0039_require_extensions">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.10.6</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#modules_require_extensions"><code>require.extensions</code></a> property is deprecated.</p>
<p><a id="DEP0040"></a></p>
<h3>DEP0040: <code>punycode</code> module<span><a class="mark" href="#deprecations_dep0040_punycode_module" id="deprecations_dep0040_punycode_module">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="punycode.html"><code>punycode</code></a> module is deprecated. Please use a userland alternative
instead.</p>
<p><a id="DEP0041"></a></p>
<h3>DEP0041: <code>NODE_REPL_HISTORY_FILE</code> environment variable<span><a class="mark" href="#deprecations_dep0041_node_repl_history_file_environment_variable" id="deprecations_dep0041_node_repl_history_file_environment_variable">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>NODE_REPL_HISTORY_FILE</code> environment variable was removed. Please use
<code>NODE_REPL_HISTORY</code> instead.</p>
<p><a id="DEP0042"></a></p>
<h3>DEP0042: <code>tls.CryptoStream</code><span><a class="mark" href="#deprecations_dep0042_tls_cryptostream" id="deprecations_dep0042_tls_cryptostream">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <a href="#tls_class_cryptostream"><code>tls.CryptoStream</code></a> class was removed. Please use
<a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</p>
<p><a id="DEP0043"></a></p>
<h3>DEP0043: <code>tls.SecurePair</code><span><a class="mark" href="#deprecations_dep0043_tls_securepair" id="deprecations_dep0043_tls_securepair">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p>Deprecation revoked.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#tls_class_securepair"><code>tls.SecurePair</code></a> class is deprecated. Please use
<a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</p>
<p><a id="DEP0044"></a></p>
<h3>DEP0044: <code>util.isArray()</code><span><a class="mark" href="#deprecations_dep0044_util_isarray" id="deprecations_dep0044_util_isarray">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isarray_object"><code>util.isArray()</code></a> API is deprecated. Please use <code>Array.isArray()</code>
instead.</p>
<p><a id="DEP0045"></a></p>
<h3>DEP0045: <code>util.isBoolean()</code><span><a class="mark" href="#deprecations_dep0045_util_isboolean" id="deprecations_dep0045_util_isboolean">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isboolean_object"><code>util.isBoolean()</code></a> API is deprecated.</p>
<p><a id="DEP0046"></a></p>
<h3>DEP0046: <code>util.isBuffer()</code><span><a class="mark" href="#deprecations_dep0046_util_isbuffer" id="deprecations_dep0046_util_isbuffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isbuffer_object"><code>util.isBuffer()</code></a> API is deprecated. Please use
<a href="#buffer_class_method_buffer_isbuffer_obj"><code>Buffer.isBuffer()</code></a> instead.</p>
<p><a id="DEP0047"></a></p>
<h3>DEP0047: <code>util.isDate()</code><span><a class="mark" href="#deprecations_dep0047_util_isdate" id="deprecations_dep0047_util_isdate">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isdate_object"><code>util.isDate()</code></a> API is deprecated.</p>
<p><a id="DEP0048"></a></p>
<h3>DEP0048: <code>util.isError()</code><span><a class="mark" href="#deprecations_dep0048_util_iserror" id="deprecations_dep0048_util_iserror">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_iserror_object"><code>util.isError()</code></a> API is deprecated.</p>
<p><a id="DEP0049"></a></p>
<h3>DEP0049: <code>util.isFunction()</code><span><a class="mark" href="#deprecations_dep0049_util_isfunction" id="deprecations_dep0049_util_isfunction">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isfunction_object"><code>util.isFunction()</code></a> API is deprecated.</p>
<p><a id="DEP0050"></a></p>
<h3>DEP0050: <code>util.isNull()</code><span><a class="mark" href="#deprecations_dep0050_util_isnull" id="deprecations_dep0050_util_isnull">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isnull_object"><code>util.isNull()</code></a> API is deprecated.</p>
<p><a id="DEP0051"></a></p>
<h3>DEP0051: <code>util.isNullOrUndefined()</code><span><a class="mark" href="#deprecations_dep0051_util_isnullorundefined" id="deprecations_dep0051_util_isnullorundefined">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isnullorundefined_object"><code>util.isNullOrUndefined()</code></a> API is deprecated.</p>
<p><a id="DEP0052"></a></p>
<h3>DEP0052: <code>util.isNumber()</code><span><a class="mark" href="#deprecations_dep0052_util_isnumber" id="deprecations_dep0052_util_isnumber">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isnumber_object"><code>util.isNumber()</code></a> API is deprecated.</p>
<p><a id="DEP0053"></a></p>
<h3>DEP0053 <code>util.isObject()</code><span><a class="mark" href="#deprecations_dep0053_util_isobject" id="deprecations_dep0053_util_isobject">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isobject_object"><code>util.isObject()</code></a> API is deprecated.</p>
<p><a id="DEP0054"></a></p>
<h3>DEP0054: <code>util.isPrimitive()</code><span><a class="mark" href="#deprecations_dep0054_util_isprimitive" id="deprecations_dep0054_util_isprimitive">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isprimitive_object"><code>util.isPrimitive()</code></a> API is deprecated.</p>
<p><a id="DEP0055"></a></p>
<h3>DEP0055: <code>util.isRegExp()</code><span><a class="mark" href="#deprecations_dep0055_util_isregexp" id="deprecations_dep0055_util_isregexp">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isregexp_object"><code>util.isRegExp()</code></a> API is deprecated.</p>
<p><a id="DEP0056"></a></p>
<h3>DEP0056: <code>util.isString()</code><span><a class="mark" href="#deprecations_dep0056_util_isstring" id="deprecations_dep0056_util_isstring">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isstring_object"><code>util.isString()</code></a> API is deprecated.</p>
<p><a id="DEP0057"></a></p>
<h3>DEP0057: <code>util.isSymbol()</code><span><a class="mark" href="#deprecations_dep0057_util_issymbol" id="deprecations_dep0057_util_issymbol">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_issymbol_object"><code>util.isSymbol()</code></a> API is deprecated.</p>
<p><a id="DEP0058"></a></p>
<h3>DEP0058: <code>util.isUndefined()</code><span><a class="mark" href="#deprecations_dep0058_util_isundefined" id="deprecations_dep0058_util_isundefined">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.8.6, v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v3.3.1, v4.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_isundefined_object"><code>util.isUndefined()</code></a> API is deprecated.</p>
<p><a id="DEP0059"></a></p>
<h3>DEP0059: <code>util.log()</code><span><a class="mark" href="#deprecations_dep0059_util_log" id="deprecations_dep0059_util_log">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_log_string"><code>util.log()</code></a> API is deprecated.</p>
<p><a id="DEP0060"></a></p>
<h3>DEP0060: <code>util._extend()</code><span><a class="mark" href="#deprecations_dep0060_util_extend" id="deprecations_dep0060_util_extend">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#util_util_extend_target_source"><code>util._extend()</code></a> API is deprecated.</p>
<p><a id="DEP0061"></a></p>
<h3>DEP0061: <code>fs.SyncWriteStream</code><span><a class="mark" href="#deprecations_dep0061_fs_syncwritestream" id="deprecations_dep0061_fs_syncwritestream">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>fs.SyncWriteStream</code> class was never intended to be a publicly accessible
API and has been removed. No alternative API is available. Please use a userland
alternative.</p>
<p><a id="DEP0062"></a></p>
<h3>DEP0062: <code>node --debug</code><span><a class="mark" href="#deprecations_dep0062_node_debug" id="deprecations_dep0062_node_debug">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>--debug</code> activates the legacy V8 debugger interface, which was removed as
of V8 5.8. It is replaced by Inspector which is activated with <code>--inspect</code>
instead.</p>
<p><a id="DEP0063"></a></p>
<h3>DEP0063: <code>ServerResponse.prototype.writeHeader()</code><span><a class="mark" href="#deprecations_dep0063_serverresponse_prototype_writeheader" id="deprecations_dep0063_serverresponse_prototype_writeheader">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>http</code> module <code>ServerResponse.prototype.writeHeader()</code> API is
deprecated. Please use <code>ServerResponse.prototype.writeHead()</code> instead.</p>
<p>The <code>ServerResponse.prototype.writeHeader()</code> method was never documented as an
officially supported API.</p>
<p><a id="DEP0064"></a></p>
<h3>DEP0064: <code>tls.createSecurePair()</code><span><a class="mark" href="#deprecations_dep0064_tls_createsecurepair" id="deprecations_dep0064_tls_createsecurepair">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p>Deprecation revoked.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>tls.createSecurePair()</code> API was deprecated in documentation in Node.js
0.11.3. Users should use <code>tls.Socket</code> instead.</p>
<p><a id="DEP0065"></a></p>
<h3>DEP0065: <code>repl.REPL_MODE_MAGIC</code> and <code>NODE_REPL_MODE=magic</code><span><a class="mark" href="#deprecations_dep0065_repl_repl_mode_magic_and_node_repl_mode_magic" id="deprecations_dep0065_repl_repl_mode_magic_and_node_repl_mode_magic">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>repl</code> module's <code>REPL_MODE_MAGIC</code> constant, used for <code>replMode</code> option, has
been removed. Its behavior has been functionally identical to that of
<code>REPL_MODE_SLOPPY</code> since Node.js 6.0.0, when V8 5.0 was imported. Please use
<code>REPL_MODE_SLOPPY</code> instead.</p>
<p>The <code>NODE_REPL_MODE</code> environment variable is used to set the underlying
<code>replMode</code> of an interactive <code>node</code> session. Its value, <code>magic</code>, is also
removed. Please use <code>sloppy</code> instead.</p>
<p><a id="DEP0066"></a></p>
<h3>DEP0066: <code>OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames</code><span><a class="mark" href="#deprecations_dep0066_outgoingmessage_prototype_headers_outgoingmessage_prototype_headernames" id="deprecations_dep0066_outgoingmessage_prototype_headers_outgoingmessage_prototype_headernames">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>http</code> module <code>OutgoingMessage.prototype._headers</code> and
<code>OutgoingMessage.prototype._headerNames</code> properties are deprecated. Use one of
the public methods (e.g. <code>OutgoingMessage.prototype.getHeader()</code>,
<code>OutgoingMessage.prototype.getHeaders()</code>,
<code>OutgoingMessage.prototype.getHeaderNames()</code>,
<code>OutgoingMessage.prototype.hasHeader()</code>,
<code>OutgoingMessage.prototype.removeHeader()</code>,
<code>OutgoingMessage.prototype.setHeader()</code>) for working with outgoing headers.</p>
<p>The <code>OutgoingMessage.prototype._headers</code> and
<code>OutgoingMessage.prototype._headerNames</code> properties were never documented as
officially supported properties.</p>
<p><a id="DEP0067"></a></p>
<h3>DEP0067: <code>OutgoingMessage.prototype._renderHeaders</code><span><a class="mark" href="#deprecations_dep0067_outgoingmessage_prototype_renderheaders" id="deprecations_dep0067_outgoingmessage_prototype_renderheaders">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>http</code> module <code>OutgoingMessage.prototype._renderHeaders()</code> API is
deprecated.</p>
<p>The <code>OutgoingMessage.prototype._renderHeaders</code> property was never documented as
an officially supported API.</p>
<p><a id="DEP0068"></a></p>
<h3>DEP0068: <code>node debug</code><span><a class="mark" href="#deprecations_dep0068_node_debug" id="deprecations_dep0068_node_debug">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>node debug</code> corresponds to the legacy CLI debugger which has been replaced with
a V8-inspector based CLI debugger available through <code>node inspect</code>.</p>
<p><a id="DEP0069"></a></p>
<h3>DEP0069: <code>vm.runInDebugContext(string)</code><span><a class="mark" href="#deprecations_dep0069_vm_runindebugcontext_string" id="deprecations_dep0069_vm_runindebugcontext_string">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>DebugContext has been removed in V8 and is not available in Node.js 10+.</p>
<p>DebugContext was an experimental API.</p>
<p><a id="DEP0070"></a></p>
<h3>DEP0070: <code>async_hooks.currentId()</code><span><a class="mark" href="#deprecations_dep0070_async_hooks_currentid" id="deprecations_dep0070_async_hooks_currentid">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.2.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>async_hooks.currentId()</code> was renamed to <code>async_hooks.executionAsyncId()</code> for
clarity.</p>
<p>This change was made while <code>async_hooks</code> was an experimental API.</p>
<p><a id="DEP0071"></a></p>
<h3>DEP0071: <code>async_hooks.triggerId()</code><span><a class="mark" href="#deprecations_dep0071_async_hooks_triggerid" id="deprecations_dep0071_async_hooks_triggerid">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.2.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>async_hooks.triggerId()</code> was renamed to <code>async_hooks.triggerAsyncId()</code> for
clarity.</p>
<p>This change was made while <code>async_hooks</code> was an experimental API.</p>
<p><a id="DEP0072"></a></p>
<h3>DEP0072: <code>async_hooks.AsyncResource.triggerId()</code><span><a class="mark" href="#deprecations_dep0072_async_hooks_asyncresource_triggerid" id="deprecations_dep0072_async_hooks_asyncresource_triggerid">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.2.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>async_hooks.AsyncResource.triggerId()</code> was renamed to
<code>async_hooks.AsyncResource.triggerAsyncId()</code> for clarity.</p>
<p>This change was made while <code>async_hooks</code> was an experimental API.</p>
<p><a id="DEP0073"></a></p>
<h3>DEP0073: Several internal properties of <code>net.Server</code><span><a class="mark" href="#deprecations_dep0073_several_internal_properties_of_net_server" id="deprecations_dep0073_several_internal_properties_of_net_server">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Accessing several internal, undocumented properties of <code>net.Server</code> instances
with inappropriate names is deprecated.</p>
<p>As the original API was undocumented and not generally useful for non-internal
code, no replacement API is provided.</p>
<p><a id="DEP0074"></a></p>
<h3>DEP0074: <code>REPLServer.bufferedCommand</code><span><a class="mark" href="#deprecations_dep0074_replserver_bufferedcommand" id="deprecations_dep0074_replserver_bufferedcommand">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>REPLServer.bufferedCommand</code> property was deprecated in favor of
<a href="#repl_replserver_clearbufferedcommand"><code>REPLServer.clearBufferedCommand()</code></a>.</p>
<p><a id="DEP0075"></a></p>
<h3>DEP0075: <code>REPLServer.parseREPLKeyword()</code><span><a class="mark" href="#deprecations_dep0075_replserver_parsereplkeyword" id="deprecations_dep0075_replserver_parsereplkeyword">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>REPLServer.parseREPLKeyword()</code> was removed from userland visibility.</p>
<p><a id="DEP0076"></a></p>
<h3>DEP0076: <code>tls.parseCertString()</code><span><a class="mark" href="#deprecations_dep0076_tls_parsecertstring" id="deprecations_dep0076_tls_parsecertstring">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v8.6.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>tls.parseCertString()</code> is a trivial parsing helper that was made public by
mistake. This function can usually be replaced with:</p>
<pre><code class="language-js">const querystring = require('querystring');
querystring.parse(str, '\n', '=');
</code></pre>
<p>This function is not completely equivalent to <code>querystring.parse()</code>. One
difference is that <code>querystring.parse()</code> does url decoding:</p>
<pre><code class="language-console">> 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: <code>Module._debug()</code><span><a class="mark" href="#deprecations_dep0077_module_debug" id="deprecations_dep0077_module_debug">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>Module._debug()</code> is deprecated.</p>
<p>The <code>Module._debug()</code> function was never documented as an officially
supported API.</p>
<p><a id="DEP0078"></a></p>
<h3>DEP0078: <code>REPLServer.turnOffEditorMode()</code><span><a class="mark" href="#deprecations_dep0078_replserver_turnoffeditormode" id="deprecations_dep0078_replserver_turnoffeditormode">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>REPLServer.turnOffEditorMode()</code> was removed from userland visibility.</p>
<p><a id="DEP0079"></a></p>
<h3>DEP0079: Custom inspection function on objects via <code>.inspect()</code><span><a class="mark" href="#deprecations_dep0079_custom_inspection_function_on_objects_via_inspect" id="deprecations_dep0079_custom_inspection_function_on_objects_via_inspect">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v8.7.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Using a property named <code>inspect</code> on an object to specify a custom inspection
function for <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> is deprecated. Use <a href="#util_util_inspect_custom"><code>util.inspect.custom</code></a>
instead. For backward compatibility with Node.js prior to version 6.4.0, both
may be specified.</p>
<p><a id="DEP0080"></a></p>
<h3>DEP0080: <code>path._makeLong()</code><span><a class="mark" href="#deprecations_dep0080_path_makelong" id="deprecations_dep0080_path_makelong">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The internal <code>path._makeLong()</code> was not intended for public use. However,
userland modules have found it useful. The internal API is deprecated
and replaced with an identical, public <code>path.toNamespacedPath()</code> method.</p>
<p><a id="DEP0081"></a></p>
<h3>DEP0081: <code>fs.truncate()</code> 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>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>fs.truncate()</code> <code>fs.truncateSync()</code> usage with a file descriptor is
deprecated. Please use <code>fs.ftruncate()</code> or <code>fs.ftruncateSync()</code> to work with
file descriptors.</p>
<p><a id="DEP0082"></a></p>
<h3>DEP0082: <code>REPLServer.prototype.memory()</code><span><a class="mark" href="#deprecations_dep0082_replserver_prototype_memory" id="deprecations_dep0082_replserver_prototype_memory">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>REPLServer.prototype.memory()</code> is only necessary for the internal mechanics of
the <code>REPLServer</code> itself. Do not use this function.</p>
<p><a id="DEP0083"></a></p>
<h3>DEP0083: Disabling ECDH by setting <code>ecdhCurve</code> to <code>false</code><span><a class="mark" href="#deprecations_dep0083_disabling_ecdh_by_setting_ecdhcurve_to_false" id="deprecations_dep0083_disabling_ecdh_by_setting_ecdhcurve_to_false">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v9.2.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life.</p>
<p>The <code>ecdhCurve</code> option to <code>tls.createSecureContext()</code> and <code>tls.TLSSocket</code> could
be set to <code>false</code> to disable ECDH entirely on the server only. This mode was
deprecated in preparation for migrating to OpenSSL 1.1.0 and consistency with
the client and is now unsupported. Use the <code>ciphers</code> parameter instead.</p>
<p><a id="DEP0084"></a></p>
<h3>DEP0084: requiring bundled internal dependencies<span><a class="mark" href="#deprecations_dep0084_requiring_bundled_internal_dependencies" id="deprecations_dep0084_requiring_bundled_internal_dependencies">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>This functionality has been removed.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Since Node.js versions 4.4.0 and 5.2.0, several modules only intended for
internal usage were mistakenly exposed to user code through <code>require()</code>. These
modules were:</p>
<ul>
<li><code>v8/tools/codemap</code></li>
<li><code>v8/tools/consarray</code></li>
<li><code>v8/tools/csvparser</code></li>
<li><code>v8/tools/logreader</code></li>
<li><code>v8/tools/profile_view</code></li>
<li><code>v8/tools/profile</code></li>
<li><code>v8/tools/SourceMap</code></li>
<li><code>v8/tools/splaytree</code></li>
<li><code>v8/tools/tickprocessor-driver</code></li>
<li><code>v8/tools/tickprocessor</code></li>
<li><code>node-inspect/lib/_inspect</code> (from 7.6.0)</li>
<li><code>node-inspect/lib/internal/inspect_client</code> (from 7.6.0)</li>
<li><code>node-inspect/lib/internal/inspect_repl</code> (from 7.6.0)</li>
</ul>
<p>The <code>v8/*</code> modules do not have any exports, and if not imported in a specific
order would in fact throw errors. As such there are virtually no legitimate use
cases for importing them through <code>require()</code>.</p>
<p>On the other hand, <code>node-inspect</code> may be installed locally through a package
manager, as it is published on the npm registry under the same name. No source
code modification is necessary if that is done.</p>
<p><a id="DEP0085"></a></p>
<h3>DEP0085: AsyncHooks sensitive API<span><a class="mark" href="#deprecations_dep0085_asynchooks_sensitive_api" id="deprecations_dep0085_asynchooks_sensitive_api">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.10.0, v9.4.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The AsyncHooks sensitive API was never documented and had various minor issues.
Use the <code>AsyncResource</code> API instead. See
<a href="https://github.com/nodejs/node/issues/15572">https://github.com/nodejs/node/issues/15572</a>.</p>
<p><a id="DEP0086"></a></p>
<h3>DEP0086: Remove <code>runInAsyncIdScope</code><span><a class="mark" href="#deprecations_dep0086_remove_runinasyncidscope" id="deprecations_dep0086_remove_runinasyncidscope">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v8.10.0, v9.4.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>runInAsyncIdScope</code> doesn't emit the <code>'before'</code> or <code>'after'</code> event and can thus
cause a lot of issues. See <a href="https://github.com/nodejs/node/issues/14328">https://github.com/nodejs/node/issues/14328</a>.</p>
<p><a id="DEP0089"></a></p>
<h3>DEP0089: <code>require('assert')</code><span><a class="mark" href="#deprecations_dep0089_require_assert" id="deprecations_dep0089_require_assert">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.8.0</td>
<td><p>Deprecation revoked.</p></td></tr>
<tr><td>v9.9.0, v10.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Deprecation revoked</p>
<p>Importing assert directly was not recommended as the exposed functions use
loose equality checks. The deprecation was revoked because use of the <code>assert</code>
module is not discouraged, and the deprecation caused end user confusion.</p>
<p><a id="DEP0090"></a></p>
<h3>DEP0090: Invalid GCM authentication tag lengths<span><a class="mark" href="#deprecations_dep0090_invalid_gcm_authentication_tag_lengths" id="deprecations_dep0090_invalid_gcm_authentication_tag_lengths">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Node.js used to support all GCM authentication tag lengths which are accepted by
OpenSSL when calling <a href="#crypto_decipher_setauthtag_buffer"><code>decipher.setAuthTag()</code></a>. Beginning with Node.js
v11.0.0, only authentication tag lengths of 128, 120, 112, 104, 96, 64, and 32
bits are allowed. Authentication tags of other lengths are invalid per
<a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf">NIST SP 800-38D</a>.</p>
<p><a id="DEP0091"></a></p>
<h3>DEP0091: <code>crypto.DEFAULT_ENCODING</code><span><a class="mark" href="#deprecations_dep0091_crypto_default_encoding" id="deprecations_dep0091_crypto_default_encoding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <a href="#crypto_crypto_default_encoding"><code>crypto.DEFAULT_ENCODING</code></a> property is deprecated.</p>
<p><a id="DEP0092"></a></p>
<h3>DEP0092: Top-level <code>this</code> bound to <code>module.exports</code><span><a class="mark" href="#deprecations_dep0092_top_level_this_bound_to_module_exports" id="deprecations_dep0092_top_level_this_bound_to_module_exports">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Assigning properties to the top-level <code>this</code> as an alternative
to <code>module.exports</code> is deprecated. Developers should use <code>exports</code>
or <code>module.exports</code> instead.</p>
<p><a id="DEP0093"></a></p>
<h3>DEP0093: <code>crypto.fips</code> is deprecated and replaced.<span><a class="mark" href="#deprecations_dep0093_crypto_fips_is_deprecated_and_replaced" id="deprecations_dep0093_crypto_fips_is_deprecated_and_replaced">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#crypto_crypto_fips"><code>crypto.fips</code></a> property is deprecated. Please use <code>crypto.setFips()</code>
and <code>crypto.getFips()</code> instead.</p>
<p><a id="DEP0094"></a></p>
<h3>DEP0094: Using <code>assert.fail()</code> with more than one argument.<span><a class="mark" href="#deprecations_dep0094_using_assert_fail_with_more_than_one_argument" id="deprecations_dep0094_using_assert_fail_with_more_than_one_argument">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Using <code>assert.fail()</code> with more than one argument is deprecated. Use
<code>assert.fail()</code> with only one argument or use a different <code>assert</code> module
method.</p>
<p><a id="DEP0095"></a></p>
<h3>DEP0095: <code>timers.enroll()</code><span><a class="mark" href="#deprecations_dep0095_timers_enroll" id="deprecations_dep0095_timers_enroll">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>timers.enroll()</code> is deprecated. Please use the publicly documented
<a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a> or <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a> instead.</p>
<p><a id="DEP0096"></a></p>
<h3>DEP0096: <code>timers.unenroll()</code><span><a class="mark" href="#deprecations_dep0096_timers_unenroll" id="deprecations_dep0096_timers_unenroll">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>timers.unenroll()</code> is deprecated. Please use the publicly documented
<a href="#timers_cleartimeout_timeout"><code>clearTimeout()</code></a> or <a href="#timers_clearinterval_timeout"><code>clearInterval()</code></a> instead.</p>
<p><a id="DEP0097"></a></p>
<h3>DEP0097: <code>MakeCallback</code> with <code>domain</code> property<span><a class="mark" href="#deprecations_dep0097_makecallback_with_domain_property" id="deprecations_dep0097_makecallback_with_domain_property">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Users of <code>MakeCallback</code> that add the <code>domain</code> property to carry context,
should start using the <code>async_context</code> variant of <code>MakeCallback</code> or
<code>CallbackScope</code>, or the high-level <code>AsyncResource</code> class.</p>
<p><a id="DEP0098"></a></p>
<h3>DEP0098: AsyncHooks embedder <code>AsyncResource.emitBefore</code> and <code>AsyncResource.emitAfter</code> APIs<span><a class="mark" href="#deprecations_dep0098_asynchooks_embedder_asyncresource_emitbefore_and_asyncresource_emitafter_apis" id="deprecations_dep0098_asynchooks_embedder_asyncresource_emitbefore_and_asyncresource_emitafter_apis">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life</p></td></tr>
<tr><td>v8.12.0, v9.6.0, v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The embedded API provided by AsyncHooks exposes <code>.emitBefore()</code> and
<code>.emitAfter()</code> methods which are very easy to use incorrectly which can lead
to unrecoverable errors.</p>
<p>Use <a href="#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args"><code>asyncResource.runInAsyncScope()</code></a> API instead which provides a much
safer, and more convenient, alternative. See
<a href="https://github.com/nodejs/node/pull/18513">https://github.com/nodejs/node/pull/18513</a>.</p>
<p><a id="DEP0099"></a></p>
<h3>DEP0099: Async context-unaware <code>node::MakeCallback</code> C++ APIs<span><a class="mark" href="#deprecations_dep0099_async_context_unaware_node_makecallback_c_apis" id="deprecations_dep0099_async_context_unaware_node_makecallback_c_apis">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Compile-time deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Compile-time</p>
<p>Certain versions of <code>node::MakeCallback</code> APIs available to native modules are
deprecated. Please use the versions of the API that accept an <code>async_context</code>
parameter.</p>
<p><a id="DEP0100"></a></p>
<h3>DEP0100: <code>process.assert()</code><span><a class="mark" href="#deprecations_dep0100_process_assert" id="deprecations_dep0100_process_assert">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v0.3.7</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><code>process.assert()</code> is deprecated. Please use the <a href="assert.html"><code>assert</code></a> module instead.</p>
<p>This was never a documented feature.</p>
<p><a id="DEP0101"></a></p>
<h3>DEP0101: <code>--with-lttng</code><span><a class="mark" href="#deprecations_dep0101_with_lttng" id="deprecations_dep0101_with_lttng">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>--with-lttng</code> compile-time option has been removed.</p>
<p><a id="DEP0102"></a></p>
<h3>DEP0102: Using <code>noAssert</code> in <code>Buffer#(read|write)</code> operations.<span><a class="mark" href="#deprecations_dep0102_using_noassert_in_buffer_read_write_operations" id="deprecations_dep0102_using_noassert_in_buffer_read_write_operations">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>End-of-Life.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Using the <code>noAssert</code> argument has no functionality anymore. All input is going
to be verified, no matter if it is set to true or not. Skipping the verification
could lead to hard to find errors and crashes.</p>
<p><a id="DEP0103"></a></p>
<h3>DEP0103: <code>process.binding('util').is[...]</code> typechecks<span><a class="mark" href="#deprecations_dep0103_process_binding_util_is_typechecks" id="deprecations_dep0103_process_binding_util_is_typechecks">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.9.0</td>
<td><p>Superseded by <a href="#DEP0111">DEP0111</a>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a>)</p>
<p>Using <code>process.binding()</code> in general should be avoided. The type checking
methods in particular can be replaced by using <a href="#util_util_types"><code>util.types</code></a>.</p>
<p>This deprecation has been superseded by the deprecation of the
<code>process.binding()</code> API (<a href="#DEP0111">DEP0111</a>).</p>
<p><a id="DEP0104"></a></p>
<h3>DEP0104: <code>process.env</code> string coercion<span><a class="mark" href="#deprecations_dep0104_process_env_string_coercion" id="deprecations_dep0104_process_env_string_coercion">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a>)</p>
<p>When assigning a non-string property to <a href="#process_process_env"><code>process.env</code></a>, the assigned value is
implicitly converted to a string. This behavior is deprecated if the assigned
value is not a string, boolean, or number. In the future, such assignment may
result in a thrown error. Please convert the property to a string before
assigning it to <code>process.env</code>.</p>
<p><a id="DEP0105"></a></p>
<h3>DEP0105: <code>decipher.finaltol</code><span><a class="mark" href="#deprecations_dep0105_decipher_finaltol" id="deprecations_dep0105_decipher_finaltol">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>decipher.finaltol()</code> has never been documented and was an alias for
<a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a>. This API has been removed, and it is recommended to use
<a href="#crypto_decipher_final_outputencoding"><code>decipher.final()</code></a> instead.</p>
<p><a id="DEP0106"></a></p>
<h3>DEP0106: <code>crypto.createCipher</code> and <code>crypto.createDecipher</code><span><a class="mark" href="#deprecations_dep0106_crypto_createcipher_and_crypto_createdecipher" id="deprecations_dep0106_crypto_createcipher_and_crypto_createdecipher">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Using <a href="#crypto_crypto_createcipher_algorithm_password_options"><code>crypto.createCipher()</code></a> and <a href="#crypto_crypto_createdecipher_algorithm_password_options"><code>crypto.createDecipher()</code></a> should be
avoided as they use a weak key derivation function (MD5 with no salt) and static
initialization vectors. It is recommended to derive a key using
<a href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback"><code>crypto.pbkdf2()</code></a> or <a href="#crypto_crypto_scrypt_password_salt_keylen_options_callback"><code>crypto.scrypt()</code></a> and to use
<a href="#crypto_crypto_createcipheriv_algorithm_key_iv_options"><code>crypto.createCipheriv()</code></a> and <a href="#crypto_crypto_createdecipheriv_algorithm_key_iv_options"><code>crypto.createDecipheriv()</code></a> to obtain the
<a href="#crypto_class_cipher"><code>Cipher</code></a> and <a href="#crypto_class_decipher"><code>Decipher</code></a> objects respectively.</p>
<p><a id="DEP0107"></a></p>
<h3>DEP0107: <code>tls.convertNPNProtocols()</code><span><a class="mark" href="#deprecations_dep0107_tls_convertnpnprotocols" id="deprecations_dep0107_tls_convertnpnprotocols">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>This was an undocumented helper function not intended for use outside Node.js
core and obsoleted by the removal of NPN (Next Protocol Negotiation) support.</p>
<p><a id="DEP0108"></a></p>
<h3>DEP0108: <code>zlib.bytesRead</code><span><a class="mark" href="#deprecations_dep0108_zlib_bytesread" id="deprecations_dep0108_zlib_bytesread">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Deprecated alias for <a href="#zlib_zlib_byteswritten"><code>zlib.bytesWritten</code></a>. This original name was chosen
because it also made sense to interpret the value as the number of bytes
read by the engine, but is inconsistent with other streams in Node.js that
expose values under these names.</p>
<p><a id="DEP0109"></a></p>
<h3>DEP0109: <code>http</code>, <code>https</code>, and <code>tls</code> support for invalid URLs<span><a class="mark" href="#deprecations_dep0109_http_https_and_tls_support_for_invalid_urls" id="deprecations_dep0109_http_https_and_tls_support_for_invalid_urls">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Some previously supported (but strictly invalid) URLs were accepted through the
<a href="#http_http_request_options_callback"><code>http.request()</code></a>, <a href="#http_http_get_options_callback"><code>http.get()</code></a>, <a href="#https_https_request_options_callback"><code>https.request()</code></a>,
<a href="#https_https_get_options_callback"><code>https.get()</code></a>, and <a href="#tls_tls_checkserveridentity_hostname_cert"><code>tls.checkServerIdentity()</code></a> APIs because those were
accepted by the legacy <code>url.parse()</code> API. The mentioned APIs now use the WHATWG
URL parser that requires strictly valid URLs. Passing an invalid URL is
deprecated and support will be removed in the future.</p>
<p><a id="DEP0110"></a></p>
<h3>DEP0110: <code>vm.Script</code> cached data<span><a class="mark" href="#deprecations_dep0110_vm_script_cached_data" id="deprecations_dep0110_vm_script_cached_data">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.6.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>produceCachedData</code> option is deprecated. Use
<a href="#vm_script_createcacheddata"><code>script.createCachedData()</code></a> instead.</p>
<p><a id="DEP0111"></a></p>
<h3>DEP0111: <code>process.binding()</code><span><a class="mark" href="#deprecations_dep0111_process_binding" id="deprecations_dep0111_process_binding">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.12.0</td>
<td><p>Added support for <code>--pending-deprecation</code>.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a>)</p>
<p><code>process.binding()</code> is for use by Node.js internal code only.</p>
<p><a id="DEP0112"></a></p>
<h3>DEP0112: <code>dgram</code> private APIs<span><a class="mark" href="#deprecations_dep0112_dgram_private_apis" id="deprecations_dep0112_dgram_private_apis">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>dgram</code> module previously contained several APIs that were never meant to
accessed outside of Node.js core: <code>Socket.prototype._handle</code>,
<code>Socket.prototype._receiving</code>, <code>Socket.prototype._bindState</code>,
<code>Socket.prototype._queue</code>, <code>Socket.prototype._reuseAddr</code>,
<code>Socket.prototype._healthCheck()</code>, <code>Socket.prototype._stopReceiving()</code>, and
<code>dgram._createSocketHandle()</code>.</p>
<p><a id="DEP0113"></a></p>
<h3>DEP0113: <code>Cipher.setAuthTag()</code>, <code>Decipher.getAuthTag()</code><span><a class="mark" href="#deprecations_dep0113_cipher_setauthtag_decipher_getauthtag" id="deprecations_dep0113_cipher_setauthtag_decipher_getauthtag">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>Cipher.setAuthTag()</code> and <code>Decipher.getAuthTag()</code> are no longer available. They
were never documented and would throw when called.</p>
<p><a id="DEP0114"></a></p>
<h3>DEP0114: <code>crypto._toBuf()</code><span><a class="mark" href="#deprecations_dep0114_crypto_tobuf" id="deprecations_dep0114_crypto_tobuf">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>crypto._toBuf()</code> function was not designed to be used by modules outside
of Node.js core and was removed.</p>
<p><a id="DEP0115"></a></p>
<h3>DEP0115: <code>crypto.prng()</code>, <code>crypto.pseudoRandomBytes()</code>, <code>crypto.rng()</code><span><a class="mark" href="#deprecations_dep0115_crypto_prng_crypto_pseudorandombytes_crypto_rng" id="deprecations_dep0115_crypto_prng_crypto_pseudorandombytes_crypto_rng">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Added documentation-only deprecation with <code>--pending-deprecation</code> support.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a>)</p>
<p>In recent versions of Node.js, there is no difference between
<a href="#crypto_crypto_randombytes_size_callback"><code>crypto.randomBytes()</code></a> and <code>crypto.pseudoRandomBytes()</code>. The latter is
deprecated along with the undocumented aliases <code>crypto.prng()</code> and
<code>crypto.rng()</code> in favor of <a href="#crypto_crypto_randombytes_size_callback"><code>crypto.randomBytes()</code></a> and may be removed in a
future release.</p>
<p><a id="DEP0116"></a></p>
<h3>DEP0116: Legacy URL API<span><a class="mark" href="#deprecations_dep0116_legacy_url_api" id="deprecations_dep0116_legacy_url_api">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#url_legacy_url_api">Legacy URL API</a> is deprecated. This includes <a href="#url_url_format_urlobject"><code>url.format()</code></a>,
<a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>, <a href="#url_url_resolve_from_to"><code>url.resolve()</code></a>, and the <a href="#url_legacy_urlobject">legacy <code>urlObject</code></a>. Please
use the <a href="#url_the_whatwg_url_api">WHATWG URL API</a> instead.</p>
<p><a id="DEP0117"></a></p>
<h3>DEP0117: Native crypto handles<span><a class="mark" href="#deprecations_dep0117_native_crypto_handles" id="deprecations_dep0117_native_crypto_handles">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Previous versions of Node.js exposed handles to internal native objects through
the <code>_handle</code> property of the <code>Cipher</code>, <code>Decipher</code>, <code>DiffieHellman</code>,
<code>DiffieHellmanGroup</code>, <code>ECDH</code>, <code>Hash</code>, <code>Hmac</code>, <code>Sign</code>, and <code>Verify</code> classes.
The <code>_handle</code> property has been removed because improper use of the native
object can lead to crashing the application.</p>
<p><a id="DEP0118"></a></p>
<h3>DEP0118: <code>dns.lookup()</code> support for a falsy host name<span><a class="mark" href="#deprecations_dep0118_dns_lookup_support_for_a_falsy_host_name" id="deprecations_dep0118_dns_lookup_support_for_a_falsy_host_name">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Previous versions of Node.js supported <code>dns.lookup()</code> with a falsy host name
like <code>dns.lookup(false)</code> due to backward compatibility.
This behavior is undocumented and is thought to be unused in real world apps.
It will become an error in future versions of Node.js.</p>
<p><a id="DEP0119"></a></p>
<h3>DEP0119: <code>process.binding('uv').errname()</code> private API<span><a class="mark" href="#deprecations_dep0119_process_binding_uv_errname_private_api" id="deprecations_dep0119_process_binding_uv_errname_private_api">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a>)</p>
<p><code>process.binding('uv').errname()</code> is deprecated. Please use
<a href="#util_util_getsystemerrorname_err"><code>util.getSystemErrorName()</code></a> instead.</p>
<p><a id="DEP0120"></a></p>
<h3>DEP0120: Windows Performance Counter support<span><a class="mark" href="#deprecations_dep0120_windows_performance_counter_support" id="deprecations_dep0120_windows_performance_counter_support">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Windows Performance Counter support has been removed from Node.js. The
undocumented <code>COUNTER_NET_SERVER_CONNECTION()</code>,
<code>COUNTER_NET_SERVER_CONNECTION_CLOSE()</code>, <code>COUNTER_HTTP_SERVER_REQUEST()</code>,
<code>COUNTER_HTTP_SERVER_RESPONSE()</code>, <code>COUNTER_HTTP_CLIENT_REQUEST()</code>, and
<code>COUNTER_HTTP_CLIENT_RESPONSE()</code> functions have been deprecated.</p>
<p><a id="DEP0121"></a></p>
<h3>DEP0121: <code>net._setSimultaneousAccepts()</code><span><a class="mark" href="#deprecations_dep0121_net_setsimultaneousaccepts" id="deprecations_dep0121_net_setsimultaneousaccepts">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The undocumented <code>net._setSimultaneousAccepts()</code> function was originally
intended for debugging and performance tuning when using the <code>child_process</code>
and <code>cluster</code> modules on Windows. The function is not generally useful and
is being removed. See discussion here:
<a href="https://github.com/nodejs/node/issues/18391">https://github.com/nodejs/node/issues/18391</a></p>
<p><a id="DEP0122"></a></p>
<h3>DEP0122: <code>tls</code> <code>Server.prototype.setOptions()</code><span><a class="mark" href="#deprecations_dep0122_tls_server_prototype_setoptions" id="deprecations_dep0122_tls_server_prototype_setoptions">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Please use <code>Server.prototype.setSecureContext()</code> instead.</p>
<p><a id="DEP0123"></a></p>
<h3>DEP0123: setting the TLS ServerName to an IP address<span><a class="mark" href="#deprecations_dep0123_setting_the_tls_servername_to_an_ip_address" id="deprecations_dep0123_setting_the_tls_servername_to_an_ip_address">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Setting the TLS ServerName to an IP address is not permitted by
<a href="https://tools.ietf.org/html/rfc6066#section-3">RFC 6066</a>. This will be ignored in a future version.</p>
<p><a id="DEP0124"></a></p>
<h3>DEP0124: using <code>REPLServer.rli</code><span><a class="mark" href="#deprecations_dep0124_using_replserver_rli" id="deprecations_dep0124_using_replserver_rli">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>This property is a reference to the instance itself.</p>
<p><a id="DEP0125"></a></p>
<h3>DEP0125: <code>require('_stream_wrap')</code><span><a class="mark" href="#deprecations_dep0125_require_stream_wrap" id="deprecations_dep0125_require_stream_wrap">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>_stream_wrap</code> module is deprecated.</p>
<p><a id="DEP0126"></a></p>
<h3>DEP0126: <code>timers.active()</code><span><a class="mark" href="#deprecations_dep0126_timers_active" id="deprecations_dep0126_timers_active">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.14.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The previously undocumented <code>timers.active()</code> is deprecated.
Please use the publicly documented <a href="#timers_timeout_refresh"><code>timeout.refresh()</code></a> instead.
If re-referencing the timeout is necessary, <a href="#timers_timeout_ref"><code>timeout.ref()</code></a> can be used
with no performance impact since Node.js 10.</p>
<p><a id="DEP0127"></a></p>
<h3>DEP0127: <code>timers._unrefActive()</code><span><a class="mark" href="#deprecations_dep0127_timers_unrefactive" id="deprecations_dep0127_timers_unrefactive">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.14.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The previously undocumented and "private" <code>timers._unrefActive()</code> is deprecated.
Please use the publicly documented <a href="#timers_timeout_refresh"><code>timeout.refresh()</code></a> instead.
If unreferencing the timeout is necessary, <a href="#timers_timeout_unref"><code>timeout.unref()</code></a> can be used
with no performance impact since Node.js 10.</p>
<p><a id="DEP0128"></a></p>
<h3>DEP0128: modules with an invalid <code>main</code> entry and an <code>index.js</code> file<span><a class="mark" href="#deprecations_dep0128_modules_with_an_invalid_main_entry_and_an_index_js_file" id="deprecations_dep0128_modules_with_an_invalid_main_entry_and_an_index_js_file">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a>)</p>
<p>Modules that have an invalid <code>main</code> entry (e.g., <code>./does-not-exist.js</code>) and
also have an <code>index.js</code> file in the top level directory will resolve the
<code>index.js</code> file. That is deprecated and is going to throw an error in future
Node.js versions.</p>
<p><a id="DEP0129"></a></p>
<h3>DEP0129: <code>ChildProcess._channel</code><span><a class="mark" href="#deprecations_dep0129_childprocess_channel" id="deprecations_dep0129_childprocess_channel">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.14.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>_channel</code> property of child process objects returned by <code>spawn()</code> and
similar functions is not intended for public use. Use <code>ChildProcess.channel</code>
instead.</p>
<p><a id="DEP0130"></a></p>
<h3>DEP0130: <code>Module.createRequireFromPath()</code><span><a class="mark" href="#deprecations_dep0130_module_createrequirefrompath" id="deprecations_dep0130_module_createrequirefrompath">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.2.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Module.createRequireFromPath() is deprecated. Please use <a href="#modules_module_createrequire_filename"><code>module.createRequire()</code></a> instead.</p>
<p><a id="DEP0131"></a></p>
<h3>DEP0131: Legacy HTTP parser<span><a class="mark" href="#deprecations_dep0131_legacy_http_parser" id="deprecations_dep0131_legacy_http_parser">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.3.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The legacy HTTP parser, used by default in versions of Node.js prior to 12.0.0,
is deprecated. This deprecation applies to users of the
<a href="#cli_http_parser_library"><code>--http-parser=legacy</code></a> command-line flag.</p>
<p><a id="DEP0132"></a></p>
<h3>DEP0132: <code>worker.terminate()</code> with callback<span><a class="mark" href="#deprecations_dep0132_worker_terminate_with_callback" id="deprecations_dep0132_worker_terminate_with_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.5.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Passing a callback to <a href="#worker_threads_worker_terminate"><code>worker.terminate()</code></a> is deprecated. Use the returned
<code>Promise</code> instead, or a listener to the worker’s <code>'exit'</code> event.</p>
<p><a id="DEP0133"></a></p>
<h3>DEP0133: <code>http</code> <code>connection</code><span><a class="mark" href="#deprecations_dep0133_http_connection" id="deprecations_dep0133_http_connection">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.12.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Prefer <a href="#http_response_socket"><code>response.socket</code></a> over <a href="#http_response_connection"><code>response.connection</code></a> and
<a href="#http_request_socket"><code>request.socket</code></a> over <a href="#http_request_connection"><code>request.connection</code></a>.</p>
<p><a id="DEP0134"></a></p>
<h3>DEP0134: <code>process._tickCallback</code><span><a class="mark" href="#deprecations_dep0134_process_tickcallback" id="deprecations_dep0134_process_tickcallback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.12.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#cli_pending_deprecation"><code>--pending-deprecation</code></a>)</p>
<p>The <code>process._tickCallback</code> property was never documented as
an officially supported API.</p>
<p><a id="DEP0136"></a></p>
<h3>DEP0136: <code>http</code> <code>finished</code><span><a class="mark" href="#deprecations_dep0136_http_finished" id="deprecations_dep0136_http_finished">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p><a href="#http_response_finished"><code>response.finished</code></a> indicates whether <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> has been
called, not whether <code>'finish'</code> has been emitted and the underlying data
is flushed.</p>
<p>Use <a href="#http_response_writablefinished"><code>response.writableFinished</code></a> or <a href="#http_response_writableended"><code>response.writableEnded</code></a>
accordingly instead to avoid the ambigiuty.</p>
<p>To maintain existing behaviour <code>response.finished</code> should be replaced with
<code>response.writableEnded</code>.</p>
<h1>DNS<span><a class="mark" href="#dns_dns" id="dns_dns">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>dns</code> module enables name resolution. For example, use it to look up IP
addresses of host names.</p>
<p>Although named for the <a href="https://en.wikipedia.org/wiki/Domain_Name_System">Domain Name System (DNS)</a>, it does not always use the
DNS protocol for lookups. <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> uses the operating system
facilities to perform name resolution. It may not need to perform any network
communication. To perform name resolution the way other applications on the same
system do, use <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</p>
<pre><code class="language-js">const dns = require('dns');

dns.lookup('example.org', (err, address, family) => {
  console.log('address: %j family: IPv%s', address, family);
});
// address: "93.184.216.34" family: IPv4
</code></pre>
<p>All other functions in the <code>dns</code> module connect to an actual DNS server to
perform name resolution. They will always use the network to perform DNS
queries. These functions do not use the same set of configuration files used by
<a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> (e.g. <code>/etc/hosts</code>). Use these functions to always perform
DNS queries, bypassing other name-resolution facilities.</p>
<pre><code class="language-js">const dns = require('dns');

dns.resolve4('archive.org', (err, addresses) => {
  if (err) throw err;

  console.log(`addresses: ${JSON.stringify(addresses)}`);

  addresses.forEach((a) => {
    dns.reverse(a, (err, hostnames) => {
      if (err) {
        throw err;
      }
      console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
    });
  });
});
</code></pre>
<p>See the <a href="#dns_implementation_considerations">Implementation considerations section</a> for more information.</p>
<h2>Class: <code>dns.Resolver</code><span><a class="mark" href="#dns_class_dns_resolver" id="dns_class_dns_resolver">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
</div>
<p>An independent resolver for DNS requests.</p>
<p>Creating a new resolver uses the default server settings. Setting
the servers used for a resolver using
<a href="#dns_dns_setservers_servers"><code>resolver.setServers()</code></a> does not affect
other resolvers:</p>
<pre><code class="language-js">const { Resolver } = require('dns');
const resolver = new Resolver();
resolver.setServers(['4.4.4.4']);

// This request will use the server at 4.4.4.4, independent of global settings.
resolver.resolve4('example.org', (err, addresses) => {
  // ...
});
</code></pre>
<p>The following methods from the <code>dns</code> module are available:</p>
<ul>
<li><a href="#dns_dns_getservers"><code>resolver.getServers()</code></a></li>
<li><a href="#dns_dns_resolve_hostname_rrtype_callback"><code>resolver.resolve()</code></a></li>
<li><a href="#dns_dns_resolve4_hostname_options_callback"><code>resolver.resolve4()</code></a></li>
<li><a href="#dns_dns_resolve6_hostname_options_callback"><code>resolver.resolve6()</code></a></li>
<li><a href="#dns_dns_resolveany_hostname_callback"><code>resolver.resolveAny()</code></a></li>
<li><a href="#dns_dns_resolvecname_hostname_callback"><code>resolver.resolveCname()</code></a></li>
<li><a href="#dns_dns_resolvemx_hostname_callback"><code>resolver.resolveMx()</code></a></li>
<li><a href="#dns_dns_resolvenaptr_hostname_callback"><code>resolver.resolveNaptr()</code></a></li>
<li><a href="#dns_dns_resolvens_hostname_callback"><code>resolver.resolveNs()</code></a></li>
<li><a href="#dns_dns_resolveptr_hostname_callback"><code>resolver.resolvePtr()</code></a></li>
<li><a href="#dns_dns_resolvesoa_hostname_callback"><code>resolver.resolveSoa()</code></a></li>
<li><a href="#dns_dns_resolvesrv_hostname_callback"><code>resolver.resolveSrv()</code></a></li>
<li><a href="#dns_dns_resolvetxt_hostname_callback"><code>resolver.resolveTxt()</code></a></li>
<li><a href="#dns_dns_reverse_ip_callback"><code>resolver.reverse()</code></a></li>
<li><a href="#dns_dns_setservers_servers"><code>resolver.setServers()</code></a></li>
</ul>
<h3><code>Resolver([options])</code><span><a class="mark" href="#dns_resolver_options" id="dns_resolver_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.18.3</td>
<td><p>The constructor now accepts an <code>options</code> object. The single supported option is <code>timeout</code>.</p></td></tr>
<tr><td>v8.3.0</td>
<td><p><span>Added in: v8.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Create a new resolver.</p>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Query timeout in milliseconds, or <code>-1</code> to use the
default timeout.</li>
</ul>
</li>
</ul>
<h3><code>resolver.cancel()</code><span><a class="mark" href="#dns_resolver_cancel" id="dns_resolver_cancel">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
</div>
<p>Cancel all outstanding DNS queries made by this resolver. The corresponding
callbacks will be called with an error with code <code>ECANCELLED</code>.</p>
<h2><code>dns.getServers()</code><span><a class="mark" href="#dns_dns_getservers" id="dns_dns_getservers">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>Returns an array of IP address strings, formatted according to <a href="https://tools.ietf.org/html/rfc5952#section-6">RFC 5952</a>,
that are currently configured for DNS resolution. A string will include a port
section if a custom port is used.</p>
<!-- eslint-disable semi-->
<pre><code class="language-js">[
  '4.4.4.4',
  '2001:4860:4860::8888',
  '4.4.4.4:1053',
  '[2001:4860:4860::8888]:1053'
]
</code></pre>
<h2><code>dns.lookup(hostname[, options], callback)</code><span><a class="mark" href="#dns_dns_lookup_hostname_options_callback" id="dns_dns_lookup_hostname_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.5.0</td>
<td><p>The <code>verbatim</code> option is supported now.</p></td></tr>
<tr><td>v1.2.0</td>
<td><p>The <code>all</code> option is supported now.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The record family. Must be <code>4</code>, <code>6</code>, or <code>0</code>. The value
<code>0</code> indicates that IPv4 and IPv6 addresses are both returned. <strong>Default:</strong>
<code>0</code>.</li>
<li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;boolean></a> When <code>true</code>, the callback receives IPv4 and IPv6
addresses in the order the DNS resolver returned them. When <code>false</code>,
IPv4 addresses are placed before IPv6 addresses.
<strong>Default:</strong> currently <code>false</code> (addresses are reordered) but this is
expected to change in the not too distant future.
New code should use <code>{ verbatim: true }</code>.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;integer></a> <code>4</code> or <code>6</code>, denoting the family of <code>address</code>, or <code>0</code> if
the address is not an IPv4 or IPv6 address. <code>0</code> is a likely indicator of a
bug in the name resolution service used by the operating system.</li>
</ul>
</li>
</ul>
<p>Resolves a host name (e.g. <code>'nodejs.org'</code>) into the first found A (IPv4) or
AAAA (IPv6) record. All <code>option</code> properties are optional. If <code>options</code> is an
integer, then it must be <code>4</code> or <code>6</code> – if <code>options</code> is not provided, then IPv4
and IPv6 addresses are both returned if found.</p>
<p>With the <code>all</code> option set to <code>true</code>, the arguments for <code>callback</code> change to
<code>(err, addresses)</code>, with <code>addresses</code> being an array of objects with the
properties <code>address</code> and <code>family</code>.</p>
<p>On error, <code>err</code> is an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is the error code.
Keep in mind that <code>err.code</code> will be set to <code>'ENOTFOUND'</code> not only when
the host name does not exist but also when the lookup fails in other ways
such as no available file descriptors.</p>
<p><code>dns.lookup()</code> does not necessarily have anything to do with the DNS protocol.
The implementation uses an operating system facility that can associate names
with addresses, and vice versa. This implementation can have subtle but
important consequences on the behavior of any Node.js program. Please take some
time to consult the <a href="#dns_implementation_considerations">Implementation considerations section</a> before using
<code>dns.lookup()</code>.</p>
<p>Example usage:</p>
<pre><code class="language-js">const dns = require('dns');
const options = {
  family: 6,
  hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
dns.lookup('example.com', options, (err, address, family) =>
  console.log('address: %j family: IPv%s', address, family));
// address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6

// When options.all is true, the result will be an Array.
options.all = true;
dns.lookup('example.com', options, (err, addresses) =>
  console.log('addresses: %j', addresses));
// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
</code></pre>
<p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, and <code>all</code>
is not set to <code>true</code>, it returns a <code>Promise</code> for an <code>Object</code> with <code>address</code> and
<code>family</code> properties.</p>
<h3>Supported getaddrinfo flags<span><a class="mark" href="#dns_supported_getaddrinfo_flags" id="dns_supported_getaddrinfo_flags">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>Added support for the <code>dns.ALL</code> flag.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The following flags can be passed as hints to <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</p>
<ul>
<li><code>dns.ADDRCONFIG</code>: Returned address types are determined by the types
of addresses supported by the current system. For example, IPv4 addresses
are only returned if the current system has at least one IPv4 address
configured. Loopback addresses are not considered.</li>
<li><code>dns.V4MAPPED</code>: If the IPv6 family was specified, but no IPv6 addresses were
found, then return IPv4 mapped IPv6 addresses. It is not supported
on some operating systems (e.g FreeBSD 10.1).</li>
<li><code>dns.ALL</code>: If <code>dns.V4MAPPED</code> is specified, return resolved IPv6 addresses as
well as IPv4 mapped IPv6 addresses.</li>
</ul>
<h2><code>dns.lookupService(address, port, callback)</code><span><a class="mark" href="#dns_dns_lookupservice_address_port_callback" id="dns_dns_lookupservice_address_port_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> e.g. <code>http</code></li>
</ul>
</li>
</ul>
<p>Resolves the given <code>address</code> and <code>port</code> into a host name and service using
the operating system's underlying <code>getnameinfo</code> implementation.</p>
<p>If <code>address</code> is not a valid IP address, a <code>TypeError</code> will be thrown.
The <code>port</code> will be coerced to a number. If it is not a legal port, a <code>TypeError</code>
will be thrown.</p>
<p>On an error, <code>err</code> is an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is the error code.</p>
<pre><code class="language-js">const dns = require('dns');
dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
  console.log(hostname, service);
  // Prints: localhost ssh
});
</code></pre>
<p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns a
<code>Promise</code> for an <code>Object</code> with <code>hostname</code> and <code>service</code> properties.</p>
<h2><code>dns.resolve(hostname[, rrtype], callback)</code><span><a class="mark" href="#dns_dns_resolve_hostname_rrtype_callback" id="dns_dns_resolve_hostname_rrtype_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Host name to resolve.</li>
<li><code>rrtype</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Resource record type. <strong>Default:</strong> <code>'A'</code>.</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>records</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve a host name (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">&#x3C;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">&#x3C;string></a></td><td><a href="#dns_dns_resolve6_hostname_options_callback"><code>dns.resolve6()</code></a></td></tr><tr><td><code>'ANY'</code></td><td>any records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></td><td><a href="#dns_dns_resolveany_hostname_callback"><code>dns.resolveAny()</code></a></td></tr><tr><td><code>'CNAME'</code></td><td>canonical name records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;string[]></a></td><td><a href="#dns_dns_resolvetxt_hostname_callback"><code>dns.resolveTxt()</code></a></td></tr></tbody></table>
<p>On error, <code>err</code> is an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is one of the
<a href="#dns_error_codes">DNS error codes</a>.</p>
<h2><code>dns.resolve4(hostname[, options], callback)</code><span><a class="mark" href="#dns_dns_resolve4_hostname_options_callback" id="dns_dns_resolve4_hostname_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.2.0</td>
<td><p>This method now supports passing <code>options</code>, specifically <code>options.ttl</code>.</p></td></tr>
<tr><td>v0.1.16</td>
<td><p><span>Added in: v0.1.16</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Host name to resolve.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Retrieve the Time-To-Live value (TTL) of each record.
When <code>true</code>, the callback receives an array of
<code>{ address: '1.2.3.4', ttl: 60 }</code> objects rather than an array of strings,
with the TTL expressed in seconds.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve a IPv4 addresses (<code>A</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function
will contain an array of IPv4 addresses (e.g.
<code>['74.125.79.104', '74.125.79.105', '74.125.79.106']</code>).</p>
<h2><code>dns.resolve6(hostname[, options], callback)</code><span><a class="mark" href="#dns_dns_resolve6_hostname_options_callback" id="dns_dns_resolve6_hostname_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.2.0</td>
<td><p>This method now supports passing <code>options</code>, specifically <code>options.ttl</code>.</p></td></tr>
<tr><td>v0.1.16</td>
<td><p><span>Added in: v0.1.16</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Host name to resolve.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Retrieve the Time-To-Live value (TTL) of each record.
When <code>true</code>, the callback receives an array of
<code>{ address: '0:1:2:3:4:5:6:7', ttl: 60 }</code> objects rather than an array of
strings, with the TTL expressed in seconds.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve a IPv6 addresses (<code>AAAA</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function
will contain an array of IPv6 addresses.</p>
<h2><code>dns.resolveAny(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolveany_hostname_callback" id="dns_dns_resolveany_hostname_callback">#</a></span></h2>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>ret</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve all records (also known as <code>ANY</code> or <code>*</code> query).
The <code>ret</code> argument passed to the <code>callback</code> function will be an array containing
various types of records. Each object has a property <code>type</code> that indicates the
type of the current record. And depending on the <code>type</code>, additional properties
will be present on the object:</p>

















































<table><thead><tr><th>Type</th><th>Properties</th></tr></thead><tbody><tr><td><code>'A'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'AAAA'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'CNAME'</code></td><td><code>value</code></td></tr><tr><td><code>'MX'</code></td><td>Refer to <a href="#dns_dns_resolvemx_hostname_callback"><code>dns.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>Refer to <a href="#dns_dns_resolvenaptr_hostname_callback"><code>dns.resolveNaptr()</code></a></td></tr><tr><td><code>'NS'</code></td><td><code>value</code></td></tr><tr><td><code>'PTR'</code></td><td><code>value</code></td></tr><tr><td><code>'SOA'</code></td><td>Refer to <a href="#dns_dns_resolvesoa_hostname_callback"><code>dns.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>Refer to <a href="#dns_dns_resolvesrv_hostname_callback"><code>dns.resolveSrv()</code></a></td></tr><tr><td><code>'TXT'</code></td><td>This type of record contains an array property called <code>entries</code> which refers to <a href="#dns_dns_resolvetxt_hostname_callback"><code>dns.resolveTxt()</code></a>, e.g. <code>{ entries: ['...'], type: 'TXT' }</code></td></tr></tbody></table>
<p>Here is an example of the <code>ret</code> object passed to the callback:</p>
<!-- eslint-disable semi -->
<pre><code class="language-js">[ { type: 'A', address: '127.0.0.1', ttl: 299 },
  { type: 'CNAME', value: 'example.com' },
  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
  { type: 'NS', value: 'ns1.example.com' },
  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
  { type: 'SOA',
    nsname: 'ns1.example.com',
    hostmaster: 'admin.example.com',
    serial: 156696742,
    refresh: 900,
    retry: 900,
    expire: 1800,
    minttl: 60 } ]
</code></pre>
<p>DNS server operators may choose not to respond to <code>ANY</code>
queries. It may be better to call individual methods like <a href="#dns_dns_resolve4_hostname_options_callback"><code>dns.resolve4()</code></a>,
<a href="#dns_dns_resolvemx_hostname_callback"><code>dns.resolveMx()</code></a>, and so on. For more details, see <a href="https://tools.ietf.org/html/rfc8482">RFC 8482</a>.</p>
<h2><code>dns.resolveCname(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvecname_hostname_callback" id="dns_dns_resolvecname_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve <code>CNAME</code> records for the <code>hostname</code>. The
<code>addresses</code> argument passed to the <code>callback</code> function
will contain an array of canonical name records available for the <code>hostname</code>
(e.g. <code>['bar.example.com']</code>).</p>
<h2><code>dns.resolveMx(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvemx_hostname_callback" id="dns_dns_resolvemx_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve mail exchange records (<code>MX</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will
contain an array of objects containing both a <code>priority</code> and <code>exchange</code>
property (e.g. <code>[{priority: 10, exchange: 'mx.example.com'}, ...]</code>).</p>
<h2><code>dns.resolveNaptr(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvenaptr_hostname_callback" id="dns_dns_resolvenaptr_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.12</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve regular expression based records (<code>NAPTR</code>
records) for the <code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code>
function will contain an array of objects with the following properties:</p>
<ul>
<li><code>flags</code></li>
<li><code>service</code></li>
<li><code>regexp</code></li>
<li><code>replacement</code></li>
<li><code>order</code></li>
<li><code>preference</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
  flags: 's',
  service: 'SIP+D2U',
  regexp: '',
  replacement: '_sip._udp.example.com',
  order: 30,
  preference: 100
}
</code></pre>
<h2><code>dns.resolveNs(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvens_hostname_callback" id="dns_dns_resolvens_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve name server records (<code>NS</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will
contain an array of name server records available for <code>hostname</code>
(e.g. <code>['ns1.example.com', 'ns2.example.com']</code>).</p>
<h2><code>dns.resolvePtr(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolveptr_hostname_callback" id="dns_dns_resolveptr_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve pointer records (<code>PTR</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will
be an array of strings containing the reply records.</p>
<h2><code>dns.resolveSoa(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvesoa_hostname_callback" id="dns_dns_resolvesoa_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.10</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve a start of authority record (<code>SOA</code> record) for
the <code>hostname</code>. The <code>address</code> argument passed to the <code>callback</code> function will
be an object with the following properties:</p>
<ul>
<li><code>nsname</code></li>
<li><code>hostmaster</code></li>
<li><code>serial</code></li>
<li><code>refresh</code></li>
<li><code>retry</code></li>
<li><code>expire</code></li>
<li><code>minttl</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
  nsname: 'ns.example.com',
  hostmaster: 'root.example.com',
  serial: 2013101809,
  refresh: 10000,
  retry: 2400,
  expire: 604800,
  minttl: 3600
}
</code></pre>
<h2><code>dns.resolveSrv(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvesrv_hostname_callback" id="dns_dns_resolvesrv_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>addresses</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve service records (<code>SRV</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function will
be an array of objects with the following properties:</p>
<ul>
<li><code>priority</code></li>
<li><code>weight</code></li>
<li><code>port</code></li>
<li><code>name</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
  priority: 10,
  weight: 5,
  port: 21223,
  name: 'service.example.com'
}
</code></pre>
<h2><code>dns.resolveTxt(hostname, callback)</code><span><a class="mark" href="#dns_dns_resolvetxt_hostname_callback" id="dns_dns_resolvetxt_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>records</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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><code>dns.reverse(ip, callback)</code><span><a class="mark" href="#dns_dns_reverse_ip_callback" id="dns_dns_reverse_ip_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><code>ip</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>hostnames</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
</li>
</ul>
<p>Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
array of host names.</p>
<p>On error, <code>err</code> is an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is
one of the <a href="#dns_error_codes">DNS error codes</a>.</p>
<h2><code>dns.setServers(servers)</code><span><a class="mark" href="#dns_dns_setservers_servers" id="dns_dns_setservers_servers">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div>
<ul>
<li><code>servers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> array of <a href="https://tools.ietf.org/html/rfc5952#section-6">RFC 5952</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">RFC 5952</a> formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.</p>
<pre><code class="language-js">dns.setServers([
  '4.4.4.4',
  '[2001:4860:4860::8888]',
  '4.4.4.4:1053',
  '[2001:4860:4860::8888]:1053'
]);
</code></pre>
<p>An error will be thrown if an invalid address is provided.</p>
<p>The <code>dns.setServers()</code> method must not be called while a DNS query is in
progress.</p>
<p>The <a href="#dns_dns_setservers_servers"><code>dns.setServers()</code></a> method affects only <a href="#dns_dns_resolve_hostname_rrtype_callback"><code>dns.resolve()</code></a>,
<code>dns.resolve*()</code> and <a href="#dns_dns_reverse_ip_callback"><code>dns.reverse()</code></a> (and specifically <em>not</em>
<a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>).</p>
<p>This method works much like
<a href="http://man7.org/linux/man-pages/man5/resolv.conf.5.html">resolve.conf</a>.
That is, if attempting to resolve with the first server provided results in a
<code>NOTFOUND</code> error, the <code>resolve()</code> method will <em>not</em> attempt to resolve with
subsequent servers provided. Fallback DNS servers will only be used if the
earlier ones time out or result in some other error.</p>
<h2>DNS promises API<span><a class="mark" href="#dns_dns_promises_api" id="dns_dns_promises_api">#</a></span></h2>
<p>The <code>dns.promises</code> API provides an alternative set of asynchronous DNS methods
that return <code>Promise</code> objects rather than using callbacks. The API is accessible
via <code>require('dns').promises</code>.</p>
<h3>Class: <code>dnsPromises.Resolver</code><span><a class="mark" href="#dns_class_dnspromises_resolver" id="dns_class_dnspromises_resolver">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<p>An independent resolver for DNS requests.</p>
<p>Creating a new resolver uses the default server settings. Setting
the servers used for a resolver using
<a href="#dns_dnspromises_setservers_servers"><code>resolver.setServers()</code></a> does not affect
other resolvers:</p>
<pre><code class="language-js">const { Resolver } = require('dns').promises;
const resolver = new Resolver();
resolver.setServers(['4.4.4.4']);

// This request will use the server at 4.4.4.4, independent of global settings.
resolver.resolve4('example.org').then((addresses) => {
  // ...
});

// Alternatively, the same code can be written using async-await style.
(async function() {
  const addresses = await resolver.resolve4('example.org');
})();
</code></pre>
<p>The following methods from the <code>dnsPromises</code> API are available:</p>
<ul>
<li><a href="#dns_dnspromises_getservers"><code>resolver.getServers()</code></a></li>
<li><a href="#dns_dnspromises_resolve_hostname_rrtype"><code>resolver.resolve()</code></a></li>
<li><a href="#dns_dnspromises_resolve4_hostname_options"><code>resolver.resolve4()</code></a></li>
<li><a href="#dns_dnspromises_resolve6_hostname_options"><code>resolver.resolve6()</code></a></li>
<li><a href="#dns_dnspromises_resolveany_hostname"><code>resolver.resolveAny()</code></a></li>
<li><a href="#dns_dnspromises_resolvecname_hostname"><code>resolver.resolveCname()</code></a></li>
<li><a href="#dns_dnspromises_resolvemx_hostname"><code>resolver.resolveMx()</code></a></li>
<li><a href="#dns_dnspromises_resolvenaptr_hostname"><code>resolver.resolveNaptr()</code></a></li>
<li><a href="#dns_dnspromises_resolvens_hostname"><code>resolver.resolveNs()</code></a></li>
<li><a href="#dns_dnspromises_resolveptr_hostname"><code>resolver.resolvePtr()</code></a></li>
<li><a href="#dns_dnspromises_resolvesoa_hostname"><code>resolver.resolveSoa()</code></a></li>
<li><a href="#dns_dnspromises_resolvesrv_hostname"><code>resolver.resolveSrv()</code></a></li>
<li><a href="#dns_dnspromises_resolvetxt_hostname"><code>resolver.resolveTxt()</code></a></li>
<li><a href="#dns_dnspromises_reverse_ip"><code>resolver.reverse()</code></a></li>
<li><a href="#dns_dnspromises_setservers_servers"><code>resolver.setServers()</code></a></li>
</ul>
<h3><code>dnsPromises.getServers()</code><span><a class="mark" href="#dns_dnspromises_getservers" id="dns_dnspromises_getservers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>Returns an array of IP address strings, formatted according to <a href="https://tools.ietf.org/html/rfc5952#section-6">RFC 5952</a>,
that are currently configured for DNS resolution. A string will include a port
section if a custom port is used.</p>
<!-- eslint-disable semi-->
<pre><code class="language-js">[
  '4.4.4.4',
  '2001:4860:4860::8888',
  '4.4.4.4:1053',
  '[2001:4860:4860::8888]:1053'
]
</code></pre>
<h3><code>dnsPromises.lookup(hostname[, options])</code><span><a class="mark" href="#dns_dnspromises_lookup_hostname_options" id="dns_dnspromises_lookup_hostname_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The record family. Must be <code>4</code>, <code>6</code>, or <code>0</code>. The value
<code>0</code> indicates that IPv4 and IPv6 addresses are both returned. <strong>Default:</strong>
<code>0</code>.</li>
<li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;boolean></a> When <code>true</code>, the <code>Promise</code> is resolved with all addresses in
an array. Otherwise, returns a single address. <strong>Default:</strong> <code>false</code>.</li>
<li><code>verbatim</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, the <code>Promise</code> is resolved with IPv4 and
IPv6 addresses in the order the DNS resolver returned them. When <code>false</code>,
IPv4 addresses are placed before IPv6 addresses.
<strong>Default:</strong> currently <code>false</code> (addresses are reordered) but this is
expected to change in the not too distant future.
New code should use <code>{ verbatim: true }</code>.</li>
</ul>
</li>
</ul>
<p>Resolves a host name (e.g. <code>'nodejs.org'</code>) into the first found A (IPv4) or
AAAA (IPv6) record. All <code>option</code> properties are optional. If <code>options</code> is an
integer, then it must be <code>4</code> or <code>6</code> – if <code>options</code> is not provided, then IPv4
and IPv6 addresses are both returned if found.</p>
<p>With the <code>all</code> option set to <code>true</code>, the <code>Promise</code> is resolved with <code>addresses</code>
being an array of objects with the properties <code>address</code> and <code>family</code>.</p>
<p>On error, the <code>Promise</code> is rejected with an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code>
is the error code.
Keep in mind that <code>err.code</code> will be set to <code>'ENOTFOUND'</code> not only when
the host name does not exist but also when the lookup fails in other ways
such as no available file descriptors.</p>
<p><a href="#dns_dnspromises_lookup_hostname_options"><code>dnsPromises.lookup()</code></a> does not necessarily have anything to do with the DNS
protocol. The implementation uses an operating system facility that can
associate names with addresses, and vice versa. This implementation can have
subtle but important consequences on the behavior of any Node.js program. Please
take some time to consult the <a href="#dns_implementation_considerations">Implementation considerations section</a> before
using <code>dnsPromises.lookup()</code>.</p>
<p>Example usage:</p>
<pre><code class="language-js">const dns = require('dns');
const dnsPromises = dns.promises;
const options = {
  family: 6,
  hints: dns.ADDRCONFIG | dns.V4MAPPED,
};

dnsPromises.lookup('example.com', options).then((result) => {
  console.log('address: %j family: IPv%s', result.address, result.family);
  // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
});

// When options.all is true, the result will be an Array.
options.all = true;
dnsPromises.lookup('example.com', options).then((result) => {
  console.log('addresses: %j', result);
  // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
});
</code></pre>
<h3><code>dnsPromises.lookupService(address, port)</code><span><a class="mark" href="#dns_dnspromises_lookupservice_address_port" id="dns_dnspromises_lookupservice_address_port">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Resolves the given <code>address</code> and <code>port</code> into a host name and service using
the operating system's underlying <code>getnameinfo</code> implementation.</p>
<p>If <code>address</code> is not a valid IP address, a <code>TypeError</code> will be thrown.
The <code>port</code> will be coerced to a number. If it is not a legal port, a <code>TypeError</code>
will be thrown.</p>
<p>On error, the <code>Promise</code> is rejected with an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code>
is the error code.</p>
<pre><code class="language-js">const dnsPromises = require('dns').promises;
dnsPromises.lookupService('127.0.0.1', 22).then((result) => {
  console.log(result.hostname, result.service);
  // Prints: localhost ssh
});
</code></pre>
<h3><code>dnsPromises.resolve(hostname[, rrtype])</code><span><a class="mark" href="#dns_dnspromises_resolve_hostname_rrtype" id="dns_dnspromises_resolve_hostname_rrtype">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Host name to resolve.</li>
<li><code>rrtype</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Resource record type. <strong>Default:</strong> <code>'A'</code>.</li>
</ul>
<p>Uses the DNS protocol to resolve a host name (e.g. <code>'nodejs.org'</code>) into an array
of the resource records. When successful, the <code>Promise</code> is resolved with an
array of resource records. The type and structure of individual results vary
based on <code>rrtype</code>:</p>













































































<table><thead><tr><th><code>rrtype</code></th><th><code>records</code> contains</th><th>Result type</th><th>Shorthand method</th></tr></thead><tbody><tr><td><code>'A'</code></td><td>IPv4 addresses (default)</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></td><td><a href="#dns_dnspromises_resolve4_hostname_options"><code>dnsPromises.resolve4()</code></a></td></tr><tr><td><code>'AAAA'</code></td><td>IPv6 addresses</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></td><td><a href="#dns_dnspromises_resolve6_hostname_options"><code>dnsPromises.resolve6()</code></a></td></tr><tr><td><code>'ANY'</code></td><td>any records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></td><td><a href="#dns_dnspromises_resolveany_hostname"><code>dnsPromises.resolveAny()</code></a></td></tr><tr><td><code>'CNAME'</code></td><td>canonical name records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></td><td><a href="#dns_dnspromises_resolvecname_hostname"><code>dnsPromises.resolveCname()</code></a></td></tr><tr><td><code>'MX'</code></td><td>mail exchange records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></td><td><a href="#dns_dnspromises_resolvemx_hostname"><code>dnsPromises.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>name authority pointer records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></td><td><a href="#dns_dnspromises_resolvenaptr_hostname"><code>dnsPromises.resolveNaptr()</code></a></td></tr><tr><td><code>'NS'</code></td><td>name server records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></td><td><a href="#dns_dnspromises_resolvens_hostname"><code>dnsPromises.resolveNs()</code></a></td></tr><tr><td><code>'PTR'</code></td><td>pointer records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></td><td><a href="#dns_dnspromises_resolveptr_hostname"><code>dnsPromises.resolvePtr()</code></a></td></tr><tr><td><code>'SOA'</code></td><td>start of authority records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></td><td><a href="#dns_dnspromises_resolvesoa_hostname"><code>dnsPromises.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>service records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></td><td><a href="#dns_dnspromises_resolvesrv_hostname"><code>dnsPromises.resolveSrv()</code></a></td></tr><tr><td><code>'TXT'</code></td><td>text records</td><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></td><td><a href="#dns_dnspromises_resolvetxt_hostname"><code>dnsPromises.resolveTxt()</code></a></td></tr></tbody></table>
<p>On error, the <code>Promise</code> is rejected with an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code>
is one of the <a href="#dns_error_codes">DNS error codes</a>.</p>
<h3><code>dnsPromises.resolve4(hostname[, options])</code><span><a class="mark" href="#dns_dnspromises_resolve4_hostname_options" id="dns_dnspromises_resolve4_hostname_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Host name to resolve.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Retrieve the Time-To-Live value (TTL) of each record.
When <code>true</code>, the <code>Promise</code> is resolved with an array of
<code>{ address: '1.2.3.4', ttl: 60 }</code> objects rather than an array of strings,
with the TTL expressed in seconds.</li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve IPv4 addresses (<code>A</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of IPv4
addresses (e.g. <code>['74.125.79.104', '74.125.79.105', '74.125.79.106']</code>).</p>
<h3><code>dnsPromises.resolve6(hostname[, options])</code><span><a class="mark" href="#dns_dnspromises_resolve6_hostname_options" id="dns_dnspromises_resolve6_hostname_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Host name to resolve.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>ttl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Retrieve the Time-To-Live value (TTL) of each record.
When <code>true</code>, the <code>Promise</code> is resolved with an array of
<code>{ address: '0:1:2:3:4:5:6:7', ttl: 60 }</code> objects rather than an array of
strings, with the TTL expressed in seconds.</li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve IPv6 addresses (<code>AAAA</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of IPv6
addresses.</p>
<h3><code>dnsPromises.resolveAny(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolveany_hostname" id="dns_dnspromises_resolveany_hostname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Uses the DNS protocol to resolve all records (also known as <code>ANY</code> or <code>*</code> query).
On success, the <code>Promise</code> is resolved with an array containing various types of
records. Each object has a property <code>type</code> that indicates the type of the
current record. And depending on the <code>type</code>, additional properties will be
present on the object:</p>

















































<table><thead><tr><th>Type</th><th>Properties</th></tr></thead><tbody><tr><td><code>'A'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'AAAA'</code></td><td><code>address</code>/<code>ttl</code></td></tr><tr><td><code>'CNAME'</code></td><td><code>value</code></td></tr><tr><td><code>'MX'</code></td><td>Refer to <a href="#dns_dnspromises_resolvemx_hostname"><code>dnsPromises.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>Refer to <a href="#dns_dnspromises_resolvenaptr_hostname"><code>dnsPromises.resolveNaptr()</code></a></td></tr><tr><td><code>'NS'</code></td><td><code>value</code></td></tr><tr><td><code>'PTR'</code></td><td><code>value</code></td></tr><tr><td><code>'SOA'</code></td><td>Refer to <a href="#dns_dnspromises_resolvesoa_hostname"><code>dnsPromises.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>Refer to <a href="#dns_dnspromises_resolvesrv_hostname"><code>dnsPromises.resolveSrv()</code></a></td></tr><tr><td><code>'TXT'</code></td><td>This type of record contains an array property called <code>entries</code> which refers to <a href="#dns_dnspromises_resolvetxt_hostname"><code>dnsPromises.resolveTxt()</code></a>, e.g. <code>{ entries: ['...'], type: 'TXT' }</code></td></tr></tbody></table>
<p>Here is an example of the result object:</p>
<!-- eslint-disable semi -->
<pre><code class="language-js">[ { type: 'A', address: '127.0.0.1', ttl: 299 },
  { type: 'CNAME', value: 'example.com' },
  { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
  { type: 'NS', value: 'ns1.example.com' },
  { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
  { type: 'SOA',
    nsname: 'ns1.example.com',
    hostmaster: 'admin.example.com',
    serial: 156696742,
    refresh: 900,
    retry: 900,
    expire: 1800,
    minttl: 60 } ]
</code></pre>
<h3><code>dnsPromises.resolveCname(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvecname_hostname" id="dns_dnspromises_resolvecname_hostname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Uses the DNS protocol to resolve <code>CNAME</code> records for the <code>hostname</code>. On success,
the <code>Promise</code> is resolved with an array of canonical name records available for
the <code>hostname</code> (e.g. <code>['bar.example.com']</code>).</p>
<h3><code>dnsPromises.resolveMx(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvemx_hostname" id="dns_dnspromises_resolvemx_hostname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Uses the DNS protocol to resolve mail exchange records (<code>MX</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of objects
containing both a <code>priority</code> and <code>exchange</code> property (e.g.
<code>[{priority: 10, exchange: 'mx.example.com'}, ...]</code>).</p>
<h3><code>dnsPromises.resolveNaptr(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvenaptr_hostname" id="dns_dnspromises_resolvenaptr_hostname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Uses the DNS protocol to resolve regular expression based records (<code>NAPTR</code>
records) for the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an array
of objects with the following properties:</p>
<ul>
<li><code>flags</code></li>
<li><code>service</code></li>
<li><code>regexp</code></li>
<li><code>replacement</code></li>
<li><code>order</code></li>
<li><code>preference</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
  flags: 's',
  service: 'SIP+D2U',
  regexp: '',
  replacement: '_sip._udp.example.com',
  order: 30,
  preference: 100
}
</code></pre>
<h3><code>dnsPromises.resolveNs(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvens_hostname" id="dns_dnspromises_resolvens_hostname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Uses the DNS protocol to resolve name server records (<code>NS</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of name server
records available for <code>hostname</code> (e.g.
<code>['ns1.example.com', 'ns2.example.com']</code>).</p>
<h3><code>dnsPromises.resolvePtr(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolveptr_hostname" id="dns_dnspromises_resolveptr_hostname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Uses the DNS protocol to resolve pointer records (<code>PTR</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of strings
containing the reply records.</p>
<h3><code>dnsPromises.resolveSoa(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvesoa_hostname" id="dns_dnspromises_resolvesoa_hostname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Uses the DNS protocol to resolve a start of authority record (<code>SOA</code> record) for
the <code>hostname</code>. On success, the <code>Promise</code> is resolved with an object with the
following properties:</p>
<ul>
<li><code>nsname</code></li>
<li><code>hostmaster</code></li>
<li><code>serial</code></li>
<li><code>refresh</code></li>
<li><code>retry</code></li>
<li><code>expire</code></li>
<li><code>minttl</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
  nsname: 'ns.example.com',
  hostmaster: 'root.example.com',
  serial: 2013101809,
  refresh: 10000,
  retry: 2400,
  expire: 604800,
  minttl: 3600
}
</code></pre>
<h3><code>dnsPromises.resolveSrv(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvesrv_hostname" id="dns_dnspromises_resolvesrv_hostname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Uses the DNS protocol to resolve service records (<code>SRV</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with an array of objects with
the following properties:</p>
<ul>
<li><code>priority</code></li>
<li><code>weight</code></li>
<li><code>port</code></li>
<li><code>name</code></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
  priority: 10,
  weight: 5,
  port: 21223,
  name: 'service.example.com'
}
</code></pre>
<h3><code>dnsPromises.resolveTxt(hostname)</code><span><a class="mark" href="#dns_dnspromises_resolvetxt_hostname" id="dns_dnspromises_resolvetxt_hostname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Uses the DNS protocol to resolve text queries (<code>TXT</code> records) for the
<code>hostname</code>. On success, the <code>Promise</code> is resolved with a two-dimensional array
of the text records available for <code>hostname</code> (e.g.
<code>[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]</code>). Each sub-array contains TXT chunks of
one record. Depending on the use case, these could be either joined together or
treated separately.</p>
<h3><code>dnsPromises.reverse(ip)</code><span><a class="mark" href="#dns_dnspromises_reverse_ip" id="dns_dnspromises_reverse_ip">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>ip</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
array of host names.</p>
<p>On error, the <code>Promise</code> is rejected with an <a href="#errors_class_error"><code>Error</code></a> object, where <code>err.code</code>
is one of the <a href="#dns_error_codes">DNS error codes</a>.</p>
<h3><code>dnsPromises.setServers(servers)</code><span><a class="mark" href="#dns_dnspromises_setservers_servers" id="dns_dnspromises_setservers_servers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li><code>servers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> array of <a href="https://tools.ietf.org/html/rfc5952#section-6">RFC 5952</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">RFC 5952</a> formatted
addresses. If the port is the IANA default DNS port (53) it can be omitted.</p>
<pre><code class="language-js">dnsPromises.setServers([
  '4.4.4.4',
  '[2001:4860:4860::8888]',
  '4.4.4.4:1053',
  '[2001:4860:4860::8888]:1053'
]);
</code></pre>
<p>An error will be thrown if an invalid address is provided.</p>
<p>The <code>dnsPromises.setServers()</code> method must not be called while a DNS query is in
progress.</p>
<p>This method works much like
<a href="http://man7.org/linux/man-pages/man5/resolv.conf.5.html">resolve.conf</a>.
That is, if attempting to resolve with the first server provided results in a
<code>NOTFOUND</code> error, the <code>resolve()</code> method will <em>not</em> attempt to resolve with
subsequent servers provided. Fallback DNS servers will only be used if the
earlier ones time out or result in some other error.</p>
<h2>Error codes<span><a class="mark" href="#dns_error_codes" id="dns_error_codes">#</a></span></h2>
<p>Each DNS query can return one of the following error codes:</p>
<ul>
<li><code>dns.NODATA</code>: DNS server returned answer with no data.</li>
<li><code>dns.FORMERR</code>: DNS server claims query was misformatted.</li>
<li><code>dns.SERVFAIL</code>: DNS server returned general failure.</li>
<li><code>dns.NOTFOUND</code>: Domain name not found.</li>
<li><code>dns.NOTIMP</code>: DNS server does not implement requested operation.</li>
<li><code>dns.REFUSED</code>: DNS server refused query.</li>
<li><code>dns.BADQUERY</code>: Misformatted DNS query.</li>
<li><code>dns.BADNAME</code>: Misformatted host name.</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 host name is not numeric.</li>
<li><code>dns.BADHINTS</code>: Illegal hints flags specified.</li>
<li><code>dns.NOTINITIALIZED</code>: c-ares library initialization not yet performed.</li>
<li><code>dns.LOADIPHLPAPI</code>: Error loading <code>iphlpapi.dll</code>.</li>
<li><code>dns.ADDRGETNETWORKPARAMS</code>: Could not find <code>GetNetworkParams</code> function.</li>
<li><code>dns.CANCELLED</code>: DNS query cancelled.</li>
</ul>
<h2>Implementation considerations<span><a class="mark" href="#dns_implementation_considerations" id="dns_implementation_considerations">#</a></span></h2>
<p>Although <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> and the various <code>dns.resolve*()/dns.reverse()</code>
functions have the same goal of associating a network name with a network
address (or vice versa), their behavior is quite different. These differences
can have subtle but significant consequences on the behavior of Node.js
programs.</p>
<h3><code>dns.lookup()</code><span><a class="mark" href="#dns_dns_lookup" id="dns_dns_lookup">#</a></span></h3>
<p>Under the hood, <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> uses the same operating system facilities
as most other programs. For instance, <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> will almost always
resolve a given name the same way as the <code>ping</code> command. On most POSIX-like
operating systems, the behavior of the <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> function can be
modified by changing settings in <a href="http://man7.org/linux/man-pages/man5/nsswitch.conf.5.html"><code>nsswitch.conf(5)</code></a> and/or <a href="http://man7.org/linux/man-pages/man5/resolv.conf.5.html"><code>resolv.conf(5)</code></a>,
but changing these files will change the behavior of all other
programs running on the same operating system.</p>
<p>Though the call to <code>dns.lookup()</code> will be asynchronous from JavaScript's
perspective, it is implemented as a synchronous call to <a href="http://man7.org/linux/man-pages/man3/getaddrinfo.3.html"><code>getaddrinfo(3)</code></a> that runs
on libuv's threadpool. This can have surprising negative performance
implications for some applications, see the <a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a>
documentation for more information.</p>
<p>Various networking APIs will call <code>dns.lookup()</code> internally to resolve
host names. If that is an issue, consider resolving the host name to an address
using <code>dns.resolve()</code> and using the address instead of a host name. Also, some
networking APIs (such as <a href="#net_socket_connect_options_connectlistener"><code>socket.connect()</code></a> and <a href="#dgram_dgram_createsocket_options_callback"><code>dgram.createSocket()</code></a>)
allow the default resolver, <code>dns.lookup()</code>, to be replaced.</p>
<h3><code>dns.resolve()</code>, <code>dns.resolve*()</code> and <code>dns.reverse()</code><span><a class="mark" href="#dns_dns_resolve_dns_resolve_and_dns_reverse" id="dns_dns_resolve_dns_resolve_and_dns_reverse">#</a></span></h3>
<p>These functions are implemented quite differently than <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>. They
do not use <a href="http://man7.org/linux/man-pages/man3/getaddrinfo.3.html"><code>getaddrinfo(3)</code></a> and they <em>always</em> perform a DNS query on the
network. This network communication is always done asynchronously, and does not
use libuv's threadpool.</p>
<p>As a result, these functions cannot have the same negative impact on other
processing that happens on libuv's threadpool that <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> can have.</p>
<p>They do not use the same set of configuration files than what <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>
uses. For instance, <em>they do not use the configuration from <code>/etc/hosts</code></em>.</p>
<h1>Domain<span><a class="mark" href="#domain_domain" id="domain_domain">#</a></span></h1>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.8.0</td>
<td><p>Any <code>Promise</code>s created in VM contexts no longer have a <code>.domain</code> property. Their handlers are still executed in the proper domain, however, and <code>Promise</code>s created in the main context still possess a <code>.domain</code> property.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Handlers for <code>Promise</code>s are now invoked in the domain in which the first promise of a chain was created.</p></td></tr>
</tbody></table>
</details>
</div>

<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p>
<p><strong>This module is pending deprecation</strong>. Once a replacement API has been
finalized, this module will be fully deprecated. Most end users should
<strong>not</strong> have cause to use this module. Users who absolutely must have
the functionality that domains provide may rely on it for the time being
but should expect to have to migrate to a different solution
in the future.</p>
<p>Domains provide a way to handle multiple different IO operations as a
single group. If any of the event emitters or callbacks registered to a
domain emit an <code>'error'</code> event, or throw an error, then the domain object
will be notified, rather than losing the context of the error in the
<code>process.on('uncaughtException')</code> handler, or causing the program to
exit immediately with an error code.</p>
<h2>Warning: Don't ignore errors!<span><a class="mark" href="#domain_warning_don_t_ignore_errors" id="domain_warning_don_t_ignore_errors">#</a></span></h2>

<p>Domain error handlers are not a substitute for closing down a
process when an error occurs.</p>
<p>By the very nature of how <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw"><code>throw</code></a> works in JavaScript, there is almost
never any way to safely "pick up where it left off", without leaking
references, or creating some other sort of undefined brittle state.</p>
<p>The safest way to respond to a thrown error is to shut down the
process. Of course, in a normal web server, there may be many
open connections, and it is not reasonable to abruptly shut those down
because an error was triggered by someone else.</p>
<p>The better approach is to send an error response to the request that
triggered the error, while letting the others finish in their normal
time, and stop listening for new requests in that worker.</p>
<p>In this way, <code>domain</code> usage goes hand-in-hand with the cluster module,
since the master process can fork a new worker when a worker
encounters an error. For Node.js programs that scale to multiple
machines, the terminating proxy or service registry can take note of
the failure, and react accordingly.</p>
<p>For example, this is not a good idea:</p>
<pre><code class="language-js">// XXX WARNING! BAD IDEA!

const d = require('domain').create();
d.on('error', (er) => {
  // The error won't crash the process, but what it does is worse!
  // Though we've prevented abrupt process restarting, we are leaking
  // resources like crazy if this ever happens.
  // This is no better than process.on('uncaughtException')!
  console.log(`error, but oh well ${er.message}`);
});
d.run(() => {
  require('http').createServer((req, res) => {
    handleRequest(req, res);
  }).listen(PORT);
});
</code></pre>
<p>By using the context of a domain, and the resilience of separating our
program into multiple worker processes, we can react more
appropriately, and handle errors with much greater safety.</p>
<pre><code class="language-js">// Much better!

const cluster = require('cluster');
const PORT = +process.env.PORT || 1337;

if (cluster.isMaster) {
  // A more realistic scenario would have more than 2 workers,
  // and perhaps not put the master and worker in the same file.
  //
  // It is also possible to get a bit fancier about logging, and
  // implement whatever custom logic is needed to prevent DoS
  // attacks and other bad behavior.
  //
  // See the options in the cluster documentation.
  //
  // The important thing is that the master does very little,
  // increasing our resilience to unexpected errors.

  cluster.fork();
  cluster.fork();

  cluster.on('disconnect', (worker) => {
    console.error('disconnect!');
    cluster.fork();
  });

} else {
  // the worker
  //
  // This is where we put our bugs!

  const domain = require('domain');

  // See the cluster documentation for more details about using
  // worker processes to serve requests. How it works, caveats, etc.

  const server = require('http').createServer((req, res) => {
    const d = domain.create();
    d.on('error', (er) => {
      console.error(`error ${er.stack}`);

      // We're in dangerous territory!
      // By definition, something unexpected occurred,
      // which we probably didn't want.
      // Anything can happen now! Be very careful!

      try {
        // Make sure we close down within 30 seconds
        const killtimer = setTimeout(() => {
          process.exit(1);
        }, 30000);
        // But don't keep the process open just for that!
        killtimer.unref();

        // Stop taking new requests.
        server.close();

        // Let the master know we're dead. This will trigger a
        // 'disconnect' in the cluster master, and then it will fork
        // a new worker.
        cluster.worker.disconnect();

        // Try to send an error to the request that triggered the problem
        res.statusCode = 500;
        res.setHeader('content-type', 'text/plain');
        res.end('Oops, there was a problem!\n');
      } catch (er2) {
        // Oh well, not much we can do at this point.
        console.error(`Error sending 500! ${er2.stack}`);
      }
    });

    // Because req and res were created before this domain existed,
    // we need to explicitly add them.
    // See the explanation of implicit vs explicit binding below.
    d.add(req);
    d.add(res);

    // Now run the handler function in the domain.
    d.run(() => {
      handleRequest(req, res);
    });
  });
  server.listen(PORT);
}

// This part is not important. Just an example routing thing.
// Put fancy application logic here.
function handleRequest(req, res) {
  switch (req.url) {
    case '/error':
      // We do some async stuff, and then...
      setTimeout(() => {
        // Whoops!
        flerb.bark();
      }, timeout);
      break;
    default:
      res.end('ok');
  }
}
</code></pre>
<h2>Additions to <code>Error</code> objects<span><a class="mark" href="#domain_additions_to_error_objects" id="domain_additions_to_error_objects">#</a></span></h2>

<p>Any time an <code>Error</code> object is routed through a domain, a few extra fields
are added to it.</p>
<ul>
<li><code>error.domain</code> The domain that first handled the error.</li>
<li><code>error.domainEmitter</code> The event emitter that emitted an <code>'error'</code> event
with the error object.</li>
<li><code>error.domainBound</code> The callback function which was bound to the
domain, and passed an error as its first argument.</li>
<li><code>error.domainThrown</code> A boolean indicating whether the error was
thrown, emitted, or passed to a bound callback function.</li>
</ul>
<h2>Implicit binding<span><a class="mark" href="#domain_implicit_binding" id="domain_implicit_binding">#</a></span></h2>

<p>If domains are in use, then all <strong>new</strong> <code>EventEmitter</code> objects (including
Stream objects, requests, responses, etc.) will be implicitly bound to
the active domain at the time of their creation.</p>
<p>Additionally, callbacks passed to lowlevel event loop requests (such as
to <code>fs.open()</code>, or other callback-taking methods) will automatically be
bound to the active domain. If they throw, then the domain will catch
the error.</p>
<p>In order to prevent excessive memory usage, <code>Domain</code> objects themselves
are not implicitly added as children of the active domain. If they
were, then it would be too easy to prevent request and response objects
from being properly garbage collected.</p>
<p>To nest <code>Domain</code> objects as children of a parent <code>Domain</code> they must be
explicitly added.</p>
<p>Implicit binding routes thrown errors and <code>'error'</code> events to the
<code>Domain</code>'s <code>'error'</code> event, but does not register the <code>EventEmitter</code> on the
<code>Domain</code>.
Implicit binding only takes care of thrown errors and <code>'error'</code> events.</p>
<h2>Explicit binding<span><a class="mark" href="#domain_explicit_binding" id="domain_explicit_binding">#</a></span></h2>

<p>Sometimes, the domain in use is not the one that ought to be used for a
specific event emitter. Or, the event emitter could have been created
in the context of one domain, but ought to instead be bound to some
other domain.</p>
<p>For example, there could be one domain in use for an HTTP server, but
perhaps we would like to have a separate domain to use for each request.</p>
<p>That is possible via explicit binding.</p>
<pre><code class="language-js">// Create a top-level domain for the server
const domain = require('domain');
const http = require('http');
const serverDomain = domain.create();

serverDomain.run(() => {
  // Server is created in the scope of serverDomain
  http.createServer((req, res) => {
    // Req and res are also created in the scope of serverDomain
    // however, we'd prefer to have a separate domain for each request.
    // create it first thing, and add req and res to it.
    const reqd = domain.create();
    reqd.add(req);
    reqd.add(res);
    reqd.on('error', (er) => {
      console.error('Error', er, req.url);
      try {
        res.writeHead(500);
        res.end('Error occurred, sorry.');
      } catch (er2) {
        console.error('Error sending 500', er2, req.url);
      }
    });
  }).listen(1337);
});
</code></pre>
<h2><code>domain.create()</code><span><a class="mark" href="#domain_domain_create" id="domain_domain_create">#</a></span></h2>
<ul>
<li>Returns: <a href="#domain_class_domain" class="type">&#x3C;Domain></a></li>
</ul>
<h2>Class: <code>Domain</code><span><a class="mark" href="#domain_class_domain" id="domain_class_domain">#</a></span></h2>
<ul>
<li>Extends: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>The <code>Domain</code> class encapsulates the functionality of routing errors and
uncaught exceptions to the active <code>Domain</code> object.</p>
<p>To handle the errors that it catches, listen to its <code>'error'</code> event.</p>
<h3><code>domain.members</code><span><a class="mark" href="#domain_domain_members" id="domain_domain_members">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a></li>
</ul>
<p>An array of timers and event emitters that have been explicitly added
to the domain.</p>
<h3><code>domain.add(emitter)</code><span><a class="mark" href="#domain_domain_add_emitter" id="domain_domain_add_emitter">#</a></span></h3>
<ul>
<li><code>emitter</code> <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a> | <a href="#timers_timers" class="type">&#x3C;Timer></a> emitter or timer to be added to the domain</li>
</ul>
<p>Explicitly adds an emitter to the domain. If any event handlers called by
the emitter throw an error, or if the emitter emits an <code>'error'</code> event, it
will be routed to the domain's <code>'error'</code> event, just like with implicit
binding.</p>
<p>This also works with timers that are returned from <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a> and
<a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a>. If their callback function throws, it will be caught by
the domain <code>'error'</code> handler.</p>
<p>If the Timer or <code>EventEmitter</code> was already bound to a domain, it is removed
from that one, and bound to this one instead.</p>
<h3><code>domain.bind(callback)</code><span><a class="mark" href="#domain_domain_bind_callback" id="domain_domain_bind_callback">#</a></span></h3>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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">&#x3C;Function></a> The bound function</li>
</ul>
<p>The returned function will be a wrapper around the supplied callback
function. When the returned function is called, any errors that are
thrown will be routed to the domain's <code>'error'</code> event.</p>
<pre><code class="language-js">const d = domain.create();

function readSomeFile(filename, cb) {
  fs.readFile(filename, 'utf8', d.bind((er, data) => {
    // If this throws, it will also be passed to the domain.
    return cb(er, data ? JSON.parse(data) : null);
  }));
}

d.on('error', (er) => {
  // An error occurred somewhere. If we throw it now, it will crash the program
  // with the normal line number and stack message.
});
</code></pre>
<h3><code>domain.enter()</code><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><code>domain.exit()</code><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><code>domain.intercept(callback)</code><span><a class="mark" href="#domain_domain_intercept_callback" id="domain_domain_intercept_callback">#</a></span></h3>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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">&#x3C;Function></a> The intercepted function</li>
</ul>
<p>This method is almost identical to <a href="#domain_domain_bind_callback"><code>domain.bind(callback)</code></a>. However, in
addition to catching thrown errors, it will also intercept <a href="#errors_class_error"><code>Error</code></a>
objects sent as the first argument to the function.</p>
<p>In this way, the common <code>if (err) return callback(err);</code> pattern can be replaced
with a single error handler in a single place.</p>
<pre><code class="language-js">const d = domain.create();

function readSomeFile(filename, cb) {
  fs.readFile(filename, 'utf8', d.intercept((data) => {
    // Note, the first argument is never passed to the
    // callback since it is assumed to be the 'Error' argument
    // and thus intercepted by the domain.

    // If this throws, it will also be passed to the domain
    // so the error-handling logic can be moved to the 'error'
    // event on the domain instead of being repeated throughout
    // the program.
    return cb(null, JSON.parse(data));
  }));
}

d.on('error', (er) => {
  // An error occurred somewhere. If we throw it now, it will crash the program
  // with the normal line number and stack message.
});
</code></pre>
<h3><code>domain.remove(emitter)</code><span><a class="mark" href="#domain_domain_remove_emitter" id="domain_domain_remove_emitter">#</a></span></h3>
<ul>
<li><code>emitter</code> <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a> | <a href="#timers_timers" class="type">&#x3C;Timer></a> emitter or timer to be removed from the domain</li>
</ul>
<p>The opposite of <a href="#domain_domain_add_emitter"><code>domain.add(emitter)</code></a>. Removes domain handling from the
specified emitter.</p>
<h3><code>domain.run(fn[, ...args])</code><span><a class="mark" href="#domain_domain_run_fn_args" id="domain_domain_run_fn_args">#</a></span></h3>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Run the supplied function in the context of the domain, implicitly
binding all event emitters, timers, and lowlevel requests that are
created in that context. Optionally, arguments can be passed to
the function.</p>
<p>This is the most basic way to use a domain.</p>
<pre><code class="language-js">const domain = require('domain');
const fs = require('fs');
const d = domain.create();
d.on('error', (er) => {
  console.error('Caught error!', er);
});
d.run(() => {
  process.nextTick(() => {
    setTimeout(() => { // Simulating some various async stuff
      fs.open('non-existent file', 'r', (er, fd) => {
        if (er) throw er;
        // proceed...
      });
    }, 100);
  });
});
</code></pre>
<p>In this example, the <code>d.on('error')</code> handler will be triggered, rather
than crashing the program.</p>
<h2>Domains and promises<span><a class="mark" href="#domain_domains_and_promises" id="domain_domains_and_promises">#</a></span></h2>
<p>As of Node.js 8.0.0, the handlers of promises are run inside the domain in
which the call to <code>.then()</code> or <code>.catch()</code> itself was made:</p>
<pre><code class="language-js">const d1 = domain.create();
const d2 = domain.create();

let p;
d1.run(() => {
  p = Promise.resolve(42);
});

d2.run(() => {
  p.then((v) => {
    // running in d2
  });
});
</code></pre>
<p>A callback may be bound to a specific domain using <a href="#domain_domain_bind_callback"><code>domain.bind(callback)</code></a>:</p>
<pre><code class="language-js">const d1 = domain.create();
const d2 = domain.create();

let p;
d1.run(() => {
  p = Promise.resolve(42);
});

d2.run(() => {
  p.then(p.domain.bind((v) => {
    // running in d1
  }));
});
</code></pre>
<p>Domains will not interfere with the error handling mechanisms for
promises. In other words, no <code>'error'</code> event will be emitted for unhandled
<code>Promise</code> rejections.</p>
<h1>ECMAScript modules<span><a class="mark" href="#esm_ecmascript_modules" id="esm_ecmascript_modules">#</a></span></h1>


<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<h2>Introduction<span><a class="mark" href="#esm_introduction" id="esm_introduction">#</a></span></h2>

<p>ECMAScript modules are <a href="https://tc39.github.io/ecma262/#sec-modules">the official standard format</a> to package JavaScript
code for reuse. Modules are defined using a variety of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import"><code>import</code></a> and
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export"><code>export</code></a> statements.</p>
<p>The following example of an ES module exports a function:</p>
<pre><code class="language-js">// addTwo.mjs
function addTwo(num) {
  return num + 2;
}

export { addTwo };
</code></pre>
<p>The following example of an ES module imports the function from <code>addTwo.mjs</code>:</p>
<pre><code class="language-js">// app.mjs
import { addTwo } from './addTwo.mjs';

// Prints: 6
console.log(addTwo(4));
</code></pre>
<p>Node.js fully supports ECMAScript modules as they are currently specified and
provides limited interoperability between them and the existing module format,
<a href="modules.html">CommonJS</a>.</p>
<p>Node.js contains support for ES Modules based upon the
<a href="https://github.com/nodejs/node-eps/blob/master/002-es-modules.md">Node.js EP for ES Modules</a> and the <a href="https://github.com/nodejs/modules/blob/master/doc/plan-for-new-modules-implementation.md">ECMAScript-modules implementation</a>.</p>
<p>Expect major changes in the implementation including interoperability support,
specifier resolution, and default behavior.</p>
<h2>Enabling<span><a class="mark" href="#esm_enabling" id="esm_enabling">#</a></span></h2>

<p>Experimental support for ECMAScript modules is enabled by default.
Node.js will treat the following as ES modules when passed to <code>node</code> as the
initial input, or when referenced by <code>import</code> statements within ES module code:</p>
<ul>
<li>
<p>Files ending in <code>.mjs</code>.</p>
</li>
<li>
<p>Files ending in <code>.js</code> when the nearest parent <code>package.json</code> file contains a
top-level field <code>"type"</code> with a value of <code>"module"</code>.</p>
</li>
<li>
<p>Strings passed in as an argument to <code>--eval</code> or <code>--print</code>, or piped to
<code>node</code> via <code>STDIN</code>, with the flag <code>--input-type=module</code>.</p>
</li>
</ul>
<p>Node.js will treat as CommonJS all other forms of input, such as <code>.js</code> files
where the nearest parent <code>package.json</code> file contains no top-level <code>"type"</code>
field, or string input without the flag <code>--input-type</code>. This behavior is to
preserve backward compatibility. However, now that Node.js supports both
CommonJS and ES modules, it is best to be explicit whenever possible. Node.js
will treat the following as CommonJS when passed to <code>node</code> as the initial input,
or when referenced by <code>import</code> statements within ES module code:</p>
<ul>
<li>
<p>Files ending in <code>.cjs</code>.</p>
</li>
<li>
<p>Files ending in <code>.js</code> when the nearest parent <code>package.json</code> file contains a
top-level field <code>"type"</code> with a value of <code>"commonjs"</code>.</p>
</li>
<li>
<p>Strings passed in as an argument to <code>--eval</code> or <code>--print</code>, or piped to
<code>node</code> via <code>STDIN</code>, with the flag <code>--input-type=commonjs</code>.</p>
</li>
</ul>
<h3><code>package.json</code> <code>"type"</code> field<span><a class="mark" href="#esm_package_json_type_field" id="esm_package_json_type_field">#</a></span></h3>
<p>Files ending with <code>.js</code> will be loaded as ES modules when the nearest parent
<code>package.json</code> file contains a top-level field <code>"type"</code> with a value of
<code>"module"</code>.</p>
<p>The nearest parent <code>package.json</code> is defined as the first <code>package.json</code> found
when searching in the current folder, that folder’s parent, and so on up
until the root of the volume is reached.</p>
<!-- eslint-skip -->
<pre><code class="language-js">// package.json
{
  "type": "module"
}
</code></pre>
<pre><code class="language-bash"># In same folder as above package.json
node my-app.js # Runs as ES module
</code></pre>
<p>If the nearest parent <code>package.json</code> lacks a <code>"type"</code> field, or contains
<code>"type": "commonjs"</code>, <code>.js</code> files are treated as CommonJS. If the volume root is
reached and no <code>package.json</code> is found, Node.js defers to the default, a
<code>package.json</code> with no <code>"type"</code> field.</p>
<p><code>import</code> statements of <code>.js</code> files are treated as ES modules if the nearest
parent <code>package.json</code> contains <code>"type": "module"</code>.</p>
<pre><code class="language-js">// my-app.js, part of the same example as above
import './startup.js'; // Loaded as ES module because of package.json
</code></pre>
<p>Package authors should include the <code>"type"</code> field, even in packages where all
sources are CommonJS. Being explicit about the <code>type</code> of the package will
future-proof the package in case the default type of Node.js ever changes, and
it will also make things easier for build tools and loaders to determine how the
files in the package should be interpreted.</p>
<p>Regardless of the value of the <code>"type"</code> field, <code>.mjs</code> files are always treated
as ES modules and <code>.cjs</code> files are always treated as CommonJS.</p>
<h3>Package scope and file extensions<span><a class="mark" href="#esm_package_scope_and_file_extensions" id="esm_package_scope_and_file_extensions">#</a></span></h3>
<p>A folder containing a <code>package.json</code> file, and all subfolders below that folder
down until the next folder containing another <code>package.json</code>, is considered a
<em>package scope</em>. The <code>"type"</code> field defines how <code>.js</code> files should be treated
within a particular <code>package.json</code> file’s package scope. Every package in a
project’s <code>node_modules</code> folder contains its own <code>package.json</code> file, so each
project’s dependencies have their own package scopes. A <code>package.json</code> lacking a
<code>"type"</code> field is treated as if it contained <code>"type": "commonjs"</code>.</p>
<p>The package scope applies not only to initial entry points (<code>node my-app.js</code>)
but also to files referenced by <code>import</code> statements and <code>import()</code> expressions.</p>
<pre><code class="language-js">// my-app.js, in an ES module package scope because there is a package.json
// file in the same folder with "type": "module".

import './startup/init.js';
// Loaded as ES module since ./startup contains no package.json file,
// and therefore inherits the ES module package scope from one level up.

import 'commonjs-package';
// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
// lacks a "type" field or contains "type": "commonjs".

import './node_modules/commonjs-package/index.js';
// Loaded as CommonJS since ./node_modules/commonjs-package/package.json
// lacks a "type" field or contains "type": "commonjs".
</code></pre>
<p>Files ending with <code>.mjs</code> are always loaded as ES modules regardless of package
scope.</p>
<p>Files ending with <code>.cjs</code> are always loaded as CommonJS regardless of package
scope.</p>
<pre><code class="language-js">import './legacy-file.cjs';
// Loaded as CommonJS since .cjs is always loaded as CommonJS.

import 'commonjs-package/src/index.mjs';
// Loaded as ES module since .mjs is always loaded as ES module.
</code></pre>
<p>The <code>.mjs</code> and <code>.cjs</code> extensions may be used to mix types within the same
package scope:</p>
<ul>
<li>
<p>Within a <code>"type": "module"</code> package scope, Node.js can be instructed to
interpret a particular file as CommonJS by naming it with a <code>.cjs</code> extension
(since both <code>.js</code> and <code>.mjs</code> files are treated as ES modules within a
<code>"module"</code> package scope).</p>
</li>
<li>
<p>Within a <code>"type": "commonjs"</code> package scope, Node.js can be instructed to
interpret a particular file as an ES module by naming it with an <code>.mjs</code>
extension (since both <code>.js</code> and <code>.cjs</code> files are treated as CommonJS within a
<code>"commonjs"</code> package scope).</p>
</li>
</ul>
<h3><code>--input-type</code> flag<span><a class="mark" href="#esm_input_type_flag" id="esm_input_type_flag">#</a></span></h3>
<p>Strings passed in as an argument to <code>--eval</code> or <code>--print</code> (or <code>-e</code> or <code>-p</code>), or
piped to <code>node</code> via <code>STDIN</code>, will be treated as ES modules when the
<code>--input-type=module</code> flag is set.</p>
<pre><code class="language-bash">node --input-type=module --eval "import { sep } from 'path'; console.log(sep);"

echo "import { sep } from 'path'; console.log(sep);" | node --input-type=module
</code></pre>
<p>For completeness there is also <code>--input-type=commonjs</code>, for explicitly running
string input as CommonJS. This is the default behavior if <code>--input-type</code> is
unspecified.</p>
<h2>Packages<span><a class="mark" href="#esm_packages" id="esm_packages">#</a></span></h2>
<h3>Package entry points<span><a class="mark" href="#esm_package_entry_points" id="esm_package_entry_points">#</a></span></h3>
<p>In a package’s <code>package.json</code> file, two fields can define entry points for a
package: <code>"main"</code> and <code>"exports"</code>. The <code>"main"</code> field is supported in all
versions of Node.js, but its capabilities are limited: it only defines the main
entry point of the package.</p>
<p>The <code>"exports"</code> field provides an alternative to <code>"main"</code> where the package
main entry point can be defined while also encapsulating the package,
<strong>preventing any other entry points besides those defined in <code>"exports"</code></strong>.
This encapsulation allows module authors to define a public interface for
their package.</p>
<p>If both <code>"exports"</code> and <code>"main"</code> are defined, the <code>"exports"</code> field takes
precedence over <code>"main"</code>. <code>"exports"</code> are not specific to ES modules or
CommonJS; <code>"main"</code> will be overridden by <code>"exports"</code> if it exists. As such
<code>"main"</code> cannot be used as a fallback for CommonJS but it can be used as a
fallback for legacy versions of Node.js that do not support the <code>"exports"</code>
field.</p>
<p><a href="#esm_conditional_exports">Conditional exports</a> can be used within <code>"exports"</code> to define different
package entry points per environment, including whether the package is
referenced via <code>require</code> or via <code>import</code>. For more information about supporting
both CommonJS and ES Modules in a single package please consult
<a href="#esm_dual_commonjs_es_module_packages">the dual CommonJS/ES module packages section</a>.</p>
<p><strong>Warning</strong>: Introducing the <code>"exports"</code> field prevents consumers of a package
from using any entry points that are not defined, including the <code>package.json</code>
(e.g. <code>require('your-package/package.json')</code>. <strong>This will likely be a breaking
change.</strong></p>
<p>To make the introduction of <code>"exports"</code> non-breaking, ensure that every
previously supported entry point is exported. It is best to explicitly specify
entry points so that the package’s public API is well-defined. For example,
a project that previous exported <code>main</code>, <code>lib</code>,
<code>feature</code>, and the <code>package.json</code> could use the following <code>package.exports</code>:</p>
<pre><code class="language-json">{
  "name": "my-mod",
  "exports": {
    ".": "./lib/index.js",
    "./lib": "./lib/index.js",
    "./lib/index": "./lib/index.js",
    "./lib/index.js": "./lib/index.js",
    "./feature": "./feature/index.js",
    "./feature/index.js": "./feature/index.js",
    "./package.json": "./package.json"
  }
}
</code></pre>
<p>Alternatively a project could choose to export entire folders:</p>
<pre><code class="language-json">{
  "name": "my-mod",
  "exports": {
    ".": "./lib/index.js",
    "./lib": "./lib/index.js",
    "./lib/": "./lib/",
    "./feature": "./feature/index.js",
    "./feature/": "./feature/",
    "./package.json": "./package.json"
  }
}
</code></pre>
<p>As a last resort, package encapsulation can be disabled entirely by creating an
export for the root of the package <code>"./": "./"</code>. This will expose every file in
the package at the cost of disabling the encapsulation and potential tooling
benefits this provides. As the ES Module loader in Node.js enforces the use of
<a href="#esm_mandatory_file_extensions">the full specifier path</a>, exporting the root rather than being explicit
about entry is less expressive than either of the prior examples. Not only
will encapsulation be lost but module consumers will be unable to
<code>import feature from 'my-mod/feature'</code> as they will need to provide the full
path <code>import feature from 'my-mod/feature/index.js</code>.</p>
<h4>Main entry point export<span><a class="mark" href="#esm_main_entry_point_export" id="esm_main_entry_point_export">#</a></span></h4>
<p>To set the main entry point for a package, it is advisable to define both
<code>"exports"</code> and <code>"main"</code> in the package’s <code>package.json</code> file:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "main": "./main.js",
  "exports": "./main.js"
}
</code></pre>
<p>The benefit of doing this is that when using the <code>"exports"</code> field all
subpaths of the package will no longer be available to importers under
<code>require('pkg/subpath.js')</code>, and instead they will get a new error,
<code>ERR_PACKAGE_PATH_NOT_EXPORTED</code>.</p>
<p>This encapsulation of exports provides more reliable guarantees
about package interfaces for tools and when handling semver upgrades for a
package. It is not a strong encapsulation since a direct require of any
absolute subpath of the package such as
<code>require('/path/to/node_modules/pkg/subpath.js')</code> will still load <code>subpath.js</code>.</p>
<h4>Subpath exports<span><a class="mark" href="#esm_subpath_exports" id="esm_subpath_exports">#</a></span></h4>
<p>When using the <code>"exports"</code> field, custom subpaths can be defined along
with the main entry point by treating the main entry point as the
<code>"."</code> subpath:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "main": "./main.js",
  "exports": {
    ".": "./main.js",
    "./submodule": "./src/submodule.js"
  }
}
</code></pre>
<p>Now only the defined subpath in <code>"exports"</code> can be imported by a
consumer:</p>
<pre><code class="language-js">import submodule from 'es-module-package/submodule';
// Loads ./node_modules/es-module-package/src/submodule.js
</code></pre>
<p>While other subpaths will error:</p>
<pre><code class="language-js">import submodule from 'es-module-package/private-module.js';
// Throws ERR_PACKAGE_PATH_NOT_EXPORTED
</code></pre>
<p>Entire folders can also be mapped with package exports:</p>
<!-- eslint-skip -->
<pre><code class="language-js">// ./node_modules/es-module-package/package.json
{
  "exports": {
    "./features/": "./src/features/"
  }
}
</code></pre>
<p>With the above, all modules within the <code>./src/features/</code> folder
are exposed deeply to <code>import</code> and <code>require</code>:</p>
<pre><code class="language-js">import feature from 'es-module-package/features/x.js';
// Loads ./node_modules/es-module-package/src/features/x.js
</code></pre>
<p>When using folder mappings, ensure that you do want to expose every
module inside the subfolder. Any modules which are not public
should be moved to another folder to retain the encapsulation
benefits of exports.</p>
<h4>Package exports fallbacks<span><a class="mark" href="#esm_package_exports_fallbacks" id="esm_package_exports_fallbacks">#</a></span></h4>
<p>For possible new specifier support in future, array fallbacks are
supported for all invalid specifiers:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "exports": {
    "./submodule": ["not:valid", "./submodule.js"]
  }
}
</code></pre>
<p>Since <code>"not:valid"</code> is not a valid specifier, <code>"./submodule.js"</code> is used
instead as the fallback, as if it were the only target.</p>
<h4>Exports sugar<span><a class="mark" href="#esm_exports_sugar" id="esm_exports_sugar">#</a></span></h4>
<p>If the <code>"."</code> export is the only export, the <code>"exports"</code> field provides sugar
for this case being the direct <code>"exports"</code> field value.</p>
<p>If the <code>"."</code> export has a fallback array or string value, then the <code>"exports"</code>
field can be set to this value directly.</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "exports": {
    ".": "./main.js"
  }
}
</code></pre>
<p>can be written:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "exports": "./main.js"
}
</code></pre>
<h4>Conditional exports<span><a class="mark" href="#esm_conditional_exports" id="esm_conditional_exports">#</a></span></h4>
<p>Conditional exports provide a way to map to different paths depending on
certain conditions. They are supported for both CommonJS and ES module imports.</p>
<p>For example, a package that wants to provide different ES module exports for
<code>require()</code> and <code>import</code> can be written:</p>
<!-- eslint-skip -->
<pre><code class="language-js">// package.json
{
  "main": "./main-require.cjs",
  "exports": {
    "import": "./main-module.js",
    "require": "./main-require.cjs"
  },
  "type": "module"
}
</code></pre>
<p>Node.js supports the following conditions:</p>
<ul>
<li><code>"import"</code> - matched when the package is loaded via <code>import</code> or
<code>import()</code>. Can reference either an ES module or CommonJS file, as both
<code>import</code> and <code>import()</code> can load either ES module or CommonJS sources.</li>
<li><code>"require"</code> - matched when the package is loaded via <code>require()</code>.
As <code>require()</code> only supports CommonJS, the referenced file must be CommonJS.</li>
<li><code>"node"</code> - matched for any Node.js environment. Can be a CommonJS or ES
module file. <em>This condition should always come after <code>"import"</code> or
<code>"require"</code>.</em></li>
<li><code>"default"</code> - the generic fallback that will always match. Can be a CommonJS
or ES module file. <em>This condition should always come last.</em></li>
</ul>
<p>Condition matching is applied in object order from first to last within the
<code>"exports"</code> object. <em>The general rule is that conditions should be used
from most specific to least specific in object order.</em></p>
<p>Other conditions such as <code>"browser"</code>, <code>"electron"</code>, <code>"deno"</code>, <code>"react-native"</code>,
etc. are ignored by Node.js but may be used by other runtimes or tools.
Further restrictions, definitions or guidance on condition names may be
provided in the future.</p>
<p>Using the <code>"import"</code> and <code>"require"</code> conditions can lead to some hazards,
which are explained further in
<a href="#esm_dual_commonjs_es_module_packages">the dual CommonJS/ES module packages section</a>.</p>
<p>Conditional exports can also be extended to exports subpaths, for example:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "main": "./main.js",
  "exports": {
    ".": "./main.js",
    "./feature": {
      "browser": "./feature-browser.js",
      "default": "./feature.js"
    }
  }
}
</code></pre>
<p>Defines a package where <code>require('pkg/feature')</code> and <code>import 'pkg/feature'</code>
could provide different implementations between the browser and Node.js,
given third-party tool support for a <code>"browser"</code> condition.</p>
<h4>Nested conditions<span><a class="mark" href="#esm_nested_conditions" id="esm_nested_conditions">#</a></span></h4>
<p>In addition to direct mappings, Node.js also supports nested condition objects.</p>
<p>For example, to define a package that only has dual mode entry points for
use in Node.js but not the browser:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  "main": "./main.js",
  "exports": {
    "browser": "./feature-browser.mjs",
    "node": {
      "import": "./feature-node.mjs",
      "require": "./feature-node.cjs"
    }
  }
}
</code></pre>
<p>Conditions continue to be matched in order as with flat conditions. If
a nested conditional does not have any mapping it will continue checking
the remaining conditions of the parent condition. In this way nested
conditions behave analogously to nested JavaScript <code>if</code> statements.</p>
<h4>Self-referencing a package using its name<span><a class="mark" href="#esm_self_referencing_a_package_using_its_name" id="esm_self_referencing_a_package_using_its_name">#</a></span></h4>
<p>Within a package, the values defined in the package’s
<code>package.json</code> <code>"exports"</code> field can be referenced via the package’s name.
For example, assuming the <code>package.json</code> is:</p>
<pre><code class="language-json">// package.json
{
  "name": "a-package",
  "exports": {
    ".": "./main.mjs",
    "./foo": "./foo.js"
  }
}
</code></pre>
<p>Then any module <em>in that package</em> can reference an export in the package itself:</p>
<pre><code class="language-js">// ./a-module.mjs
import { something } from 'a-package'; // Imports "something" from ./main.mjs.
</code></pre>
<p>Self-referencing is available only if <code>package.json</code> has <code>exports</code>, and will
allow importing only what that <code>exports</code> (in the <code>package.json</code>) allows.
So the code below, given the package above, will generate a runtime error:</p>
<pre><code class="language-js">// ./another-module.mjs

// Imports "another" from ./m.mjs. Fails because
// the "package.json" "exports" field
// does not provide an export named "./m.mjs".
import { another } from 'a-package/m.mjs';
</code></pre>
<p>Self-referencing is also available when using <code>require</code>, both in an ES module,
and in a CommonJS one. For example, this code will also work:</p>
<pre><code class="language-js">// ./a-module.js
const { something } = require('a-package/foo'); // Loads from ./foo.js.
</code></pre>
<h3>Dual CommonJS/ES module packages<span><a class="mark" href="#esm_dual_commonjs_es_module_packages" id="esm_dual_commonjs_es_module_packages">#</a></span></h3>
<p>Prior to the introduction of support for ES modules in Node.js, it was a common
pattern for package authors to include both CommonJS and ES module JavaScript
sources in their package, with <code>package.json</code> <code>"main"</code> specifying the CommonJS
entry point and <code>package.json</code> <code>"module"</code> specifying the ES module entry point.
This enabled Node.js to run the CommonJS entry point while build tools such as
bundlers used the ES module entry point, since Node.js ignored (and still
ignores) the top-level <code>"module"</code> field.</p>
<p>Node.js can now run ES module entry points, and a package can contain both
CommonJS and ES module entry points (either via separate specifiers such as
<code>'pkg'</code> and <code>'pkg/es-module'</code>, or both at the same specifier via <a href="#esm_conditional_exports">Conditional
exports</a>). Unlike in the scenario where <code>"module"</code> is only used by bundlers,
or ES module files are transpiled into CommonJS on the fly before evaluation by
Node.js, the files referenced by the ES module entry point are evaluated as ES
modules.</p>
<h4>Dual package hazard<span><a class="mark" href="#esm_dual_package_hazard" id="esm_dual_package_hazard">#</a></span></h4>
<p>When an application is using a package that provides both CommonJS and ES module
sources, there is a risk of certain bugs if both versions of the package get
loaded. This potential comes from the fact that the <code>pkgInstance</code> created by
<code>const pkgInstance = require('pkg')</code> is not the same as the <code>pkgInstance</code>
created by <code>import pkgInstance from 'pkg'</code> (or an alternative main path like
<code>'pkg/module'</code>). This is the “dual package hazard,” where two versions of the
same package can be loaded within the same runtime environment. While it is
unlikely that an application or package would intentionally load both versions
directly, it is common for an application to load one version while a dependency
of the application loads the other version. This hazard can happen because
Node.js supports intermixing CommonJS and ES modules, and can lead to unexpected
behavior.</p>
<p>If the package main export is a constructor, an <code>instanceof</code> comparison of
instances created by the two versions returns <code>false</code>, and if the export is an
object, properties added to one (like <code>pkgInstance.foo = 3</code>) are not present on
the other. This differs from how <code>import</code> and <code>require</code> statements work in
all-CommonJS or all-ES module environments, respectively, and therefore is
surprising to users. It also differs from the behavior users are familiar with
when using transpilation via tools like <a href="https://babeljs.io/">Babel</a> or <a href="https://github.com/standard-things/esm#readme"><code>esm</code></a>.</p>
<h4>Writing dual packages while avoiding or minimizing hazards<span><a class="mark" href="#esm_writing_dual_packages_while_avoiding_or_minimizing_hazards" id="esm_writing_dual_packages_while_avoiding_or_minimizing_hazards">#</a></span></h4>
<p>First, the hazard described in the previous section occurs when a package
contains both CommonJS and ES module sources and both sources are provided for
use in Node.js, either via separate main entry points or exported paths. A
package could instead be written where any version of Node.js receives only
CommonJS sources, and any separate ES module sources the package may contain
could be intended only for other environments such as browsers. Such a package
would be usable by any version of Node.js, since <code>import</code> can refer to CommonJS
files; but it would not provide any of the advantages of using ES module syntax.</p>
<p>A package could also switch from CommonJS to ES module syntax in a breaking
change version bump. This has the disadvantage that the newest version
of the package would only be usable in ES module-supporting versions of Node.js.</p>
<p>Every pattern has tradeoffs, but there are two broad approaches that satisfy the
following conditions:</p>
<ol>
<li>The package is usable via both <code>require</code> and <code>import</code>.</li>
<li>The package is usable in both current Node.js and older versions of Node.js
that lack support for ES modules.</li>
<li>The package main entry point, e.g. <code>'pkg'</code> can be used by both <code>require</code> to
resolve to a CommonJS file and by <code>import</code> to resolve to an ES module file.
(And likewise for exported paths, e.g. <code>'pkg/feature'</code>.)</li>
<li>The package provides named exports, e.g. <code>import { name } from 'pkg'</code> rather
than <code>import pkg from 'pkg'; pkg.name</code>.</li>
<li>The package is potentially usable in other ES module environments such as
browsers.</li>
<li>The hazards described in the previous section are avoided or minimized.</li>
</ol>
<h5>Approach #1: Use an ES module wrapper<span><a class="mark" href="#esm_approach_1_use_an_es_module_wrapper" id="esm_approach_1_use_an_es_module_wrapper">#</a></span></h5>
<p>Write the package in CommonJS or transpile ES module sources into CommonJS, and
create an ES module wrapper file that defines the named exports. Using
<a href="#esm_conditional_exports">Conditional exports</a>, the ES module wrapper is used for <code>import</code> and the
CommonJS entry point for <code>require</code>.</p>
<!-- eslint-skip -->
<pre><code class="language-js">// ./node_modules/pkg/package.json
{
  "type": "module",
  "main": "./index.cjs",
  "exports": {
    "import": "./wrapper.mjs",
    "require": "./index.cjs"
  }
}
</code></pre>
<pre><code class="language-js">// ./node_modules/pkg/index.cjs
exports.name = 'value';
</code></pre>
<pre><code class="language-js">// ./node_modules/pkg/wrapper.mjs
import cjsModule from './index.cjs';
export const name = cjsModule.name;
</code></pre>
<p>In this example, the <code>name</code> from <code>import { name } from 'pkg'</code> is the same
singleton as the <code>name</code> from <code>const { name } = require('pkg')</code>. Therefore <code>===</code>
returns <code>true</code> when comparing the two <code>name</code>s and the divergent specifier hazard
is avoided.</p>
<p>If the module is not simply a list of named exports, but rather contains a
unique function or object export like <code>module.exports = function () { ... }</code>,
or if support in the wrapper for the <code>import pkg from 'pkg'</code> pattern is desired,
then the wrapper would instead be written to export the default optionally
along with any named exports as well:</p>
<pre><code class="language-js">import cjsModule from './index.cjs';
export const name = cjsModule.name;
export default cjsModule;
</code></pre>
<p>This approach is appropriate for any of the following use cases:</p>
<ul>
<li>The package is currently written in CommonJS and the author would prefer not
to refactor it into ES module syntax, but wishes to provide named exports for
ES module consumers.</li>
<li>The package has other packages that depend on it, and the end user might
install both this package and those other packages. For example a <code>utilities</code>
package is used directly in an application, and a <code>utilities-plus</code> package
adds a few more functions to <code>utilities</code>. Because the wrapper exports
underlying CommonJS files, it doesn’t matter if <code>utilities-plus</code> is written in
CommonJS or ES module syntax; it will work either way.</li>
<li>The package stores internal state, and the package author would prefer not to
refactor the package to isolate its state management. See the next section.</li>
</ul>
<p>A variant of this approach not requiring conditional exports for consumers could
be to add an export, e.g. <code>"./module"</code>, to point to an all-ES module-syntax
version of the package. This could be used via <code>import 'pkg/module'</code> by users
who are certain that the CommonJS version will not be loaded anywhere in the
application, such as by dependencies; or if the CommonJS version can be loaded
but doesn’t affect the ES module version (for example, because the package is
stateless):</p>
<!-- eslint-skip -->
<pre><code class="language-js">// ./node_modules/pkg/package.json
{
  "type": "module",
  "main": "./index.cjs",
  "exports": {
    ".": "./index.cjs",
    "./module": "./wrapper.mjs"
  }
}
</code></pre>
<h5>Approach #2: Isolate state<span><a class="mark" href="#esm_approach_2_isolate_state" id="esm_approach_2_isolate_state">#</a></span></h5>
<p>A <code>package.json</code> file can define the separate CommonJS and ES module entry
points directly:</p>
<!-- eslint-skip -->
<pre><code class="language-js">// ./node_modules/pkg/package.json
{
  "type": "module",
  "main": "./index.cjs",
  "exports": {
    "import": "./index.mjs",
    "require": "./index.cjs"
  }
}
</code></pre>
<p>This can be done if both the CommonJS and ES module versions of the package are
equivalent, for example because one is the transpiled output of the other; and
the package’s management of state is carefully isolated (or the package is
stateless).</p>
<p>The reason that state is an issue is because both the CommonJS and ES module
versions of the package may get used within an application; for example, the
user’s application code could <code>import</code> the ES module version while a dependency
<code>require</code>s the CommonJS version. If that were to occur, two copies of the
package would be loaded in memory and therefore two separate states would be
present. This would likely cause hard-to-troubleshoot bugs.</p>
<p>Aside from writing a stateless package (if JavaScript’s <code>Math</code> were a package,
for example, it would be stateless as all of its methods are static), there are
some ways to isolate state so that it’s shared between the potentially loaded
CommonJS and ES module instances of the package:</p>
<ol>
<li>
<p>If possible, contain all state within an instantiated object. JavaScript’s
<code>Date</code>, for example, needs to be instantiated to contain state; if it were a
package, it would be used like this:</p>
<pre><code class="language-js">import Date from 'date';
const someDate = new Date();
// someDate contains state; Date does not
</code></pre>
<p>The <code>new</code> keyword isn’t required; a package’s function can return a new
object, or modify a passed-in object, to keep the state external to the
package.</p>
</li>
<li>
<p>Isolate the state in one or more CommonJS files that are shared between the
CommonJS and ES module versions of the package. For example, if the CommonJS
and ES module entry points are <code>index.cjs</code> and <code>index.mjs</code>, respectively:</p>
<pre><code class="language-js">// ./node_modules/pkg/index.cjs
const state = require('./state.cjs');
module.exports.state = state;
</code></pre>
<pre><code class="language-js">// ./node_modules/pkg/index.mjs
import state from './state.cjs';
export {
  state
};
</code></pre>
<p>Even if <code>pkg</code> is used via both <code>require</code> and <code>import</code> in an application (for
example, via <code>import</code> in application code and via <code>require</code> by a dependency)
each reference of <code>pkg</code> will contain the same state; and modifying that
state from either module system will apply to both.</p>
</li>
</ol>
<p>Any plugins that attach to the package’s singleton would need to separately
attach to both the CommonJS and ES module singletons.</p>
<p>This approach is appropriate for any of the following use cases:</p>
<ul>
<li>The package is currently written in ES module syntax and the package author
wants that version to be used wherever such syntax is supported.</li>
<li>The package is stateless or its state can be isolated without too much
difficulty.</li>
<li>The package is unlikely to have other public packages that depend on it, or if
it does, the package is stateless or has state that need not be shared between
dependencies or with the overall application.</li>
</ul>
<p>Even with isolated state, there is still the cost of possible extra code
execution between the CommonJS and ES module versions of a package.</p>
<p>As with the previous approach, a variant of this approach not requiring
conditional exports for consumers could be to add an export, e.g.
<code>"./module"</code>, to point to an all-ES module-syntax version of the package:</p>
<!-- eslint-skip -->
<pre><code class="language-js">// ./node_modules/pkg/package.json
{
  "type": "module",
  "main": "./index.cjs",
  "exports": {
    ".": "./index.cjs",
    "./module": "./index.mjs"
  }
}
</code></pre>
<h2><code>import</code> Specifiers<span><a class="mark" href="#esm_import_specifiers" id="esm_import_specifiers">#</a></span></h2>
<h3>Terminology<span><a class="mark" href="#esm_terminology" id="esm_terminology">#</a></span></h3>
<p>The <em>specifier</em> of an <code>import</code> statement is the string after the <code>from</code> keyword,
e.g. <code>'path'</code> in <code>import { sep } from 'path'</code>. Specifiers are also used in
<code>export from</code> statements, and as the argument to an <code>import()</code> expression.</p>
<p>There are four types of specifiers:</p>
<ul>
<li>
<p><em>Bare specifiers</em> like <code>'some-package'</code>. They refer to an entry point of a
package by the package name.</p>
</li>
<li>
<p><em>Deep import specifiers</em> like <code>'some-package/lib/shuffle.mjs'</code>. They refer to
a path within a package prefixed by the package name.</p>
</li>
<li>
<p><em>Relative specifiers</em> like <code>'./startup.js'</code> or <code>'../config.mjs'</code>. They refer
to a path relative to the location of the importing file.</p>
</li>
<li>
<p><em>Absolute specifiers</em> like <code>'file:///opt/nodejs/config.js'</code>. They refer
directly and explicitly to a full path.</p>
</li>
</ul>
<p>Bare specifiers, and the bare specifier portion of deep import specifiers, are
strings; but everything else in a specifier is a URL.</p>
<p>Only <code>file:</code> and <code>data:</code> URLs are supported. A specifier like
<code>'https://example.com/app.js'</code> may be supported by browsers but it is not
supported in Node.js.</p>
<p>Specifiers may not begin with <code>/</code> or <code>//</code>. These are reserved for potential
future use. The root of the current volume may be referenced via <code>file:///</code>.</p>
<h4><code>data:</code> Imports<span><a class="mark" href="#esm_data_imports" id="esm_data_imports">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs"><code>data:</code> URLs</a> are supported for importing with the following MIME types:</p>
<ul>
<li><code>text/javascript</code> for ES Modules</li>
<li><code>application/json</code> for JSON</li>
<li><code>application/wasm</code> for WASM.</li>
</ul>
<p><code>data:</code> URLs only resolve <a href="#esm_terminology"><em>Bare specifiers</em></a> for builtin modules
and <a href="#esm_terminology"><em>Absolute specifiers</em></a>. Resolving
<a href="#esm_terminology"><em>Relative specifiers</em></a> will not work because <code>data:</code> is not a
<a href="https://url.spec.whatwg.org/#special-scheme">special scheme</a>. For example, attempting to load <code>./foo</code>
from <code>data:text/javascript,import "./foo";</code> will fail to resolve since there
is no concept of relative resolution for <code>data:</code> URLs. An example of a <code>data:</code>
URLs being used is:</p>
<pre><code class="language-js">import 'data:text/javascript,console.log("hello!");';
import _ from 'data:application/json,"world!"';
</code></pre>
<h2><code>import.meta</code><span><a class="mark" href="#esm_import_meta" id="esm_import_meta">#</a></span></h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>The <code>import.meta</code> metaproperty is an <code>Object</code> that contains the following
property:</p>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The absolute <code>file:</code> URL of the module.</li>
</ul>
<h2>Differences between ES modules and CommonJS<span><a class="mark" href="#esm_differences_between_es_modules_and_commonjs" id="esm_differences_between_es_modules_and_commonjs">#</a></span></h2>
<h3>Mandatory file extensions<span><a class="mark" href="#esm_mandatory_file_extensions" id="esm_mandatory_file_extensions">#</a></span></h3>
<p>A file extension must be provided when using the <code>import</code> keyword. Directory
indexes (e.g. <code>'./startup/index.js'</code>) must also be fully specified.</p>
<p>This behavior matches how <code>import</code> behaves in browser environments, assuming a
typically configured server.</p>
<h3>No <code>NODE_PATH</code><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</code>, <code>exports</code>, <code>module.exports</code>, <code>__filename</code>, <code>__dirname</code><span><a class="mark" href="#esm_no_require_exports_module_exports_filename_dirname" id="esm_no_require_exports_module_exports_filename_dirname">#</a></span></h3>
<p>These CommonJS variables are not available in ES modules.</p>
<p><code>require</code> can be imported into an ES module using <a href="#modules_module_createrequire_filename"><code>module.createRequire()</code></a>.</p>
<p>Equivalents of <code>__filename</code> and <code>__dirname</code> can be created inside of each file
via <a href="#esm_import_meta"><code>import.meta.url</code></a>.</p>
<pre><code class="language-js">import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
</code></pre>
<h3>No <code>require.resolve</code><span><a class="mark" href="#esm_no_require_resolve" id="esm_no_require_resolve">#</a></span></h3>
<p>Former use cases relying on <code>require.resolve</code> to determine the resolved path
of a module can be supported via <code>import.meta.resolve</code>, which is experimental
and supported via the <code>--experimental-import-meta-resolve</code> flag:</p>
<pre><code class="language-js">(async () => {
  const dependencyAsset = await import.meta.resolve('component-lib/asset.css');
})();
</code></pre>
<p><code>import.meta.resolve</code> also accepts a second argument which is the parent module
from which to resolve from:</p>
<pre><code class="language-js">(async () => {
  // Equivalent to import.meta.resolve('./dep')
  await import.meta.resolve('./dep', import.meta.url);
})();
</code></pre>
<p>This function is asynchronous since the ES module resolver in Node.js is
asynchronous. With the introduction of <a href="https://github.com/tc39/proposal-top-level-await">Top-Level Await</a>, these use cases
will be easier as they won't require an async function wrapper.</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>ES modules are resolved and cached based upon
<a href="https://url.spec.whatwg.org/">URL</a> semantics. This means that files containing
special characters such as <code>#</code> and <code>?</code> need to be escaped.</p>
<p>Modules will be loaded multiple times if the <code>import</code> specifier used to resolve
them have a different query or fragment.</p>
<pre><code class="language-js">import './foo.mjs?query=1'; // loads ./foo.mjs with query of "?query=1"
import './foo.mjs?query=2'; // loads ./foo.mjs with query of "?query=2"
</code></pre>
<p>For now, only modules using the <code>file:</code> protocol can be loaded.</p>
<h2>Interoperability with CommonJS<span><a class="mark" href="#esm_interoperability_with_commonjs" id="esm_interoperability_with_commonjs">#</a></span></h2>
<h3><code>require</code><span><a class="mark" href="#esm_require" id="esm_require">#</a></span></h3>
<p><code>require</code> always treats the files it references as CommonJS. This applies
whether <code>require</code> is used the traditional way within a CommonJS environment, or
in an ES module environment using <a href="#modules_module_createrequire_filename"><code>module.createRequire()</code></a>.</p>
<p>To include an ES module into CommonJS, use <a href="#esm_import_expressions"><code>import()</code></a>.</p>
<h3><code>import</code> statements<span><a class="mark" href="#esm_import_statements" id="esm_import_statements">#</a></span></h3>
<p>An <code>import</code> statement can reference an ES module or a CommonJS module. Other
file types such as JSON or native modules are not supported. For those, use
<a href="#modules_module_createrequire_filename"><code>module.createRequire()</code></a>.</p>
<p><code>import</code> statements are permitted only in ES modules. For similar functionality
in CommonJS, see <a href="#esm_import_expressions"><code>import()</code></a>.</p>
<p>The <em>specifier</em> of an <code>import</code> statement (the string after the <code>from</code> keyword)
can either be an URL-style relative path like <code>'./file.mjs'</code> or a package name
like <code>'fs'</code>.</p>
<p>Like in CommonJS, files within packages can be accessed by appending a path to
the package name; unless the package’s <code>package.json</code> contains an <code>"exports"</code>
field, in which case files within packages need to be accessed via the path
defined in <code>"exports"</code>.</p>
<pre><code class="language-js">import { sin, cos } from 'geometry/trigonometry-functions.mjs';
</code></pre>
<p>Only the “default export” is supported for CommonJS files or packages:</p>
<!-- eslint-disable no-duplicate-imports -->
<pre><code class="language-js">import packageMain from 'commonjs-package'; // Works

import { method } from 'commonjs-package'; // Errors
</code></pre>
<p>It is also possible to
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Import_a_module_for_its_side_effects_only">import an ES or CommonJS module for its side effects only</a>.</p>
<h3><code>import()</code> expressions<span><a class="mark" href="#esm_import_expressions" id="esm_import_expressions">#</a></span></h3>
<p><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports">Dynamic <code>import()</code></a> is supported in both CommonJS and ES modules. It can be
used to include ES module files from CommonJS code.</p>
<h2>CommonJS, JSON, and native modules<span><a class="mark" href="#esm_commonjs_json_and_native_modules" id="esm_commonjs_json_and_native_modules">#</a></span></h2>
<p>CommonJS, JSON, and native modules can be used with
<a href="#modules_module_createrequire_filename"><code>module.createRequire()</code></a>.</p>
<pre><code class="language-js">// cjs.cjs
module.exports = 'cjs';

// esm.mjs
import { createRequire } from 'module';

const require = createRequire(import.meta.url);

const cjs = require('./cjs.cjs');
cjs === 'cjs'; // true
</code></pre>
<h2>Builtin modules<span><a class="mark" href="#esm_builtin_modules" id="esm_builtin_modules">#</a></span></h2>
<p>Builtin modules will provide named exports of their public API. A
default export is also provided which is the value of the CommonJS exports.
The default export can be used for, among other things, modifying the named
exports. Named exports of builtin modules are updated only by calling
<a href="#modules_module_syncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a>.</p>
<pre><code class="language-js">import EventEmitter from 'events';
const e = new EventEmitter();
</code></pre>
<pre><code class="language-js">import { readFile } from 'fs';
readFile('./foo.txt', (err, source) => {
  if (err) {
    console.error(err);
  } else {
    console.log(source);
  }
});
</code></pre>
<pre><code class="language-js">import fs, { readFileSync } from 'fs';
import { syncBuiltinESMExports } from 'module';

fs.readFileSync = () => Buffer.from('Hello, ESM');
syncBuiltinESMExports();

fs.readFileSync === readFileSync;
</code></pre>
<h2>Experimental JSON modules<span><a class="mark" href="#esm_experimental_json_modules" id="esm_experimental_json_modules">#</a></span></h2>
<p>Currently importing JSON modules are only supported in the <code>commonjs</code> mode
and are loaded using the CJS loader. <a href="https://html.spec.whatwg.org/#creating-a-json-module-script">WHATWG JSON modules specification</a> are
still being standardized, and are experimentally supported by including the
additional flag <code>--experimental-json-modules</code> when running Node.js.</p>
<p>When the <code>--experimental-json-modules</code> flag is included both the
<code>commonjs</code> and <code>module</code> mode will use the new experimental JSON
loader. The imported JSON only exposes a <code>default</code>, there is no
support for named exports. A cache entry is created in the CommonJS
cache, to avoid duplication. The same object will be returned in
CommonJS if the JSON module has already been imported from the
same path.</p>
<p>Assuming an <code>index.mjs</code> with</p>
<!-- eslint-skip -->
<pre><code class="language-js">import packageConfig from './package.json';
</code></pre>
<p>The <code>--experimental-json-modules</code> flag is needed for the module
to work.</p>
<pre><code class="language-bash">node index.mjs # fails
node --experimental-json-modules index.mjs # works
</code></pre>
<h2>Experimental Wasm modules<span><a class="mark" href="#esm_experimental_wasm_modules" id="esm_experimental_wasm_modules">#</a></span></h2>
<p>Importing Web Assembly modules is supported under the
<code>--experimental-wasm-modules</code> flag, allowing any <code>.wasm</code> files to be
imported as normal modules while also supporting their module imports.</p>
<p>This integration is in line with the
<a href="https://github.com/webassembly/esm-integration">ES Module Integration Proposal for Web Assembly</a>.</p>
<p>For example, an <code>index.mjs</code> containing:</p>
<pre><code class="language-js">import * as M from './module.wasm';
console.log(M);
</code></pre>
<p>executed under:</p>
<pre><code class="language-bash">node --experimental-wasm-modules index.mjs
</code></pre>
<p>would provide the exports interface for the instantiation of <code>module.wasm</code>.</p>
<h2>Experimental loaders<span><a class="mark" href="#esm_experimental_loaders" id="esm_experimental_loaders">#</a></span></h2>
<p><strong>Note: This API is currently being redesigned and will still change.</strong></p>

<p>To customize the default module resolution, loader hooks can optionally be
provided via a <code>--experimental-loader ./loader-name.mjs</code> argument to Node.js.</p>
<p>When hooks are used they only apply to ES module loading and not to any
CommonJS modules loaded.</p>
<h3>Hooks<span><a class="mark" href="#esm_hooks" id="esm_hooks">#</a></span></h3>
<h4><code>resolve</code> hook<span><a class="mark" href="#esm_code_resolve_code_hook" id="esm_code_resolve_code_hook">#</a></span></h4>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<p>The <code>resolve</code> hook returns the resolved file URL for a given module specifier
and parent URL. The module specifier is the string in an <code>import</code> statement or
<code>import()</code> expression, and the parent URL is the URL of the module that imported
this one, or <code>undefined</code> if this is the main entry point for the application.</p>
<p>The <code>conditions</code> property on the <code>context</code> is an array of conditions for
<a href="#esm_conditional_exports">Conditional exports</a> that apply to this resolution request. They can be used
for looking up conditional mappings elsewhere or to modify the list when calling
the default resolution logic.</p>
<p>The <a href="#esm_conditional_exports">current set of Node.js default conditions</a> will always
be in the <code>context.conditions</code> list passed to the hook. If the hook wants to
ensure Node.js-compatible resolution logic, all items from this default
condition list <strong>must</strong> be passed through to the <code>defaultResolve</code> function.</p>
<pre><code class="language-js">/**
 * @param {string} specifier
 * @param {{
 *   parentURL: !(string | undefined),
 *   conditions: !(Array&#x3C;string>),
 * }} context
 * @param {Function} defaultResolve
 * @returns {!(Promise&#x3C;{ url: string }>)}
 */
export async function resolve(specifier, context, defaultResolve) {
  const { parentURL = null } = context;
  if (Math.random() > 0.5) { // Some condition.
    // For some or all specifiers, do some custom logic for resolving.
    // Always return an object of the form {url: &#x3C;string>}.
    return {
      url: parentURL ?
        new URL(specifier, parentURL).href :
        new URL(specifier).href,
    };
  }
  if (Math.random() &#x3C; 0.5) { // Another condition.
    // When calling `defaultResolve`, the arguments can be modified. In this
    // case it's adding another value for matching conditional exports.
    return defaultResolve(specifier, {
      ...context,
      conditions: [...context.conditions, 'another-condition'],
    });
  }
  // Defer to Node.js for all other specifiers.
  return defaultResolve(specifier, context, defaultResolve);
}
</code></pre>
<h4><code>getFormat</code> hook<span><a class="mark" href="#esm_code_getformat_code_hook" id="esm_code_getformat_code_hook">#</a></span></h4>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<p>The <code>getFormat</code> hook provides a way to define a custom method of determining how
a URL should be interpreted. The <code>format</code> returned also affects what the
acceptable forms of source values are for a module when parsing. This can be one
of the following:</p>








































<table><thead><tr><th><code>format</code></th><th>Description</th><th>Acceptable Types For <code>source</code> Returned by <code>getSource</code> or <code>transformSource</code></th></tr></thead><tbody><tr><td><code>'builtin'</code></td><td>Load a Node.js builtin module</td><td>Not applicable</td></tr><tr><td><code>'commonjs'</code></td><td>Load a Node.js CommonJS module</td><td>Not applicable</td></tr><tr><td><code>'dynamic'</code></td><td>Use a <a href="#esm_code_dynamicinstantiate_code_hook">dynamic instantiate hook</a></td><td>Not applicable</td></tr><tr><td><code>'json'</code></td><td>Load a JSON file</td><td>{ <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer-constructor">ArrayBuffer</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-string-constructor">string</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-typedarray-objects">TypedArray</a> }</td></tr><tr><td><code>'module'</code></td><td>Load an ES module</td><td>{ <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer-constructor">ArrayBuffer</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-string-constructor">string</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-typedarray-objects">TypedArray</a> }</td></tr><tr><td><code>'wasm'</code></td><td>Load a WebAssembly module</td><td>{ <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer-constructor">ArrayBuffer</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-string-constructor">string</a>, <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-typedarray-objects">TypedArray</a> }</td></tr></tbody></table>
<p>Note: These types all correspond to classes defined in ECMAScript.</p>
<ul>
<li>The specific <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-arraybuffer-constructor">ArrayBuffer</a> object is a <a href="https://tc39.es/ecma262/#sec-sharedarraybuffer-constructor">SharedArrayBuffer</a>.</li>
<li>The specific <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-string-constructor">string</a> object is not the class constructor, but an instance.</li>
<li>The specific <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-typedarray-objects">TypedArray</a> object is a <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-uint8array">Uint8Array</a>.</li>
</ul>
<p>Note: If the source value of a text-based format (i.e., <code>'json'</code>, <code>'module'</code>) is
not a string, it will be converted to a string using <a href="#util_class_util_textdecoder"><code>util.TextDecoder</code></a>.</p>
<pre><code class="language-js">/**
 * @param {string} url
 * @param {Object} context (currently empty)
 * @param {Function} defaultGetFormat
 * @returns {Promise&#x3C;{ format: string }>}
 */
export async function getFormat(url, context, defaultGetFormat) {
  if (Math.random() > 0.5) { // Some condition.
    // For some or all URLs, do some custom logic for determining format.
    // Always return an object of the form {format: &#x3C;string>}, where the
    // format is one of the strings in the table above.
    return {
      format: 'module',
    };
  }
  // Defer to Node.js for all other URLs.
  return defaultGetFormat(url, context, defaultGetFormat);
}
</code></pre>
<h4><code>getSource</code> hook<span><a class="mark" href="#esm_code_getsource_code_hook" id="esm_code_getsource_code_hook">#</a></span></h4>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<p>The <code>getSource</code> hook provides a way to define a custom method for retrieving
the source code of an ES module specifier. This would allow a loader to
potentially avoid reading files from disk.</p>
<pre><code class="language-js">/**
 * @param {string} url
 * @param {{ format: string }} context
 * @param {Function} defaultGetSource
 * @returns {Promise&#x3C;{ source: !(SharedArrayBuffer | string | Uint8Array) }>}
 */
export async function getSource(url, context, defaultGetSource) {
  const { format } = context;
  if (Math.random() > 0.5) { // Some condition.
    // For some or all URLs, do some custom logic for retrieving the source.
    // Always return an object of the form {source: &#x3C;string|buffer>}.
    return {
      source: '...',
    };
  }
  // Defer to Node.js for all other URLs.
  return defaultGetSource(url, context, defaultGetSource);
}
</code></pre>
<h4><code>transformSource</code> hook<span><a class="mark" href="#esm_code_transformsource_code_hook" id="esm_code_transformsource_code_hook">#</a></span></h4>
<pre><code class="language-console">NODE_OPTIONS='--experimental-loader ./custom-loader.mjs' node x.js
</code></pre>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<p>The <code>transformSource</code> hook provides a way to modify the source code of a loaded
ES module file after the source string has been loaded but before Node.js has
done anything with it.</p>
<p>If this hook is used to convert unknown-to-Node.js file types into executable
JavaScript, a resolve hook is also necessary in order to register any
unknown-to-Node.js file extensions. See the <a href="#esm_transpiler_loader">transpiler loader example</a> below.</p>
<pre><code class="language-js">/**
 * @param {!(SharedArrayBuffer | string | Uint8Array)} source
 * @param {{
 *   url: string,
 *   format: string,
 * }} context
 * @param {Function} defaultTransformSource
 * @returns {Promise&#x3C;{ source: !(SharedArrayBuffer | string | Uint8Array) }>}
 */
export async function transformSource(source, context, defaultTransformSource) {
  const { url, format } = context;
  if (Math.random() > 0.5) { // Some condition.
    // For some or all URLs, do some custom logic for modifying the source.
    // Always return an object of the form {source: &#x3C;string|buffer>}.
    return {
      source: '...',
    };
  }
  // Defer to Node.js for all other sources.
  return defaultTransformSource(source, context, defaultTransformSource);
}
</code></pre>
<h4><code>getGlobalPreloadCode</code> hook<span><a class="mark" href="#esm_code_getglobalpreloadcode_code_hook" id="esm_code_getglobalpreloadcode_code_hook">#</a></span></h4>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<p>Sometimes it can be necessary to run some code inside of the same global scope
that the application will run in. This hook allows to return a string that will
be ran as sloppy-mode script on startup.</p>
<p>Similar to how CommonJS wrappers work, the code runs in an implicit function
scope. The only argument is a <code>require</code>-like function that can be used to load
builtins like "fs": <code>getBuiltin(request: string)</code>.</p>
<p>If the code needs more advanced <code>require</code> features, it will have to construct
its own <code>require</code> using  <code>module.createRequire()</code>.</p>
<pre><code class="language-js">/**
 * @returns {string} Code to run before application startup
 */
export function getGlobalPreloadCode() {
  return `\
globalThis.someInjectedProperty = 42;
console.log('I just set some globals!');

const { createRequire } = getBuiltin('module');

const require = createRequire(process.cwd() + '/&#x3C;preload>');
// [...]
`;
}
</code></pre>
<h4><code>dynamicInstantiate</code> hook<span><a class="mark" href="#esm_code_dynamicinstantiate_code_hook" id="esm_code_dynamicinstantiate_code_hook">#</a></span></h4>
<blockquote>
<p>Note: The loaders API is being redesigned. This hook may disappear or its
signature may change. Do not rely on the API described below.</p>
</blockquote>
<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 <a href="#esm_code_getformat_code_hook"><code>getFormat</code> hook</a>.</p>
<pre><code class="language-js">/**
 * @param {string} url
 * @returns {object} response
 * @returns {array} response.exports
 * @returns {function} response.execute
 */
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>
<h3>Examples<span><a class="mark" href="#esm_examples" id="esm_examples">#</a></span></h3>
<p>The various loader hooks can be used together to accomplish wide-ranging
customizations of Node.js’ code loading and evaluation behaviors.</p>
<h4>HTTPS loader<span><a class="mark" href="#esm_https_loader" id="esm_https_loader">#</a></span></h4>
<p>In current Node.js, specifiers starting with <code>https://</code> are unsupported. The
loader below registers hooks to enable rudimentary support for such specifiers.
While this may seem like a significant improvement to Node.js core
functionality, there are substantial downsides to actually using this loader:
performance is much slower than loading files from disk, there is no caching,
and there is no security.</p>
<pre><code class="language-js">// https-loader.mjs
import { get } from 'https';

export function resolve(specifier, context, defaultResolve) {
  const { parentURL = null } = context;

  // Normally Node.js would error on specifiers starting with 'https://', so
  // this hook intercepts them and converts them into absolute URLs to be
  // passed along to the later hooks below.
  if (specifier.startsWith('https://')) {
    return {
      url: specifier
    };
  } else if (parentURL &#x26;&#x26; parentURL.startsWith('https://')) {
    return {
      url: new URL(specifier, parentURL).href
    };
  }

  // Let Node.js handle all other specifiers.
  return defaultResolve(specifier, context, defaultResolve);
}

export function getFormat(url, context, defaultGetFormat) {
  // This loader assumes all network-provided JavaScript is ES module code.
  if (url.startsWith('https://')) {
    return {
      format: 'module'
    };
  }

  // Let Node.js handle all other URLs.
  return defaultGetFormat(url, context, defaultGetFormat);
}

export function getSource(url, context, defaultGetSource) {
  // For JavaScript to be loaded over the network, we need to fetch and
  // return it.
  if (url.startsWith('https://')) {
    return new Promise((resolve, reject) => {
      get(url, (res) => {
        let data = '';
        res.on('data', (chunk) => data += chunk);
        res.on('end', () => resolve({ source: data }));
      }).on('error', (err) => reject(err));
    });
  }

  // Let Node.js handle all other URLs.
  return defaultGetSource(url, context, defaultGetSource);
}
</code></pre>
<pre><code class="language-js">// main.mjs
import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';

console.log(VERSION);
</code></pre>
<p>With this loader, running:</p>
<pre><code class="language-console">node --experimental-loader ./https-loader.mjs ./main.js
</code></pre>
<p>Will print the current version of CoffeeScript per the module at the URL in
<code>main.mjs</code>.</p>
<h4>Transpiler loader<span><a class="mark" href="#esm_transpiler_loader" id="esm_transpiler_loader">#</a></span></h4>
<p>Sources that are in formats Node.js doesn’t understand can be converted into
JavaScript using the <a href="#esm_code_transformsource_code_hook"><code>transformSource</code> hook</a>. Before that hook gets called,
however, other hooks need to tell Node.js not to throw an error on unknown file
types; and to tell Node.js how to load this new file type.</p>
<p>This is less performant than transpiling source files before running
Node.js; a transpiler loader should only be used for development and testing
purposes.</p>
<pre><code class="language-js">// coffeescript-loader.mjs
import { URL, pathToFileURL } from 'url';
import CoffeeScript from 'coffeescript';

const baseURL = pathToFileURL(`${process.cwd()}/`).href;

// CoffeeScript files end in .coffee, .litcoffee or .coffee.md.
const extensionsRegex = /\.coffee$|\.litcoffee$|\.coffee\.md$/;

export function resolve(specifier, context, defaultResolve) {
  const { parentURL = baseURL } = context;

  // Node.js normally errors on unknown file extensions, so return a URL for
  // specifiers ending in the CoffeeScript file extensions.
  if (extensionsRegex.test(specifier)) {
    return {
      url: new URL(specifier, parentURL).href
    };
  }

  // Let Node.js handle all other specifiers.
  return defaultResolve(specifier, context, defaultResolve);
}

export function getFormat(url, context, defaultGetFormat) {
  // Now that we patched resolve to let CoffeeScript URLs through, we need to
  // tell Node.js what format such URLs should be interpreted as. For the
  // purposes of this loader, all CoffeeScript URLs are ES modules.
  if (extensionsRegex.test(url)) {
    return {
      format: 'module'
    };
  }

  // Let Node.js handle all other URLs.
  return defaultGetFormat(url, context, defaultGetFormat);
}

export function transformSource(source, context, defaultTransformSource) {
  const { url, format } = context;

  if (extensionsRegex.test(url)) {
    return {
      source: CoffeeScript.compile(source, { bare: true })
    };
  }

  // Let Node.js handle all other sources.
  return defaultTransformSource(source, context, defaultTransformSource);
}
</code></pre>
<pre><code class="language-coffee"># main.coffee
import { scream } from './scream.coffee'
console.log scream 'hello, world'

import { version } from 'process'
console.log "Brought to you by Node.js version #{version}"
</code></pre>
<pre><code class="language-coffee"># scream.coffee
export scream = (str) -> str.toUpperCase()
</code></pre>
<p>With this loader, running:</p>
<pre><code class="language-console">node --experimental-loader ./coffeescript-loader.mjs main.coffee
</code></pre>
<p>Will cause <code>main.coffee</code> to be turned into JavaScript after its source code is
loaded from disk but before Node.js executes it; and so on for any <code>.coffee</code>,
<code>.litcoffee</code> or <code>.coffee.md</code> files referenced via <code>import</code> statements of any
loaded file.</p>
<h2>Resolution algorithm<span><a class="mark" href="#esm_resolution_algorithm" id="esm_resolution_algorithm">#</a></span></h2>
<h3>Features<span><a class="mark" href="#esm_features" id="esm_features">#</a></span></h3>
<p>The resolver has the following properties:</p>
<ul>
<li>FileURL-based resolution as is used by ES modules</li>
<li>Support for builtin module loading</li>
<li>Relative and absolute URL resolution</li>
<li>No default extensions</li>
<li>No folder mains</li>
<li>Bare specifier package resolution lookup through node_modules</li>
</ul>
<h3>Resolver algorithm<span><a class="mark" href="#esm_resolver_algorithm" id="esm_resolver_algorithm">#</a></span></h3>
<p>The algorithm to load an ES module specifier is given through the
<strong>ESM_RESOLVE</strong> method below. It returns the resolved URL for a
module specifier relative to a parentURL.</p>
<p>The algorithm to determine the module format of a resolved URL is
provided by <strong>ESM_FORMAT</strong>, which returns the unique module
format for any file. The <em>"module"</em> format is returned for an ECMAScript
Module, while the <em>"commonjs"</em> format is used to indicate loading through the
legacy CommonJS loader. Additional formats such as <em>"addon"</em> can be extended in
future updates.</p>
<p>In the following algorithms, all subroutine errors are propagated as errors
of these top-level routines unless stated otherwise.</p>
<p><em>defaultEnv</em> is the conditional environment name priority array,
<code>["node", "import"]</code>.</p>
<p>The resolver can throw the following errors:</p>
<ul>
<li><em>Invalid Module Specifier</em>: Module specifier is an invalid URL, package name
or package subpath specifier.</li>
<li><em>Invalid Package Configuration</em>: package.json configuration is invalid or
contains an invalid configuration.</li>
<li><em>Invalid Package Target</em>: Package exports define a target module within the
package that is an invalid type or string target.</li>
<li><em>Package Path Not Exported</em>: Package exports do not define or permit a target
subpath in the package for the given module.</li>
<li><em>Module Not Found</em>: The package or module requested does not exist.</li>
</ul>
<details>
<summary>Resolver algorithm specification</summary>
<p><strong>ESM_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>resolvedURL</em> be <strong>undefined</strong>.</li>
<li>
<p>If <em>specifier</em> is a valid URL, then</p>
<ol>
<li>Set <em>resolvedURL</em> to the result of parsing and reserializing
<em>specifier</em> as a URL.</li>
</ol>
</li>
<li>
<p>Otherwise, if <em>specifier</em> starts with <em>"/"</em>, then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>
<p>Otherwise, if <em>specifier</em> starts with <em>"./"</em> or <em>"../"</em>, then</p>
<ol>
<li>Set <em>resolvedURL</em> to the URL resolution of <em>specifier</em> relative to
<em>parentURL</em>.</li>
</ol>
</li>
<li>
<p>Otherwise,</p>
<ol>
<li>Note: <em>specifier</em> is now a bare specifier.</li>
<li>Set <em>resolvedURL</em> the result of
<strong>PACKAGE_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>).</li>
</ol>
</li>
<li>
<p>If <em>resolvedURL</em> contains any percent encodings of <em>"/"</em> or <em>"\"</em> (<em>"%2f"</em>
and <em>"%5C"</em> respectively), then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>
<p>If the file at <em>resolvedURL</em> is a directory, then</p>
<ol>
<li>Throw an <em>Unsupported Directory Import</em> error.</li>
</ol>
</li>
<li>
<p>If the file at <em>resolvedURL</em> does not exist, then</p>
<ol>
<li>Throw a <em>Module Not Found</em> error.</li>
</ol>
</li>
<li>Set <em>resolvedURL</em> to the real path of <em>resolvedURL</em>.</li>
<li>Let <em>format</em> be the result of <strong>ESM_FORMAT</strong>(<em>resolvedURL</em>).</li>
<li>Load <em>resolvedURL</em> as module format, <em>format</em>.</li>
<li>Return <em>resolvedURL</em>.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_RESOLVE</strong>(<em>packageSpecifier</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>packageName</em> be <em>undefined</em>.</li>
<li>Let <em>packageSubpath</em> be <em>undefined</em>.</li>
<li>
<p>If <em>packageSpecifier</em> is an empty string, then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>
<p>Otherwise,</p>
<ol>
<li>
<p>If <em>packageSpecifier</em> does not contain a <em>"/"</em> separator, then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Set <em>packageName</em> to the substring of <em>packageSpecifier</em>
until the second <em>"/"</em> separator or the end of the string.</li>
</ol>
</li>
<li>
<p>If <em>packageName</em> starts with <em>"."</em> or contains <em>"\"</em> or <em>"%"</em>, then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Let <em>packageSubpath</em> be <em>undefined</em>.</li>
<li>
<p>If the length of <em>packageSpecifier</em> is greater than the length of
<em>packageName</em>, then</p>
<ol>
<li>Set <em>packageSubpath</em> to <em>"."</em> concatenated with the substring of
<em>packageSpecifier</em> from the position at the length of <em>packageName</em>.</li>
</ol>
</li>
<li>
<p>If <em>packageSubpath</em> contains any <em>"."</em> or <em>".."</em> segments or percent
encoded strings for <em>"/"</em> or <em>"\"</em>, then</p>
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Set <em>selfUrl</em> to the result of
<strong>SELF_REFERENCE_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>).</li>
<li>If <em>selfUrl</em> isn't empty, return <em>selfUrl</em>.</li>
<li>
<p>If <em>packageSubpath</em> is <em>undefined</em> and <em>packageName</em> is a Node.js builtin
module, then</p>
<ol>
<li>Return the string <em>"nodejs:"</em> concatenated with <em>packageSpecifier</em>.</li>
</ol>
</li>
<li>
<p>While <em>parentURL</em> is not the file system root,</p>
<ol>
<li>Let <em>packageURL</em> be the URL resolution of <em>"node_modules/"</em>
concatenated with <em>packageSpecifier</em>, relative to <em>parentURL</em>.</li>
<li>Set <em>parentURL</em> to the parent folder URL of <em>parentURL</em>.</li>
<li>
<p>If the folder at <em>packageURL</em> does not exist, then</p>
<ol>
<li>Set <em>parentURL</em> to the parent URL path of <em>parentURL</em>.</li>
<li>Continue the next loop iteration.</li>
</ol>
</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
<li>
<p>If <em>packageSubpath</em> is equal to <em>"./"</em>, then</p>
<ol>
<li>Return <em>packageURL</em> + <em>"/"</em>.</li>
</ol>
</li>
<li>
<p>If <em>packageSubpath</em> is _undefined__, then</p>
<ol>
<li>Return the result of <strong>PACKAGE_MAIN_RESOLVE</strong>(<em>packageURL</em>,
<em>pjson</em>).</li>
</ol>
</li>
<li>
<p>Otherwise,</p>
<ol>
<li>
<p>If <em>pjson</em> is not <strong>null</strong> and <em>pjson</em> has an <em>"exports"</em> key, then</p>
<ol>
<li>Let <em>exports</em> be <em>pjson.exports</em>.</li>
<li>
<p>If <em>exports</em> is not <strong>null</strong> or <strong>undefined</strong>, then</p>
<ol>
<li>Return <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>,
<em>packageSubpath</em>, <em>pjson.exports</em>).</li>
</ol>
</li>
</ol>
</li>
<li>Return the URL resolution of <em>packageSubpath</em> in <em>packageURL</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Throw a <em>Module Not Found</em> error.</li>
</ol>
</blockquote>
<p><strong>SELF_REFERENCE_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>packageURL</em> be the result of <strong>READ_PACKAGE_SCOPE</strong>(<em>parentURL</em>).</li>
<li>
<p>If <em>packageURL</em> is <strong>null</strong>, then</p>
<ol>
<li>Return <strong>undefined</strong>.</li>
</ol>
</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
<li>
<p>If <em>pjson</em> does not include an <em>"exports"</em> property, then</p>
<ol>
<li>Return <strong>undefined</strong>.</li>
</ol>
</li>
<li>
<p>If <em>pjson.name</em> is equal to <em>packageName</em>, then</p>
<ol>
<li>
<p>If <em>packageSubpath</em> is equal to <em>"./"</em>, then</p>
<ol>
<li>Return <em>packageURL</em> + <em>"/"</em>.</li>
</ol>
</li>
<li>
<p>If <em>packageSubpath</em> is <em>undefined</em>, then</p>
<ol>
<li>Return the result of <strong>PACKAGE_MAIN_RESOLVE</strong>(<em>packageURL</em>, <em>pjson</em>).</li>
</ol>
</li>
<li>
<p>Otherwise,</p>
<ol>
<li>
<p>If <em>pjson</em> is not <strong>null</strong> and <em>pjson</em> has an <em>"exports"</em> key, then</p>
<ol>
<li>Let <em>exports</em> be <em>pjson.exports</em>.</li>
<li>
<p>If <em>exports</em> is not <strong>null</strong> or <strong>undefined</strong>, then</p>
<ol>
<li>Return <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>subpath</em>,
<em>pjson.exports</em>).</li>
</ol>
</li>
</ol>
</li>
<li>Return the URL resolution of <em>subpath</em> in <em>packageURL</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Otherwise, return <strong>undefined</strong>.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_MAIN_RESOLVE</strong>(<em>packageURL</em>, <em>pjson</em>)</p>
<blockquote>
<ol>
<li>
<p>If <em>pjson</em> is <strong>null</strong>, then</p>
<ol>
<li>Throw a <em>Module Not Found</em> error.</li>
</ol>
</li>
<li>
<p>If <em>pjson.exports</em> is not <strong>null</strong> or <strong>undefined</strong>, then</p>
<ol>
<li>If <em>exports</em> is an Object with both a key starting with <em>"."</em> and a key
not starting with <em>"."</em>, throw an <em>Invalid Package Configuration</em> error.</li>
<li>
<p>If <em>pjson.exports</em> is a String or Array, or an Object containing no
keys starting with <em>"."</em>, then</p>
<ol>
<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>,
<em>pjson.exports</em>, <em>""</em>).</li>
</ol>
</li>
<li>
<p>If <em>pjson.exports</em> is an Object containing a <em>"."</em> property, then</p>
<ol>
<li>Let <em>mainExport</em> be the <em>"."</em> property in <em>pjson.exports</em>.</li>
<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>,
<em>mainExport</em>, <em>""</em>).</li>
</ol>
</li>
<li>Throw a <em>Package Path Not Exported</em> error.</li>
</ol>
</li>
<li>Let <em>legacyMainURL</em> be the result applying the legacy
<strong>LOAD_AS_DIRECTORY</strong> CommonJS resolver to <em>packageURL</em>, throwing a
<em>Module Not Found</em> error for no resolution.</li>
<li>Return <em>legacyMainURL</em>.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>packagePath</em>, <em>exports</em>)</p>
<blockquote>
<ol>
<li>If <em>exports</em> is an Object with both a key starting with <em>"."</em> and a key not
starting with <em>"."</em>, throw an <em>Invalid Package Configuration</em> error.</li>
<li>
<p>If <em>exports</em> is an Object and all keys of <em>exports</em> start with <em>"."</em>, then</p>
<ol>
<li>Set <em>packagePath</em> to <em>"./"</em> concatenated with <em>packagePath</em>.</li>
<li>
<p>If <em>packagePath</em> is a key of <em>exports</em>, then</p>
<ol>
<li>Let <em>target</em> be the value of <em>exports[packagePath]</em>.</li>
<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>,
<em>""</em>, <em>defaultEnv</em>).</li>
</ol>
</li>
<li>Let <em>directoryKeys</em> be the list of keys of <em>exports</em> ending in
<em>"/"</em>, sorted by length descending.</li>
<li>
<p>For each key <em>directory</em> in <em>directoryKeys</em>, do</p>
<ol>
<li>
<p>If <em>packagePath</em> starts with <em>directory</em>, then</p>
<ol>
<li>Let <em>target</em> be the value of <em>exports[directory]</em>.</li>
<li>Let <em>subpath</em> be the substring of <em>target</em> starting at the index
of the length of <em>directory</em>.</li>
<li>Return <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>,
<em>subpath</em>, <em>defaultEnv</em>).</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
<li>Throw a <em>Package Path Not Exported</em> error.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>, <em>subpath</em>, <em>env</em>)</p>
<blockquote>
<ol>
<li>
<p>If <em>target</em> is a String, then</p>
<ol>
<li>If <em>target</em> does not start with <em>"./"</em> or contains any <em>"node_modules"</em>
segments including <em>"node_modules"</em> percent-encoding, throw an
<em>Invalid Package Target</em> error.</li>
<li>Let <em>resolvedTarget</em> be the URL resolution of the concatenation of
<em>packageURL</em> and <em>target</em>.</li>
<li>If <em>resolvedTarget</em> is not contained in <em>packageURL</em>, throw an
<em>Invalid Package Target</em> error.</li>
<li>If <em>subpath</em> has non-zero length and <em>target</em> does not end with <em>"/"</em>,
throw an <em>Invalid Module Specifier</em> error.</li>
<li>Let <em>resolved</em> be the URL resolution of the concatenation of
<em>subpath</em> and <em>resolvedTarget</em>.</li>
<li>If <em>resolved</em> is not contained in <em>resolvedTarget</em>, throw an
<em>Invalid Module Specifier</em> error.</li>
<li>Return <em>resolved</em>.</li>
</ol>
</li>
<li>
<p>Otherwise, if <em>target</em> is a non-null Object, then</p>
<ol>
<li>If <em>exports</em> contains any index property keys, as defined in ECMA-262
<a href="https://tc39.es/ecma262/#integer-index">6.1.7 Array Index</a>, throw an <em>Invalid Package Configuration</em> error.</li>
<li>
<p>For each property <em>p</em> of <em>target</em>, in object insertion order as,</p>
<ol>
<li>
<p>If <em>p</em> equals <em>"default"</em> or <em>env</em> contains an entry for <em>p</em>, then</p>
<ol>
<li>Let <em>targetValue</em> be the value of the <em>p</em> property in <em>target</em>.</li>
<li>Return the result of <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(
<em>packageURL</em>, <em>targetValue</em>, <em>subpath</em>, <em>env</em>), continuing the
loop on any <em>Package Path Not Exported</em> error.</li>
</ol>
</li>
</ol>
</li>
<li>Throw a <em>Package Path Not Exported</em> error.</li>
</ol>
</li>
<li>
<p>Otherwise, if <em>target</em> is an Array, then</p>
<ol>
<li>If <em>target.length is zero, throw a _Package Path Not Exported</em> error.</li>
<li>
<p>For each item <em>targetValue</em> in <em>target</em>, do</p>
<ol>
<li>If <em>targetValue</em> is an Array, continue the loop.</li>
<li>Return the result of <strong>PACKAGE_EXPORTS_TARGET_RESOLVE</strong>(<em>packageURL</em>,
<em>targetValue</em>, <em>subpath</em>, <em>env</em>), continuing the loop on any
<em>Package Path Not Exported</em> or <em>Invalid Package Target</em> error.</li>
</ol>
</li>
<li>Throw the last fallback resolution error.</li>
</ol>
</li>
<li>Otherwise, if <em>target</em> is <em>null</em>, throw a <em>Package Path Not Exported</em>
error.</li>
<li>Otherwise throw an <em>Invalid Package Target</em> error.</li>
</ol>
</blockquote>
<p><strong>ESM_FORMAT</strong>(<em>url</em>)</p>
<blockquote>
<ol>
<li>Assert: <em>url</em> corresponds to an existing file.</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_SCOPE</strong>(<em>url</em>).</li>
<li>
<p>If <em>url</em> ends in <em>".mjs"</em>, then</p>
<ol>
<li>Return <em>"module"</em>.</li>
</ol>
</li>
<li>
<p>If <em>url</em> ends in <em>".cjs"</em>, then</p>
<ol>
<li>Return <em>"commonjs"</em>.</li>
</ol>
</li>
<li>
<p>If <em>pjson?.type</em> exists and is <em>"module"</em>, then</p>
<ol>
<li>
<p>If <em>url</em> ends in <em>".js"</em>, then</p>
<ol>
<li>Return <em>"module"</em>.</li>
</ol>
</li>
<li>Throw an <em>Unsupported File Extension</em> error.</li>
</ol>
</li>
<li>
<p>Otherwise,</p>
<ol>
<li>Throw an <em>Unsupported File Extension</em> error.</li>
</ol>
</li>
</ol>
</blockquote>
<p><strong>READ_PACKAGE_SCOPE</strong>(<em>url</em>)</p>
<blockquote>
<ol>
<li>Let <em>scopeURL</em> be <em>url</em>.</li>
<li>
<p>While <em>scopeURL</em> is not the file system root,</p>
<ol>
<li>If <em>scopeURL</em> ends in a <em>"node_modules"</em> path segment, return <strong>null</strong>.</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>scopeURL</em>).</li>
<li>
<p>If <em>pjson</em> is not <strong>null</strong>, then</p>
<ol>
<li>Return <em>pjson</em>.</li>
</ol>
</li>
<li>Set <em>scopeURL</em> to the parent URL of <em>scopeURL</em>.</li>
</ol>
</li>
<li>Return <strong>null</strong>.</li>
</ol>
</blockquote>
<p><strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>pjsonURL</em> be the resolution of <em>"package.json"</em> within <em>packageURL</em>.</li>
<li>
<p>If the file at <em>pjsonURL</em> does not exist, then</p>
<ol>
<li>Return <strong>null</strong>.</li>
</ol>
</li>
<li>
<p>If the file at <em>packageURL</em> does not parse as valid JSON, then</p>
<ol>
<li>Throw an <em>Invalid Package Configuration</em> error.</li>
</ol>
</li>
<li>Return the parsed JSON source of the file at <em>pjsonURL</em>.</li>
</ol>
</blockquote>
</details>
<h3>Customizing ESM specifier resolution algorithm<span><a class="mark" href="#esm_customizing_esm_specifier_resolution_algorithm" id="esm_customizing_esm_specifier_resolution_algorithm">#</a></span></h3>
<p>The current specifier resolution does not support all default behavior of
the CommonJS loader. One of the behavior differences is automatic resolution
of file extensions and the ability to import directories that have an index
file.</p>
<p>The <code>--experimental-specifier-resolution=[mode]</code> flag can be used to customize
the extension resolution algorithm. The default mode is <code>explicit</code>, which
requires the full path to a module be provided to the loader. To enable the
automatic extension resolution and importing from directories that include an
index file use the <code>node</code> mode.</p>
<pre><code class="language-bash">$ node index.mjs
success!
$ node index # Failure!
Error: Cannot find module
$ node --experimental-specifier-resolution=node index
success!
</code></pre>
<h1>Errors<span><a class="mark" href="#errors_errors" id="errors_errors">#</a></span></h1>


<p>Applications running in Node.js will generally experience four categories of
errors:</p>
<ul>
<li>Standard JavaScript errors such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError" class="type">&#x3C;EvalError></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError" class="type">&#x3C;SyntaxError></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError" class="type">&#x3C;RangeError></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError" class="type">&#x3C;ReferenceError></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError" class="type">&#x3C;TypeError></a>, and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError" class="type">&#x3C;URIError></a>.</li>
<li>System errors triggered by underlying operating system constraints such
as attempting to open a file that does not exist or attempting to send data
over a closed socket.</li>
<li>User-specified errors triggered by application code.</li>
<li><code>AssertionError</code>s are a special class of error that can be triggered when
Node.js detects an exceptional logic violation that should never occur. These
are raised typically by the <code>assert</code> module.</li>
</ul>
<p>All JavaScript and system errors raised by Node.js inherit from, or are
instances of, the standard JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> class and are guaranteed
to provide <em>at least</em> the properties available on that class.</p>
<h2>Error propagation and interception<span><a class="mark" href="#errors_error_propagation_and_interception" id="errors_error_propagation_and_interception">#</a></span></h2>

<p>Node.js supports several mechanisms for propagating and handling errors that
occur while an application is running. How these errors are reported and
handled depends entirely on the type of <code>Error</code> and the style of the API that is
called.</p>
<p>All JavaScript errors are handled as exceptions that <em>immediately</em> generate
and throw an error using the standard JavaScript <code>throw</code> mechanism. These
are handled using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>try…catch</code> construct</a> provided by the
JavaScript language.</p>
<pre><code class="language-js">// Throws with a ReferenceError because z is not defined.
try {
  const m = 1;
  const n = m + z;
} catch (err) {
  // Handle the error here.
}
</code></pre>
<p>Any use of the JavaScript <code>throw</code> mechanism will raise an exception that
<em>must</em> be handled using <code>try…catch</code> or the Node.js process will exit
immediately.</p>
<p>With few exceptions, <em>Synchronous</em> APIs (any blocking method that does not
accept a <code>callback</code> function, such as <a href="#fs_fs_readfilesync_path_options"><code>fs.readFileSync</code></a>), will use <code>throw</code>
to report errors.</p>
<p>Errors that occur within <em>Asynchronous APIs</em> may be reported in multiple ways:</p>
<ul>
<li>Most asynchronous methods that accept a <code>callback</code> function will accept an
<code>Error</code> object passed as the first argument to that function. If that first
argument is not <code>null</code> and is an instance of <code>Error</code>, then an error occurred
that should be handled.</li>
</ul>
<!-- eslint-disable no-useless-return -->
<pre><code class="language-js">const fs = require('fs');
fs.readFile('a file that does not exist', (err, data) => {
  if (err) {
    console.error('There was an error reading the file!', err);
    return;
  }
  // Otherwise handle the data
});
</code></pre>
<ul>
<li>
<p>When an asynchronous method is called on an object that is an
<a href="#events_class_eventemitter"><code>EventEmitter</code></a>, errors can be routed to that object's <code>'error'</code> event.</p>
<pre><code class="language-js">const net = require('net');
const connection = net.connect('localhost');

// Adding an 'error' event handler to a stream:
connection.on('error', (err) => {
  // If the connection is reset by the server, or if it can't
  // connect at all, or on any sort of error encountered by
  // the connection, the error will be sent here.
  console.error(err);
});

connection.pipe(process.stdout);
</code></pre>
</li>
<li>
<p>A handful of typically asynchronous methods in the Node.js API may still
use the <code>throw</code> mechanism to raise exceptions that must be handled using
<code>try…catch</code>. There is no comprehensive list of such methods; please
refer to the documentation of each method to determine the appropriate
error handling mechanism required.</p>
</li>
</ul>
<p>The use of the <code>'error'</code> event mechanism is most common for <a href="stream.html">stream-based</a>
and <a href="#events_class_eventemitter">event emitter-based</a> APIs, which themselves represent a series of
asynchronous operations over time (as opposed to a single operation that may
pass or fail).</p>
<p>For <em>all</em> <a href="#events_class_eventemitter"><code>EventEmitter</code></a> objects, if an <code>'error'</code> event handler is not
provided, the error will be thrown, causing the Node.js process to report an
uncaught exception and crash unless either: The <a href="domain.html"><code>domain</code></a> module is
used appropriately or a handler has been registered for the
<a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a> event.</p>
<pre><code class="language-js">const EventEmitter = require('events');
const ee = new EventEmitter();

setImmediate(() => {
  // This will crash the process because no 'error' event
  // handler has been added.
  ee.emit('error', new Error('This will crash'));
});
</code></pre>
<p>Errors generated in this way <em>cannot</em> be intercepted using <code>try…catch</code> as
they are thrown <em>after</em> the calling code has already exited.</p>
<p>Developers must refer to the documentation for each method to determine
exactly how errors raised by those methods are propagated.</p>
<h3>Error-first callbacks<span><a class="mark" href="#errors_error_first_callbacks" id="errors_error_first_callbacks">#</a></span></h3>

<p>Most asynchronous methods exposed by the Node.js core API follow an idiomatic
pattern referred to as an <em>error-first callback</em>. With this pattern, a callback
function is passed to the method as an argument. When the operation either
completes or an error is raised, the callback function is called with the
<code>Error</code> object (if any) passed as the first argument. If no error was raised,
the first argument will be passed as <code>null</code>.</p>
<pre><code class="language-js">const fs = require('fs');

function errorFirstCallback(err, data) {
  if (err) {
    console.error('There was an error', err);
    return;
  }
  console.log(data);
}

fs.readFile('/some/file/that/does-not-exist', errorFirstCallback);
fs.readFile('/some/file/that/does-exist', errorFirstCallback);
</code></pre>
<p>The JavaScript <code>try…catch</code> mechanism <strong>cannot</strong> be used to intercept errors
generated by asynchronous APIs. A common mistake for beginners is to try to
use <code>throw</code> inside an error-first callback:</p>
<pre><code class="language-js">// THIS WILL NOT WORK:
const fs = require('fs');

try {
  fs.readFile('/some/file/that/does-not-exist', (err, data) => {
    // Mistaken assumption: throwing here...
    if (err) {
      throw err;
    }
  });
} catch (err) {
  // This will not catch the throw!
  console.error(err);
}
</code></pre>
<p>This will not work because the callback function passed to <code>fs.readFile()</code> is
called asynchronously. By the time the callback has been called, the
surrounding code, including the <code>try…catch</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: <code>Error</code><span><a class="mark" href="#errors_class_error" id="errors_class_error">#</a></span></h2>

<p>A generic JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> 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>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><code>new Error(message)</code><span><a class="mark" href="#errors_new_error_message" id="errors_new_error_message">#</a></span></h3>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Creates a new <code>Error</code> object and sets the <code>error.message</code> property to the
provided text message. If an object is passed as <code>message</code>, the text message
is generated by calling <code>message.toString()</code>. The <code>error.stack</code> property will
represent the point in the code at which <code>new Error()</code> was called. Stack traces
are dependent on <a href="https://github.com/v8/v8/wiki/Stack-Trace-API">V8's stack trace API</a>. Stack traces extend only to either
(a) the beginning of <em>synchronous code execution</em>, or (b) the number of frames
given by the property <code>Error.stackTraceLimit</code>, whichever is smaller.</p>
<h3><code>Error.captureStackTrace(targetObject[, constructorOpt])</code><span><a class="mark" href="#errors_error_capturestacktrace_targetobject_constructoropt" id="errors_error_capturestacktrace_targetobject_constructoropt">#</a></span></h3>
<ul>
<li><code>targetObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>constructorOpt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Creates a <code>.stack</code> property on <code>targetObject</code>, which when accessed returns
a string representing the location in the code at which
<code>Error.captureStackTrace()</code> was called.</p>
<pre><code class="language-js">const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack`
</code></pre>
<p>The first line of the trace will be prefixed with
<code>${myObject.name}: ${myObject.message}</code>.</p>
<p>The optional <code>constructorOpt</code> argument accepts a function. If given, all frames
above <code>constructorOpt</code>, including <code>constructorOpt</code>, will be omitted from the
generated stack trace.</p>
<p>The <code>constructorOpt</code> argument is useful for hiding implementation
details of error generation from an end user. For instance:</p>
<pre><code class="language-js">function MyError() {
  Error.captureStackTrace(this, MyError);
}

// Without passing MyError to captureStackTrace, the MyError
// frame would show up in the .stack property. By passing
// the constructor, we omit that frame, and retain all frames below it.
new MyError().stack;
</code></pre>
<h3><code>Error.stackTraceLimit</code><span><a class="mark" href="#errors_error_stacktracelimit" id="errors_error_stacktracelimit">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The <code>Error.stackTraceLimit</code> property specifies the number of stack frames
collected by a stack trace (whether generated by <code>new Error().stack</code> or
<code>Error.captureStackTrace(obj)</code>).</p>
<p>The default value is <code>10</code> but may be set to any valid JavaScript number. Changes
will affect any stack trace captured <em>after</em> the value has been changed.</p>
<p>If set to a non-number value, or set to a negative number, stack traces will
not capture any frames.</p>
<h3><code>error.code</code><span><a class="mark" href="#errors_error_code" id="errors_error_code">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>error.code</code> property is a string label that identifies the kind of error.
<code>error.code</code> is the most stable way to identify an error. It will only change
between major versions of Node.js. In contrast, <code>error.message</code> strings may
change between any versions of Node.js. See <a href="#nodejs-error-codes">Node.js error codes</a> for details
about specific codes.</p>
<h3><code>error.message</code><span><a class="mark" href="#errors_error_message" id="errors_error_message">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>error.message</code> property is the string description of the error as set by
calling <code>new Error(message)</code>. The <code>message</code> passed to the constructor will also
appear in the first line of the stack trace of the <code>Error</code>, however changing
this property after the <code>Error</code> object is created <em>may not</em> change the first
line of the stack trace (for example, when <code>error.stack</code> is read before this
property is changed).</p>
<pre><code class="language-js">const err = new Error('The message');
console.error(err.message);
// Prints: The message
</code></pre>
<h3><code>error.stack</code><span><a class="mark" href="#errors_error_stack" id="errors_error_stack">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>error.stack</code> property is a string describing the point in the code at which
the <code>Error</code> was instantiated.</p>
<pre><code class="language-console">Error: Things keep happening!
   at /home/gbusey/file.js:525:2
   at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)
   at Actor.&#x3C;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>&#x3C;error class name>: &#x3C;error message></code>, and
is followed by a series of stack frames (each line beginning with "at ").
Each frame describes a call site within the code that lead to the error being
generated. V8 attempts to display a name for each function (by variable name,
function name, or object method name), but occasionally it will not be able to
find a suitable name. If V8 cannot determine a name for the function, only
location information will be displayed for that frame. Otherwise, the
determined function name will be displayed with location information appended
in parentheses.</p>
<p>Frames are only generated for JavaScript functions. If, for example, execution
synchronously passes through a C++ addon function called <code>cheetahify</code> which
itself calls a JavaScript function, the frame representing the <code>cheetahify</code> call
will not be present in the stack traces:</p>
<pre><code class="language-js">const cheetahify = require('./native-binding.node');

function makeFaster() {
  // `cheetahify()` *synchronously* calls speedy.
  cheetahify(function speedy() {
    throw new Error('oh no!');
  });
}

makeFaster();
// will throw:
//   /home/gbusey/file.js:6
//       throw new Error('oh no!');
//           ^
//   Error: oh no!
//       at speedy (/home/gbusey/file.js:6:11)
//       at makeFaster (/home/gbusey/file.js:5:3)
//       at Object.&#x3C;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>
<h2>Class: <code>AssertionError</code><span><a class="mark" href="#errors_class_assertionerror" id="errors_class_assertionerror">#</a></span></h2>
<ul>
<li>Extends: <a href="#errors_class_error" class="type">&#x3C;errors.Error></a></li>
</ul>
<p>Indicates the failure of an assertion. For details, see
<a href="#assert_class_assert_assertionerror"><code>Class: assert.AssertionError</code></a>.</p>
<h2>Class: <code>RangeError</code><span><a class="mark" href="#errors_class_rangeerror" id="errors_class_rangeerror">#</a></span></h2>
<ul>
<li>Extends: <a href="#errors_class_error" class="type">&#x3C;errors.Error></a></li>
</ul>
<p>Indicates that a provided argument was not within the set or range of
acceptable values for a function; whether that is a numeric range, or
outside the set of options for a given function parameter.</p>
<pre><code class="language-js">require('net').connect(-1);
// Throws "RangeError: "port" option should be >= 0 and &#x3C; 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: <code>ReferenceError</code><span><a class="mark" href="#errors_class_referenceerror" id="errors_class_referenceerror">#</a></span></h2>
<ul>
<li>Extends: <a href="#errors_class_error" class="type">&#x3C;errors.Error></a></li>
</ul>
<p>Indicates that an attempt is being made to access a variable that is not
defined. Such errors commonly indicate typos in code, or an otherwise broken
program.</p>
<p>While client code may generate and propagate these errors, in practice, only V8
will do so.</p>
<pre><code class="language-js">doesNotExist;
// Throws ReferenceError, doesNotExist is not a variable in this program.
</code></pre>
<p>Unless an application is dynamically generating and running code,
<code>ReferenceError</code> instances should always be considered a bug in the code
or its dependencies.</p>
<h2>Class: <code>SyntaxError</code><span><a class="mark" href="#errors_class_syntaxerror" id="errors_class_syntaxerror">#</a></span></h2>
<ul>
<li>Extends: <a href="#errors_class_error" class="type">&#x3C;errors.Error></a></li>
</ul>
<p>Indicates that a program is not valid JavaScript. These errors may only be
generated and propagated as a result of code evaluation. Code evaluation may
happen as a result of <code>eval</code>, <code>Function</code>, <code>require</code>, or <a href="vm.html">vm</a>. These errors
are almost always indicative of a broken program.</p>
<pre><code class="language-js">try {
  require('vm').runInThisContext('binary ! isNotOk');
} catch (err) {
  // 'err' will be a SyntaxError.
}
</code></pre>
<p><code>SyntaxError</code> instances are unrecoverable in the context that created them –
they may only be caught by other contexts.</p>
<h2>Class: <code>SystemError</code><span><a class="mark" href="#errors_class_systemerror" id="errors_class_systemerror">#</a></span></h2>
<ul>
<li>Extends: <a href="#errors_class_error" class="type">&#x3C;errors.Error></a></li>
</ul>
<p>Node.js generates system errors when exceptions occur within its runtime
environment. These usually occur when an application violates an operating
system constraint. For example, a system error will occur if an application
attempts to read a file that does not exist.</p>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If present, the address to which a network connection
failed</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The string error code</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If present, the file path destination when reporting a file
system error</li>
<li><code>errno</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The system-provided error number</li>
<li><code>info</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> If present, extra details about the error condition</li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> A system-provided human-readable description of the error</li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If present, the file path when reporting a file system error</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> If present, the network connection port that is not available</li>
<li><code>syscall</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The name of the system call that triggered the error</li>
</ul>
<h3><code>error.address</code><span><a class="mark" href="#errors_error_address" id="errors_error_address">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>If present, <code>error.address</code> is a string describing the address to which a
network connection failed.</p>
<h3><code>error.code</code><span><a class="mark" href="#errors_error_code_1" id="errors_error_code_1">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>error.code</code> property is a string representing the error code.</p>
<h3><code>error.dest</code><span><a class="mark" href="#errors_error_dest" id="errors_error_dest">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>If present, <code>error.dest</code> is the file path destination when reporting a file
system error.</p>
<h3><code>error.errno</code><span><a class="mark" href="#errors_error_errno" id="errors_error_errno">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The <code>error.errno</code> property is a number or a string. If it is a number, it is a
negative value which corresponds to the error code defined in
<a href="http://docs.libuv.org/en/v1.x/errors.html"><code>libuv Error handling</code></a>. See the libuv <code>errno.h</code> header file
(<code>deps/uv/include/uv/errno.h</code> in the Node.js source tree) for details. In case
of a string, it is the same as <code>error.code</code>.</p>
<h3><code>error.info</code><span><a class="mark" href="#errors_error_info" id="errors_error_info">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>If present, <code>error.info</code> is an object with details about the error condition.</p>
<h3><code>error.message</code><span><a class="mark" href="#errors_error_message_1" id="errors_error_message_1">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p><code>error.message</code> is a system-provided human-readable description of the error.</p>
<h3><code>error.path</code><span><a class="mark" href="#errors_error_path" id="errors_error_path">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>If present, <code>error.path</code> is a string containing a relevant invalid pathname.</p>
<h3><code>error.port</code><span><a class="mark" href="#errors_error_port" id="errors_error_port">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>If present, <code>error.port</code> is the network connection port that is not available.</p>
<h3><code>error.syscall</code><span><a class="mark" href="#errors_error_syscall" id="errors_error_syscall">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>error.syscall</code> property is a string describing the <a href="http://man7.org/linux/man-pages/man2/syscalls.2.html">syscall</a> that failed.</p>
<h3>Common system errors<span><a class="mark" href="#errors_common_system_errors" id="errors_common_system_errors">#</a></span></h3>
<p>This is a list of system errors commonly-encountered when writing a Node.js
program. For a comprehensive list, see the <a href="http://man7.org/linux/man-pages/man3/errno.3.html"><code>errno</code>(3) man page</a>.</p>
<ul>
<li>
<p><code>EACCES</code> (Permission denied): An attempt was made to access a file in a way
forbidden by its file access permissions.</p>
</li>
<li>
<p><code>EADDRINUSE</code> (Address already in use): An attempt to bind a server
(<a href="net.html"><code>net</code></a>, <a href="http.html"><code>http</code></a>, or <a href="https.html"><code>https</code></a>) to a local address failed due to
another server on the local system already occupying that address.</p>
</li>
<li>
<p><code>ECONNREFUSED</code> (Connection refused): No connection could be made because the
target machine actively refused it. This usually results from trying to
connect to a service that is inactive on the foreign host.</p>
</li>
<li>
<p><code>ECONNRESET</code> (Connection reset by peer): A connection was forcibly closed by
a peer. This normally results from a loss of the connection on the remote
socket due to a timeout or reboot. Commonly encountered via the <a href="http.html"><code>http</code></a>
and <a href="net.html"><code>net</code></a> modules.</p>
</li>
<li>
<p><code>EEXIST</code> (File exists): An existing file was the target of an operation that
required that the target not exist.</p>
</li>
<li>
<p><code>EISDIR</code> (Is a directory): An operation expected a file, but the given
pathname was a directory.</p>
</li>
<li>
<p><code>EMFILE</code> (Too many open files in system): Maximum number of
<a href="https://en.wikipedia.org/wiki/File_descriptor">file descriptors</a> allowable on the system has been reached, and
requests for another descriptor cannot be fulfilled until at least one
has been closed. This is encountered when opening many files at once in
parallel, especially on systems (in particular, macOS) where there is a low
file descriptor limit for processes. To remedy a low limit, run
<code>ulimit -n 2048</code> in the same shell that will run the Node.js process.</p>
</li>
<li>
<p><code>ENOENT</code> (No such file or directory): Commonly raised by <a href="fs.html"><code>fs</code></a> operations
to indicate that a component of the specified pathname does not exist. No
entity (file or directory) could be found by the given path.</p>
</li>
<li>
<p><code>ENOTDIR</code> (Not a directory): A component of the given pathname existed, but
was not a directory as expected. Commonly raised by <a href="#fs_fs_readdir_path_options_callback"><code>fs.readdir</code></a>.</p>
</li>
<li>
<p><code>ENOTEMPTY</code> (Directory not empty): A directory with entries was the target
of an operation that requires an empty directory, usually <a href="#fs_fs_unlink_path_callback"><code>fs.unlink</code></a>.</p>
</li>
<li>
<p><code>ENOTFOUND</code> (DNS lookup failed): Indicates a DNS failure of either
<code>EAI_NODATA</code> or <code>EAI_NONAME</code>. This is not a standard POSIX error.</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>
<h2>Class: <code>TypeError</code><span><a class="mark" href="#errors_class_typeerror" id="errors_class_typeerror">#</a></span></h2>
<ul>
<li>Extends <a href="#errors_class_error" class="type">&#x3C;errors.Error></a></li>
</ul>
<p>Indicates that a provided argument is not an allowable type. For example,
passing a function to a parameter which expects a string would be considered
a <code>TypeError</code>.</p>
<pre><code class="language-js">require('url').parse(() => { });
// Throws TypeError, since it expected a string.
</code></pre>
<p>Node.js will generate and throw <code>TypeError</code> instances <em>immediately</em> as a form
of argument validation.</p>
<h2>Exceptions vs. errors<span><a class="mark" href="#errors_exceptions_vs_errors" id="errors_exceptions_vs_errors">#</a></span></h2>

<p>A JavaScript exception is a value that is thrown as a result of an invalid
operation or as the target of a <code>throw</code> statement. While it is not required
that these values are instances of <code>Error</code> or classes which inherit from
<code>Error</code>, all exceptions thrown by Node.js or the JavaScript runtime <em>will</em> be
instances of <code>Error</code>.</p>
<p>Some exceptions are <em>unrecoverable</em> at the JavaScript layer. Such exceptions
will <em>always</em> cause the Node.js process to crash. Examples include <code>assert()</code>
checks or <code>abort()</code> calls in the C++ layer.</p>
<h2>OpenSSL errors<span><a class="mark" href="#errors_openssl_errors" id="errors_openssl_errors">#</a></span></h2>
<p>Errors originating in <code>crypto</code> or <code>tls</code> are of class <code>Error</code>, and in addition to
the standard <code>.code</code> and <code>.message</code> properties, may have some additional
OpenSSL-specific properties.</p>
<h3><code>error.opensslErrorStack</code><span><a class="mark" href="#errors_error_opensslerrorstack" id="errors_error_opensslerrorstack">#</a></span></h3>
<p>An array of errors that can give context to where in the OpenSSL library an
error originates from.</p>
<h3><code>error.function</code><span><a class="mark" href="#errors_error_function" id="errors_error_function">#</a></span></h3>
<p>The OpenSSL function the error originates in.</p>
<h3><code>error.library</code><span><a class="mark" href="#errors_error_library" id="errors_error_library">#</a></span></h3>
<p>The OpenSSL library the error originates in.</p>
<h3><code>error.reason</code><span><a class="mark" href="#errors_error_reason" id="errors_error_reason">#</a></span></h3>
<p>A human-readable string describing the reason for the error.</p>
<p><a id="nodejs-error-codes"></a></p>
<h2>Node.js error codes<span><a class="mark" href="#errors_node_js_error_codes" id="errors_node_js_error_codes">#</a></span></h2>
<p><a id="ERR_AMBIGUOUS_ARGUMENT"></a></p>
<h3><code>ERR_AMBIGUOUS_ARGUMENT</code><span><a class="mark" href="#errors_err_ambiguous_argument" id="errors_err_ambiguous_argument">#</a></span></h3>
<p>A function argument is being used in a way that suggests that the function
signature may be misunderstood. This is thrown by the <code>assert</code> module when the
<code>message</code> parameter in <code>assert.throws(block, message)</code> matches the error message
thrown by <code>block</code> because that usage suggests that the user believes <code>message</code>
is the expected message rather than the message the <code>AssertionError</code> will
display if <code>block</code> does not throw.</p>
<p><a id="ERR_ARG_NOT_ITERABLE"></a></p>
<h3><code>ERR_ARG_NOT_ITERABLE</code><span><a class="mark" href="#errors_err_arg_not_iterable" id="errors_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><code>ERR_ASSERTION</code><span><a class="mark" href="#errors_err_assertion" id="errors_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><code>ERR_ASYNC_CALLBACK</code><span><a class="mark" href="#errors_err_async_callback" id="errors_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><code>ERR_ASYNC_TYPE</code><span><a class="mark" href="#errors_err_async_type" id="errors_err_async_type">#</a></span></h3>
<p>The type of an asynchronous resource was invalid. Users are also able
to define their own types if using the public embedder API.</p>
<p><a id="ERR_BROTLI_COMPRESSION_FAILED"></a></p>
<h3><code>ERR_BROTLI_COMPRESSION_FAILED</code><span><a class="mark" href="#errors_err_brotli_compression_failed" id="errors_err_brotli_compression_failed">#</a></span></h3>
<p>Data passed to a Brotli stream was not successfully compressed.</p>
<p><a id="ERR_BROTLI_INVALID_PARAM"></a></p>
<h3><code>ERR_BROTLI_INVALID_PARAM</code><span><a class="mark" href="#errors_err_brotli_invalid_param" id="errors_err_brotli_invalid_param">#</a></span></h3>
<p>An invalid parameter key was passed during construction of a Brotli stream.</p>
<p><a id="ERR_BUFFER_CONTEXT_NOT_AVAILABLE"></a></p>
<h3><code>ERR_BUFFER_CONTEXT_NOT_AVAILABLE</code><span><a class="mark" href="#errors_err_buffer_context_not_available" id="errors_err_buffer_context_not_available">#</a></span></h3>
<p>An attempt was made to create a Node.js <code>Buffer</code> instance from addon or embedder
code, while in a JS engine Context that is not associated with a Node.js
instance. The data passed to the <code>Buffer</code> method will have been released
by the time the method returns.</p>
<p>When encountering this error, a possible alternative to creating a <code>Buffer</code>
instance is to create a normal <code>Uint8Array</code>, which only differs in the
prototype of the resulting object. <code>Uint8Array</code>s are generally accepted in all
Node.js core APIs where <code>Buffer</code>s are; they are available in all Contexts.</p>
<p><a id="ERR_BUFFER_OUT_OF_BOUNDS"></a></p>
<h3><code>ERR_BUFFER_OUT_OF_BOUNDS</code><span><a class="mark" href="#errors_err_buffer_out_of_bounds" id="errors_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><code>ERR_BUFFER_TOO_LARGE</code><span><a class="mark" href="#errors_err_buffer_too_large" id="errors_err_buffer_too_large">#</a></span></h3>
<p>An attempt has been made to create a <code>Buffer</code> larger than the maximum allowed
size.</p>
<p><a id="ERR_CANNOT_WATCH_SIGINT"></a></p>
<h3><code>ERR_CANNOT_WATCH_SIGINT</code><span><a class="mark" href="#errors_err_cannot_watch_sigint" id="errors_err_cannot_watch_sigint">#</a></span></h3>
<p>Node.js was unable to watch for the <code>SIGINT</code> signal.</p>
<p><a id="ERR_CHILD_CLOSED_BEFORE_REPLY"></a></p>
<h3><code>ERR_CHILD_CLOSED_BEFORE_REPLY</code><span><a class="mark" href="#errors_err_child_closed_before_reply" id="errors_err_child_closed_before_reply">#</a></span></h3>
<p>A child process was closed before the parent received a reply.</p>
<p><a id="ERR_CHILD_PROCESS_IPC_REQUIRED"></a></p>
<h3><code>ERR_CHILD_PROCESS_IPC_REQUIRED</code><span><a class="mark" href="#errors_err_child_process_ipc_required" id="errors_err_child_process_ipc_required">#</a></span></h3>
<p>Used when a child process is being forked without specifying an IPC channel.</p>
<p><a id="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"></a></p>
<h3><code>ERR_CHILD_PROCESS_STDIO_MAXBUFFER</code><span><a class="mark" href="#errors_err_child_process_stdio_maxbuffer" id="errors_err_child_process_stdio_maxbuffer">#</a></span></h3>
<p>Used when the main process is trying to read data from the child process's
STDERR/STDOUT, and the data's length is longer than the <code>maxBuffer</code> option.</p>
<p><a id="ERR_CONSOLE_WRITABLE_STREAM"></a></p>
<h3><code>ERR_CONSOLE_WRITABLE_STREAM</code><span><a class="mark" href="#errors_err_console_writable_stream" id="errors_err_console_writable_stream">#</a></span></h3>
<p><code>Console</code> was instantiated without <code>stdout</code> stream, or <code>Console</code> has a
non-writable <code>stdout</code> or <code>stderr</code> stream.</p>
<p><a id="ERR_CONSTRUCT_CALL_REQUIRED"></a></p>
<h3><code>ERR_CONSTRUCT_CALL_REQUIRED</code><span><a class="mark" href="#errors_err_construct_call_required" id="errors_err_construct_call_required">#</a></span></h3>
<p>A constructor for a class was called without <code>new</code>.</p>
<p><a id="ERR_CONSTRUCT_CALL_INVALID"></a></p>
<h3><code>ERR_CONSTRUCT_CALL_INVALID</code><span><a class="mark" href="#errors_err_construct_call_invalid" id="errors_err_construct_call_invalid">#</a></span></h3>
<!--
added: v12.5.0
-->
<p>A class constructor was called that is not callable.</p>
<p><a id="ERR_CPU_USAGE"></a></p>
<h3><code>ERR_CPU_USAGE</code><span><a class="mark" href="#errors_err_cpu_usage" id="errors_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><code>ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED</code><span><a class="mark" href="#errors_err_crypto_custom_engine_not_supported" id="errors_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><code>ERR_CRYPTO_ECDH_INVALID_FORMAT</code><span><a class="mark" href="#errors_err_crypto_ecdh_invalid_format" id="errors_err_crypto_ecdh_invalid_format">#</a></span></h3>
<p>An invalid value for the <code>format</code> argument was passed to the <code>crypto.ECDH()</code>
class <code>getPublicKey()</code> method.</p>
<p><a id="ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY"></a></p>
<h3><code>ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY</code><span><a class="mark" href="#errors_err_crypto_ecdh_invalid_public_key" id="errors_err_crypto_ecdh_invalid_public_key">#</a></span></h3>
<p>An invalid value for the <code>key</code> argument has been passed to the
<code>crypto.ECDH()</code> class <code>computeSecret()</code> method. It means that the public
key lies outside of the elliptic curve.</p>
<p><a id="ERR_CRYPTO_ENGINE_UNKNOWN"></a></p>
<h3><code>ERR_CRYPTO_ENGINE_UNKNOWN</code><span><a class="mark" href="#errors_err_crypto_engine_unknown" id="errors_err_crypto_engine_unknown">#</a></span></h3>
<p>An invalid crypto engine identifier was passed to
<a href="#crypto_crypto_setengine_engine_flags"><code>require('crypto').setEngine()</code></a>.</p>
<p><a id="ERR_CRYPTO_FIPS_FORCED"></a></p>
<h3><code>ERR_CRYPTO_FIPS_FORCED</code><span><a class="mark" href="#errors_err_crypto_fips_forced" id="errors_err_crypto_fips_forced">#</a></span></h3>
<p>The <a href="#cli_force_fips"><code>--force-fips</code></a> command-line argument was used but there was an attempt
to enable or disable FIPS mode in the <code>crypto</code> module.</p>
<p><a id="ERR_CRYPTO_FIPS_UNAVAILABLE"></a></p>
<h3><code>ERR_CRYPTO_FIPS_UNAVAILABLE</code><span><a class="mark" href="#errors_err_crypto_fips_unavailable" id="errors_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_FINALIZED"></a></p>
<h3><code>ERR_CRYPTO_HASH_FINALIZED</code><span><a class="mark" href="#errors_err_crypto_hash_finalized" id="errors_err_crypto_hash_finalized">#</a></span></h3>
<p><a href="#crypto_hash_digest_encoding"><code>hash.digest()</code></a> was called multiple times. The <code>hash.digest()</code> method must
be called no more than one time per instance of a <code>Hash</code> object.</p>
<p><a id="ERR_CRYPTO_HASH_UPDATE_FAILED"></a></p>
<h3><code>ERR_CRYPTO_HASH_UPDATE_FAILED</code><span><a class="mark" href="#errors_err_crypto_hash_update_failed" id="errors_err_crypto_hash_update_failed">#</a></span></h3>
<p><a href="#crypto_hash_update_data_inputencoding"><code>hash.update()</code></a> failed for any reason. This should rarely, if ever, happen.</p>
<p><a id="ERR_CRYPTO_INCOMPATIBLE_KEY"></a></p>
<h3><code>ERR_CRYPTO_INCOMPATIBLE_KEY</code><span><a class="mark" href="#errors_err_crypto_incompatible_key" id="errors_err_crypto_incompatible_key">#</a></span></h3>
<p>The given crypto keys are incompatible with the attempted operation.</p>
<p><a id="ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS"></a></p>
<h3><code>ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS</code><span><a class="mark" href="#errors_err_crypto_incompatible_key_options" id="errors_err_crypto_incompatible_key_options">#</a></span></h3>
<p>The selected public or private key encoding is incompatible with other options.</p>
<p><a id="ERR_CRYPTO_INVALID_DIGEST"></a></p>
<h3><code>ERR_CRYPTO_INVALID_DIGEST</code><span><a class="mark" href="#errors_err_crypto_invalid_digest" id="errors_err_crypto_invalid_digest">#</a></span></h3>
<p>An invalid <a href="#crypto_crypto_gethashes">crypto digest algorithm</a> was specified.</p>
<p><a id="ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE"></a></p>
<h3><code>ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE</code><span><a class="mark" href="#errors_err_crypto_invalid_key_object_type" id="errors_err_crypto_invalid_key_object_type">#</a></span></h3>
<p>The given crypto key object's type is invalid for the attempted operation.</p>
<p><a id="ERR_CRYPTO_INVALID_STATE"></a></p>
<h3><code>ERR_CRYPTO_INVALID_STATE</code><span><a class="mark" href="#errors_err_crypto_invalid_state" id="errors_err_crypto_invalid_state">#</a></span></h3>
<p>A crypto method was used on an object that was in an invalid state. For
instance, calling <a href="#crypto_cipher_getauthtag"><code>cipher.getAuthTag()</code></a> before calling <code>cipher.final()</code>.</p>
<p><a id="ERR_CRYPTO_PBKDF2_ERROR"></a></p>
<h3><code>ERR_CRYPTO_PBKDF2_ERROR</code><span><a class="mark" href="#errors_err_crypto_pbkdf2_error" id="errors_err_crypto_pbkdf2_error">#</a></span></h3>
<p>The PBKDF2 algorithm failed for unspecified reasons. OpenSSL does not provide
more details and therefore neither does Node.js.</p>
<p><a id="ERR_CRYPTO_SCRYPT_INVALID_PARAMETER"></a></p>
<h3><code>ERR_CRYPTO_SCRYPT_INVALID_PARAMETER</code><span><a class="mark" href="#errors_err_crypto_scrypt_invalid_parameter" id="errors_err_crypto_scrypt_invalid_parameter">#</a></span></h3>
<p>One or more <a href="#crypto_crypto_scrypt_password_salt_keylen_options_callback"><code>crypto.scrypt()</code></a> or <a href="#crypto_crypto_scryptsync_password_salt_keylen_options"><code>crypto.scryptSync()</code></a> parameters are
outside their legal range.</p>
<p><a id="ERR_CRYPTO_SCRYPT_NOT_SUPPORTED"></a></p>
<h3><code>ERR_CRYPTO_SCRYPT_NOT_SUPPORTED</code><span><a class="mark" href="#errors_err_crypto_scrypt_not_supported" id="errors_err_crypto_scrypt_not_supported">#</a></span></h3>
<p>Node.js was compiled without <code>scrypt</code> support. Not possible with the official
release binaries but can happen with custom builds, including distro builds.</p>
<p><a id="ERR_CRYPTO_SIGN_KEY_REQUIRED"></a></p>
<h3><code>ERR_CRYPTO_SIGN_KEY_REQUIRED</code><span><a class="mark" href="#errors_err_crypto_sign_key_required" id="errors_err_crypto_sign_key_required">#</a></span></h3>
<p>A signing <code>key</code> was not provided to the <a href="#crypto_sign_sign_privatekey_outputencoding"><code>sign.sign()</code></a> method.</p>
<p><a id="ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH"></a></p>
<h3><code>ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH</code><span><a class="mark" href="#errors_err_crypto_timing_safe_equal_length" id="errors_err_crypto_timing_safe_equal_length">#</a></span></h3>
<p><a href="#crypto_crypto_timingsafeequal_a_b"><code>crypto.timingSafeEqual()</code></a> was called with <code>Buffer</code>, <code>TypedArray</code>, or
<code>DataView</code> arguments of different lengths.</p>
<p><a id="ERR_CRYPTO_UNKNOWN_CIPHER"></a></p>
<h3><code>ERR_CRYPTO_UNKNOWN_CIPHER</code><span><a class="mark" href="#errors_err_crypto_unknown_cipher" id="errors_err_crypto_unknown_cipher">#</a></span></h3>
<p>An unknown cipher was specified.</p>
<p><a id="ERR_CRYPTO_UNKNOWN_DH_GROUP"></a></p>
<h3><code>ERR_CRYPTO_UNKNOWN_DH_GROUP</code><span><a class="mark" href="#errors_err_crypto_unknown_dh_group" id="errors_err_crypto_unknown_dh_group">#</a></span></h3>
<p>An unknown Diffie-Hellman group name was given. See
<a href="#crypto_crypto_getdiffiehellman_groupname"><code>crypto.getDiffieHellman()</code></a> for a list of valid group names.</p>
<p><a id="ERR_DIR_CLOSED"></a></p>
<h3><code>ERR_DIR_CLOSED</code><span><a class="mark" href="#errors_err_dir_closed" id="errors_err_dir_closed">#</a></span></h3>
<p>The <a href="#fs_class_fs_dir"><code>fs.Dir</code></a> was previously closed.</p>
<p><a id="ERR_DIR_CONCURRENT_OPERATION"></a></p>
<h3><code>ERR_DIR_CONCURRENT_OPERATION</code><span><a class="mark" href="#errors_err_dir_concurrent_operation" id="errors_err_dir_concurrent_operation">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.18.1</span>
</div>
<p>A synchronous read or close call was attempted on an <a href="#fs_class_fs_dir"><code>fs.Dir</code></a> which has
ongoing asynchronous operations.</p>
<p><a id="ERR_DNS_SET_SERVERS_FAILED"></a></p>
<h3><code>ERR_DNS_SET_SERVERS_FAILED</code><span><a class="mark" href="#errors_err_dns_set_servers_failed" id="errors_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><code>ERR_DOMAIN_CALLBACK_NOT_AVAILABLE</code><span><a class="mark" href="#errors_err_domain_callback_not_available" id="errors_err_domain_callback_not_available">#</a></span></h3>
<p>The <code>domain</code> module was not usable since it could not establish the required
error handling hooks, because
<a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> had been called at an
earlier point in time.</p>
<p><a id="ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE"></a></p>
<h3><code>ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</code><span><a class="mark" href="#errors_err_domain_cannot_set_uncaught_exception_capture" id="errors_err_domain_cannot_set_uncaught_exception_capture">#</a></span></h3>
<p><a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> could not be called
because the <code>domain</code> module has been loaded at an earlier point in time.</p>
<p>The stack trace is extended to include the point in time at which the
<code>domain</code> module had been loaded.</p>
<p><a id="ERR_ENCODING_INVALID_ENCODED_DATA"></a></p>
<h3><code>ERR_ENCODING_INVALID_ENCODED_DATA</code><span><a class="mark" href="#errors_err_encoding_invalid_encoded_data" id="errors_err_encoding_invalid_encoded_data">#</a></span></h3>
<p>Data provided to <code>TextDecoder()</code> API was invalid according to the encoding
provided.</p>
<p><a id="ERR_ENCODING_NOT_SUPPORTED"></a></p>
<h3><code>ERR_ENCODING_NOT_SUPPORTED</code><span><a class="mark" href="#errors_err_encoding_not_supported" id="errors_err_encoding_not_supported">#</a></span></h3>
<p>Encoding provided to <code>TextDecoder()</code> API was not one of the
<a href="#util_whatwg_supported_encodings">WHATWG Supported Encodings</a>.</p>
<p><a id="ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE"></a></p>
<h3><code>ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE</code><span><a class="mark" href="#errors_err_execution_environment_not_available" id="errors_err_execution_environment_not_available">#</a></span></h3>
<p>The JS execution context is not associated with a Node.js environment.
This may occur when Node.js is used as an embedded library and some hooks
for the JS engine are not set up properly.</p>
<p><a id="ERR_FALSY_VALUE_REJECTION"></a></p>
<h3><code>ERR_FALSY_VALUE_REJECTION</code><span><a class="mark" href="#errors_err_falsy_value_rejection" id="errors_err_falsy_value_rejection">#</a></span></h3>
<p>A <code>Promise</code> that was callbackified via <code>util.callbackify()</code> was rejected with a
falsy value.</p>
<p><a id="ERR_FS_FILE_TOO_LARGE"></a></p>
<h3><code>ERR_FS_FILE_TOO_LARGE</code><span><a class="mark" href="#errors_err_fs_file_too_large" id="errors_err_fs_file_too_large">#</a></span></h3>
<p>An attempt has been made to read a file whose size is larger than the maximum
allowed size for a <code>Buffer</code>.</p>
<p><a id="ERR_FS_INVALID_SYMLINK_TYPE"></a></p>
<h3><code>ERR_FS_INVALID_SYMLINK_TYPE</code><span><a class="mark" href="#errors_err_fs_invalid_symlink_type" id="errors_err_fs_invalid_symlink_type">#</a></span></h3>
<p>An invalid symlink type was passed to the <a href="#fs_fs_symlink_target_path_type_callback"><code>fs.symlink()</code></a> or
<a href="#fs_fs_symlinksync_target_path_type"><code>fs.symlinkSync()</code></a> methods.</p>
<p><a id="ERR_HTTP_HEADERS_SENT"></a></p>
<h3><code>ERR_HTTP_HEADERS_SENT</code><span><a class="mark" href="#errors_err_http_headers_sent" id="errors_err_http_headers_sent">#</a></span></h3>
<p>An attempt was made to add more headers after the headers had already been sent.</p>
<p><a id="ERR_HTTP_INVALID_HEADER_VALUE"></a></p>
<h3><code>ERR_HTTP_INVALID_HEADER_VALUE</code><span><a class="mark" href="#errors_err_http_invalid_header_value" id="errors_err_http_invalid_header_value">#</a></span></h3>
<p>An invalid HTTP header value was specified.</p>
<p><a id="ERR_HTTP_INVALID_STATUS_CODE"></a></p>
<h3><code>ERR_HTTP_INVALID_STATUS_CODE</code><span><a class="mark" href="#errors_err_http_invalid_status_code" id="errors_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><code>ERR_HTTP_TRAILER_INVALID</code><span><a class="mark" href="#errors_err_http_trailer_invalid" id="errors_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><code>ERR_HTTP2_ALTSVC_INVALID_ORIGIN</code><span><a class="mark" href="#errors_err_http2_altsvc_invalid_origin" id="errors_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><code>ERR_HTTP2_ALTSVC_LENGTH</code><span><a class="mark" href="#errors_err_http2_altsvc_length" id="errors_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><code>ERR_HTTP2_CONNECT_AUTHORITY</code><span><a class="mark" href="#errors_err_http2_connect_authority" id="errors_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><code>ERR_HTTP2_CONNECT_PATH</code><span><a class="mark" href="#errors_err_http2_connect_path" id="errors_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><code>ERR_HTTP2_CONNECT_SCHEME</code><span><a class="mark" href="#errors_err_http2_connect_scheme" id="errors_err_http2_connect_scheme">#</a></span></h3>
<p>For HTTP/2 requests using the <code>CONNECT</code> method, the <code>:scheme</code> pseudo-header is
forbidden.</p>
<p><a id="ERR_HTTP2_ERROR"></a></p>
<h3><code>ERR_HTTP2_ERROR</code><span><a class="mark" href="#errors_err_http2_error" id="errors_err_http2_error">#</a></span></h3>
<p>A non-specific HTTP/2 error has occurred.</p>
<p><a id="ERR_HTTP2_GOAWAY_SESSION"></a></p>
<h3><code>ERR_HTTP2_GOAWAY_SESSION</code><span><a class="mark" href="#errors_err_http2_goaway_session" id="errors_err_http2_goaway_session">#</a></span></h3>
<p>New HTTP/2 Streams may not be opened after the <code>Http2Session</code> has received a
<code>GOAWAY</code> frame from the connected peer.</p>
<p><a id="ERR_HTTP2_HEADERS_AFTER_RESPOND"></a></p>
<h3><code>ERR_HTTP2_HEADERS_AFTER_RESPOND</code><span><a class="mark" href="#errors_err_http2_headers_after_respond" id="errors_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><code>ERR_HTTP2_HEADERS_SENT</code><span><a class="mark" href="#errors_err_http2_headers_sent" id="errors_err_http2_headers_sent">#</a></span></h3>
<p>An attempt was made to send multiple response headers.</p>
<p><a id="ERR_HTTP2_HEADER_SINGLE_VALUE"></a></p>
<h3><code>ERR_HTTP2_HEADER_SINGLE_VALUE</code><span><a class="mark" href="#errors_err_http2_header_single_value" id="errors_err_http2_header_single_value">#</a></span></h3>
<p>Multiple values were provided for an HTTP/2 header field that was required to
have only a single value.</p>
<p><a id="ERR_HTTP2_INFO_STATUS_NOT_ALLOWED"></a></p>
<h3><code>ERR_HTTP2_INFO_STATUS_NOT_ALLOWED</code><span><a class="mark" href="#errors_err_http2_info_status_not_allowed" id="errors_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><code>ERR_HTTP2_INVALID_CONNECTION_HEADERS</code><span><a class="mark" href="#errors_err_http2_invalid_connection_headers" id="errors_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><code>ERR_HTTP2_INVALID_HEADER_VALUE</code><span><a class="mark" href="#errors_err_http2_invalid_header_value" id="errors_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><code>ERR_HTTP2_INVALID_INFO_STATUS</code><span><a class="mark" href="#errors_err_http2_invalid_info_status" id="errors_err_http2_invalid_info_status">#</a></span></h3>
<p>An invalid HTTP informational status code has been specified. Informational
status codes must be an integer between <code>100</code> and <code>199</code> (inclusive).</p>
<p><a id="ERR_HTTP2_INVALID_ORIGIN"></a></p>
<h3><code>ERR_HTTP2_INVALID_ORIGIN</code><span><a class="mark" href="#errors_err_http2_invalid_origin" id="errors_err_http2_invalid_origin">#</a></span></h3>
<p>HTTP/2 <code>ORIGIN</code> frames require a valid origin.</p>
<p><a id="ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH"></a></p>
<h3><code>ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH</code><span><a class="mark" href="#errors_err_http2_invalid_packed_settings_length" id="errors_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><code>ERR_HTTP2_INVALID_PSEUDOHEADER</code><span><a class="mark" href="#errors_err_http2_invalid_pseudoheader" id="errors_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><code>ERR_HTTP2_INVALID_SESSION</code><span><a class="mark" href="#errors_err_http2_invalid_session" id="errors_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><code>ERR_HTTP2_INVALID_SETTING_VALUE</code><span><a class="mark" href="#errors_err_http2_invalid_setting_value" id="errors_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><code>ERR_HTTP2_INVALID_STREAM</code><span><a class="mark" href="#errors_err_http2_invalid_stream" id="errors_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><code>ERR_HTTP2_MAX_PENDING_SETTINGS_ACK</code><span><a class="mark" href="#errors_err_http2_max_pending_settings_ack" id="errors_err_http2_max_pending_settings_ack">#</a></span></h3>
<p>Whenever an HTTP/2 <code>SETTINGS</code> frame is sent to a connected peer, the peer is
required to send an acknowledgment that it has received and applied the new
<code>SETTINGS</code>. By default, a maximum number of unacknowledged <code>SETTINGS</code> frames may
be sent at any given time. This error code is used when that limit has been
reached.</p>
<p><a id="ERR_HTTP2_NESTED_PUSH"></a></p>
<h3><code>ERR_HTTP2_NESTED_PUSH</code><span><a class="mark" href="#errors_err_http2_nested_push" id="errors_err_http2_nested_push">#</a></span></h3>
<p>An attempt was made to initiate a new push stream from within a push stream.
Nested push streams are not permitted.</p>
<p><a id="ERR_HTTP2_NO_SOCKET_MANIPULATION"></a></p>
<h3><code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code><span><a class="mark" href="#errors_err_http2_no_socket_manipulation" id="errors_err_http2_no_socket_manipulation">#</a></span></h3>
<p>An attempt was made to directly manipulate (read, write, pause, resume, etc.) a
socket attached to an <code>Http2Session</code>.</p>
<p><a id="ERR_HTTP2_ORIGIN_LENGTH"></a></p>
<h3><code>ERR_HTTP2_ORIGIN_LENGTH</code><span><a class="mark" href="#errors_err_http2_origin_length" id="errors_err_http2_origin_length">#</a></span></h3>
<p>HTTP/2 <code>ORIGIN</code> frames are limited to a length of 16382 bytes.</p>
<p><a id="ERR_HTTP2_OUT_OF_STREAMS"></a></p>
<h3><code>ERR_HTTP2_OUT_OF_STREAMS</code><span><a class="mark" href="#errors_err_http2_out_of_streams" id="errors_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><code>ERR_HTTP2_PAYLOAD_FORBIDDEN</code><span><a class="mark" href="#errors_err_http2_payload_forbidden" id="errors_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><code>ERR_HTTP2_PING_CANCEL</code><span><a class="mark" href="#errors_err_http2_ping_cancel" id="errors_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><code>ERR_HTTP2_PING_LENGTH</code><span><a class="mark" href="#errors_err_http2_ping_length" id="errors_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><code>ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED</code><span><a class="mark" href="#errors_err_http2_pseudoheader_not_allowed" id="errors_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><code>ERR_HTTP2_PUSH_DISABLED</code><span><a class="mark" href="#errors_err_http2_push_disabled" id="errors_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><code>ERR_HTTP2_SEND_FILE</code><span><a class="mark" href="#errors_err_http2_send_file" id="errors_err_http2_send_file">#</a></span></h3>
<p>An attempt was made to use the <code>Http2Stream.prototype.responseWithFile()</code> API to
send a directory.</p>
<p><a id="ERR_HTTP2_SEND_FILE_NOSEEK"></a></p>
<h3><code>ERR_HTTP2_SEND_FILE_NOSEEK</code><span><a class="mark" href="#errors_err_http2_send_file_noseek" id="errors_err_http2_send_file_noseek">#</a></span></h3>
<p>An attempt was made to use the <code>Http2Stream.prototype.responseWithFile()</code> API to
send something other than a regular file, but <code>offset</code> or <code>length</code> options were
provided.</p>
<p><a id="ERR_HTTP2_SESSION_ERROR"></a></p>
<h3><code>ERR_HTTP2_SESSION_ERROR</code><span><a class="mark" href="#errors_err_http2_session_error" id="errors_err_http2_session_error">#</a></span></h3>
<p>The <code>Http2Session</code> closed with a non-zero error code.</p>
<p><a id="ERR_HTTP2_SETTINGS_CANCEL"></a></p>
<h3><code>ERR_HTTP2_SETTINGS_CANCEL</code><span><a class="mark" href="#errors_err_http2_settings_cancel" id="errors_err_http2_settings_cancel">#</a></span></h3>
<p>The <code>Http2Session</code> settings canceled.</p>
<p><a id="ERR_HTTP2_SOCKET_BOUND"></a></p>
<h3><code>ERR_HTTP2_SOCKET_BOUND</code><span><a class="mark" href="#errors_err_http2_socket_bound" id="errors_err_http2_socket_bound">#</a></span></h3>
<p>An attempt was made to connect a <code>Http2Session</code> object to a <code>net.Socket</code> or
<code>tls.TLSSocket</code> that had already been bound to another <code>Http2Session</code> object.</p>
<p><a id="ERR_HTTP2_SOCKET_UNBOUND"></a></p>
<h3><code>ERR_HTTP2_SOCKET_UNBOUND</code><span><a class="mark" href="#errors_err_http2_socket_unbound" id="errors_err_http2_socket_unbound">#</a></span></h3>
<p>An attempt was made to use the <code>socket</code> property of an <code>Http2Session</code> that
has already been closed.</p>
<p><a id="ERR_HTTP2_STATUS_101"></a></p>
<h3><code>ERR_HTTP2_STATUS_101</code><span><a class="mark" href="#errors_err_http2_status_101" id="errors_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><code>ERR_HTTP2_STATUS_INVALID</code><span><a class="mark" href="#errors_err_http2_status_invalid" id="errors_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><code>ERR_HTTP2_STREAM_CANCEL</code><span><a class="mark" href="#errors_err_http2_stream_cancel" id="errors_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><code>ERR_HTTP2_STREAM_ERROR</code><span><a class="mark" href="#errors_err_http2_stream_error" id="errors_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><code>ERR_HTTP2_STREAM_SELF_DEPENDENCY</code><span><a class="mark" href="#errors_err_http2_stream_self_dependency" id="errors_err_http2_stream_self_dependency">#</a></span></h3>
<p>When setting the priority for an HTTP/2 stream, the stream may be marked as
a dependency for a parent stream. This error code is used when an attempt is
made to mark a stream and dependent of itself.</p>
<p><a id="ERR_HTTP2_TRAILERS_ALREADY_SENT"></a></p>
<h3><code>ERR_HTTP2_TRAILERS_ALREADY_SENT</code><span><a class="mark" href="#errors_err_http2_trailers_already_sent" id="errors_err_http2_trailers_already_sent">#</a></span></h3>
<p>Trailing headers have already been sent on the <code>Http2Stream</code>.</p>
<p><a id="ERR_HTTP2_TRAILERS_NOT_READY"></a></p>
<h3><code>ERR_HTTP2_TRAILERS_NOT_READY</code><span><a class="mark" href="#errors_err_http2_trailers_not_ready" id="errors_err_http2_trailers_not_ready">#</a></span></h3>
<p>The <code>http2stream.sendTrailers()</code> method cannot be called until after the
<code>'wantTrailers'</code> event is emitted on an <code>Http2Stream</code> object. The
<code>'wantTrailers'</code> event will only be emitted if the <code>waitForTrailers</code> option
is set for the <code>Http2Stream</code>.</p>
<p><a id="ERR_HTTP2_UNSUPPORTED_PROTOCOL"></a></p>
<h3><code>ERR_HTTP2_UNSUPPORTED_PROTOCOL</code><span><a class="mark" href="#errors_err_http2_unsupported_protocol" id="errors_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_INTERNAL_ASSERTION"></a></p>
<h3><code>ERR_INTERNAL_ASSERTION</code><span><a class="mark" href="#errors_err_internal_assertion" id="errors_err_internal_assertion">#</a></span></h3>
<p>There was a bug in Node.js or incorrect usage of Node.js internals.
To fix the error, open an issue at <a href="https://github.com/nodejs/node/issues">https://github.com/nodejs/node/issues</a>.</p>
<p><a id="ERR_INCOMPATIBLE_OPTION_PAIR"></a></p>
<h3><code>ERR_INCOMPATIBLE_OPTION_PAIR</code><span><a class="mark" href="#errors_err_incompatible_option_pair" id="errors_err_incompatible_option_pair">#</a></span></h3>
<p>An option pair is incompatible with each other and cannot be used at the same
time.</p>
<p><a id="ERR_INPUT_TYPE_NOT_ALLOWED"></a></p>
<h3><code>ERR_INPUT_TYPE_NOT_ALLOWED</code><span><a class="mark" href="#errors_err_input_type_not_allowed" id="errors_err_input_type_not_allowed">#</a></span></h3>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>The <code>--input-type</code> flag was used to attempt to execute a file. This flag can
only be used with input via <code>--eval</code>, <code>--print</code> or <code>STDIN</code>.</p>
<p><a id="ERR_INSPECTOR_ALREADY_ACTIVATED"></a></p>
<h3><code>ERR_INSPECTOR_ALREADY_ACTIVATED</code><span><a class="mark" href="#errors_err_inspector_already_activated" id="errors_err_inspector_already_activated">#</a></span></h3>
<p>While using the <code>inspector</code> module, an attempt was made to activate the
inspector when it already started to listen on a port. Use <code>inspector.close()</code>
before activating it on a different address.</p>
<p><a id="ERR_INSPECTOR_ALREADY_CONNECTED"></a></p>
<h3><code>ERR_INSPECTOR_ALREADY_CONNECTED</code><span><a class="mark" href="#errors_err_inspector_already_connected" id="errors_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><code>ERR_INSPECTOR_CLOSED</code><span><a class="mark" href="#errors_err_inspector_closed" id="errors_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_COMMAND"></a></p>
<h3><code>ERR_INSPECTOR_COMMAND</code><span><a class="mark" href="#errors_err_inspector_command" id="errors_err_inspector_command">#</a></span></h3>
<p>An error occurred while issuing a command via the <code>inspector</code> module.</p>
<p><a id="ERR_INSPECTOR_NOT_ACTIVE"></a></p>
<h3><code>ERR_INSPECTOR_NOT_ACTIVE</code><span><a class="mark" href="#errors_err_inspector_not_active" id="errors_err_inspector_not_active">#</a></span></h3>
<p>The <code>inspector</code> is not active when <code>inspector.waitForDebugger()</code> is called.</p>
<p><a id="ERR_INSPECTOR_NOT_AVAILABLE"></a></p>
<h3><code>ERR_INSPECTOR_NOT_AVAILABLE</code><span><a class="mark" href="#errors_err_inspector_not_available" id="errors_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><code>ERR_INSPECTOR_NOT_CONNECTED</code><span><a class="mark" href="#errors_err_inspector_not_connected" id="errors_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_INSPECTOR_NOT_WORKER"></a></p>
<h3><code>ERR_INSPECTOR_NOT_WORKER</code><span><a class="mark" href="#errors_err_inspector_not_worker" id="errors_err_inspector_not_worker">#</a></span></h3>
<p>An API was called on the main thread that can only be used from
the worker thread.</p>
<p><a id="ERR_INVALID_ADDRESS_FAMILY"></a></p>
<h3><code>ERR_INVALID_ADDRESS_FAMILY</code><span><a class="mark" href="#errors_err_invalid_address_family" id="errors_err_invalid_address_family">#</a></span></h3>
<p>The provided address family is not understood by the Node.js API.</p>
<p><a id="ERR_INVALID_ARG_TYPE"></a></p>
<h3><code>ERR_INVALID_ARG_TYPE</code><span><a class="mark" href="#errors_err_invalid_arg_type" id="errors_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><code>ERR_INVALID_ARG_VALUE</code><span><a class="mark" href="#errors_err_invalid_arg_value" id="errors_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_ASYNC_ID"></a></p>
<h3><code>ERR_INVALID_ASYNC_ID</code><span><a class="mark" href="#errors_err_invalid_async_id" id="errors_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><code>ERR_INVALID_BUFFER_SIZE</code><span><a class="mark" href="#errors_err_invalid_buffer_size" id="errors_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><code>ERR_INVALID_CALLBACK</code><span><a class="mark" href="#errors_err_invalid_callback" id="errors_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><code>ERR_INVALID_CHAR</code><span><a class="mark" href="#errors_err_invalid_char" id="errors_err_invalid_char">#</a></span></h3>
<p>Invalid characters were detected in headers.</p>
<p><a id="ERR_INVALID_CURSOR_POS"></a></p>
<h3><code>ERR_INVALID_CURSOR_POS</code><span><a class="mark" href="#errors_err_invalid_cursor_pos" id="errors_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_FD"></a></p>
<h3><code>ERR_INVALID_FD</code><span><a class="mark" href="#errors_err_invalid_fd" id="errors_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><code>ERR_INVALID_FD_TYPE</code><span><a class="mark" href="#errors_err_invalid_fd_type" id="errors_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><code>ERR_INVALID_FILE_URL_HOST</code><span><a class="mark" href="#errors_err_invalid_file_url_host" id="errors_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><code>ERR_INVALID_FILE_URL_PATH</code><span><a class="mark" href="#errors_err_invalid_file_url_path" id="errors_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><code>ERR_INVALID_HANDLE_TYPE</code><span><a class="mark" href="#errors_err_invalid_handle_type" id="errors_err_invalid_handle_type">#</a></span></h3>
<p>An attempt was made to send an unsupported "handle" over an IPC communication
channel to a child process. See <a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>subprocess.send()</code></a> and <a href="#process_process_send_message_sendhandle_options_callback"><code>process.send()</code></a>
for more information.</p>
<p><a id="ERR_INVALID_HTTP_TOKEN"></a></p>
<h3><code>ERR_INVALID_HTTP_TOKEN</code><span><a class="mark" href="#errors_err_invalid_http_token" id="errors_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><code>ERR_INVALID_IP_ADDRESS</code><span><a class="mark" href="#errors_err_invalid_ip_address" id="errors_err_invalid_ip_address">#</a></span></h3>
<p>An IP address is not valid.</p>
<p><a id="ERR_INVALID_MODULE_SPECIFIER"></a></p>
<h3><code>ERR_INVALID_MODULE_SPECIFIER</code><span><a class="mark" href="#errors_err_invalid_module_specifier" id="errors_err_invalid_module_specifier">#</a></span></h3>
<p>The imported module string is an invalid URL, package name, or package subpath
specifier.</p>
<p><a id="ERR_INVALID_OPT_VALUE"></a></p>
<h3><code>ERR_INVALID_OPT_VALUE</code><span><a class="mark" href="#errors_err_invalid_opt_value" id="errors_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><code>ERR_INVALID_OPT_VALUE_ENCODING</code><span><a class="mark" href="#errors_err_invalid_opt_value_encoding" id="errors_err_invalid_opt_value_encoding">#</a></span></h3>
<p>An invalid or unknown file encoding was passed.</p>
<p><a id="ERR_INVALID_PACKAGE_CONFIG"></a></p>
<h3><code>ERR_INVALID_PACKAGE_CONFIG</code><span><a class="mark" href="#errors_err_invalid_package_config" id="errors_err_invalid_package_config">#</a></span></h3>
<p>An invalid <code>package.json</code> file was found which failed parsing.</p>
<p><a id="ERR_INVALID_PACKAGE_TARGET"></a></p>
<h3><code>ERR_INVALID_PACKAGE_TARGET</code><span><a class="mark" href="#errors_err_invalid_package_target" id="errors_err_invalid_package_target">#</a></span></h3>
<p>The <code>package.json</code> <a href="#esm_package_entry_points">exports</a> field contains an invalid target mapping value
for the attempted module resolution.</p>
<p><a id="ERR_INVALID_PERFORMANCE_MARK"></a></p>
<h3><code>ERR_INVALID_PERFORMANCE_MARK</code><span><a class="mark" href="#errors_err_invalid_performance_mark" id="errors_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><code>ERR_INVALID_PROTOCOL</code><span><a class="mark" href="#errors_err_invalid_protocol" id="errors_err_invalid_protocol">#</a></span></h3>
<p>An invalid <code>options.protocol</code> was passed to <code>http.request()</code>.</p>
<p><a id="ERR_INVALID_REPL_EVAL_CONFIG"></a></p>
<h3><code>ERR_INVALID_REPL_EVAL_CONFIG</code><span><a class="mark" href="#errors_err_invalid_repl_eval_config" id="errors_err_invalid_repl_eval_config">#</a></span></h3>
<p>Both <code>breakEvalOnSigint</code> and <code>eval</code> options were set in the <a href="repl.html"><code>REPL</code></a> config,
which is not supported.</p>
<p><a id="ERR_INVALID_REPL_INPUT"></a></p>
<h3><code>ERR_INVALID_REPL_INPUT</code><span><a class="mark" href="#errors_err_invalid_repl_input" id="errors_err_invalid_repl_input">#</a></span></h3>
<p>The input may not be used in the <a href="repl.html"><code>REPL</code></a>. All prohibited inputs are
documented in the <a href="repl.html"><code>REPL</code></a>'s documentation.</p>
<p><a id="ERR_INVALID_RETURN_PROPERTY"></a></p>
<h3><code>ERR_INVALID_RETURN_PROPERTY</code><span><a class="mark" href="#errors_err_invalid_return_property" id="errors_err_invalid_return_property">#</a></span></h3>
<p>Thrown in case a function option does not provide a valid value for one of its
returned object properties on execution.</p>
<p><a id="ERR_INVALID_RETURN_PROPERTY_VALUE"></a></p>
<h3><code>ERR_INVALID_RETURN_PROPERTY_VALUE</code><span><a class="mark" href="#errors_err_invalid_return_property_value" id="errors_err_invalid_return_property_value">#</a></span></h3>
<p>Thrown in case a function option does not provide an expected value
type for one of its returned object properties on execution.</p>
<p><a id="ERR_INVALID_RETURN_VALUE"></a></p>
<h3><code>ERR_INVALID_RETURN_VALUE</code><span><a class="mark" href="#errors_err_invalid_return_value" id="errors_err_invalid_return_value">#</a></span></h3>
<p>Thrown in case a function option does not return an expected value
type on execution, such as when a function is expected to return a promise.</p>
<p><a id="ERR_INVALID_SYNC_FORK_INPUT"></a></p>
<h3><code>ERR_INVALID_SYNC_FORK_INPUT</code><span><a class="mark" href="#errors_err_invalid_sync_fork_input" id="errors_err_invalid_sync_fork_input">#</a></span></h3>
<p>A <code>Buffer</code>, <code>TypedArray</code>, <code>DataView</code> or <code>string</code> was provided as stdio input to
an asynchronous fork. See the documentation for the <a href="child_process.html"><code>child_process</code></a> module
for more information.</p>
<p><a id="ERR_INVALID_THIS"></a></p>
<h3><code>ERR_INVALID_THIS</code><span><a class="mark" href="#errors_err_invalid_this" id="errors_err_invalid_this">#</a></span></h3>
<p>A Node.js API function was called with an incompatible <code>this</code> value.</p>
<pre><code class="language-js">const urlSearchParams = new URLSearchParams('foo=bar&#x26;baz=new');

const buf = Buffer.alloc(1);
urlSearchParams.has.call(buf, 'foo');
// Throws a TypeError with code 'ERR_INVALID_THIS'
</code></pre>
<p><a id="ERR_INVALID_TRANSFER_OBJECT"></a></p>
<h3><code>ERR_INVALID_TRANSFER_OBJECT</code><span><a class="mark" href="#errors_err_invalid_transfer_object" id="errors_err_invalid_transfer_object">#</a></span></h3>
<p>An invalid transfer object was passed to <code>postMessage()</code>.</p>
<p><a id="ERR_INVALID_TUPLE"></a></p>
<h3><code>ERR_INVALID_TUPLE</code><span><a class="mark" href="#errors_err_invalid_tuple" id="errors_err_invalid_tuple">#</a></span></h3>
<p>An element in the <code>iterable</code> provided to the <a href="#url_the_whatwg_url_api">WHATWG</a>
<a href="#url_constructor_new_urlsearchparams_iterable"><code>URLSearchParams</code> constructor</a> did not
represent a <code>[name, value]</code> tuple – that is, if an element is not iterable, or
does not consist of exactly two elements.</p>
<p><a id="ERR_INVALID_URI"></a></p>
<h3><code>ERR_INVALID_URI</code><span><a class="mark" href="#errors_err_invalid_uri" id="errors_err_invalid_uri">#</a></span></h3>
<p>An invalid URI was passed.</p>
<p><a id="ERR_INVALID_URL"></a></p>
<h3><code>ERR_INVALID_URL</code><span><a class="mark" href="#errors_err_invalid_url" id="errors_err_invalid_url">#</a></span></h3>
<p>An invalid URL was passed to the <a href="#url_the_whatwg_url_api">WHATWG</a>
<a href="#url_constructor_new_url_input_base"><code>URL</code> constructor</a> to be parsed. The thrown error object
typically has an additional property <code>'input'</code> that contains the URL that failed
to parse.</p>
<p><a id="ERR_INVALID_URL_SCHEME"></a></p>
<h3><code>ERR_INVALID_URL_SCHEME</code><span><a class="mark" href="#errors_err_invalid_url_scheme" id="errors_err_invalid_url_scheme">#</a></span></h3>
<p>An attempt was made to use a URL of an incompatible scheme (protocol) for a
specific purpose. It is only used in the <a href="#url_the_whatwg_url_api">WHATWG URL API</a> support in the
<a href="fs.html"><code>fs</code></a> module (which only accepts URLs with <code>'file'</code> scheme), but may be used
in other Node.js APIs as well in the future.</p>
<p><a id="ERR_IPC_CHANNEL_CLOSED"></a></p>
<h3><code>ERR_IPC_CHANNEL_CLOSED</code><span><a class="mark" href="#errors_err_ipc_channel_closed" id="errors_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><code>ERR_IPC_DISCONNECTED</code><span><a class="mark" href="#errors_err_ipc_disconnected" id="errors_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><code>ERR_IPC_ONE_PIPE</code><span><a class="mark" href="#errors_err_ipc_one_pipe" id="errors_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><code>ERR_IPC_SYNC_FORK</code><span><a class="mark" href="#errors_err_ipc_sync_fork" id="errors_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_MANIFEST_ASSERT_INTEGRITY"></a></p>
<h3><code>ERR_MANIFEST_ASSERT_INTEGRITY</code><span><a class="mark" href="#errors_err_manifest_assert_integrity" id="errors_err_manifest_assert_integrity">#</a></span></h3>
<p>An attempt was made to load a resource, but the resource did not match the
integrity defined by the policy manifest. See the documentation for <a href="policy.html">policy</a>
manifests for more information.</p>
<p><a id="ERR_MANIFEST_DEPENDENCY_MISSING"></a></p>
<h3><code>ERR_MANIFEST_DEPENDENCY_MISSING</code><span><a class="mark" href="#errors_err_manifest_dependency_missing" id="errors_err_manifest_dependency_missing">#</a></span></h3>
<p>An attempt was made to load a resource, but the resource was not listed as a
dependency from the location that attempted to load it. See the documentation
for <a href="policy.html">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_INTEGRITY_MISMATCH"></a></p>
<h3><code>ERR_MANIFEST_INTEGRITY_MISMATCH</code><span><a class="mark" href="#errors_err_manifest_integrity_mismatch" id="errors_err_manifest_integrity_mismatch">#</a></span></h3>
<p>An attempt was made to load a policy manifest, but the manifest had multiple
entries for a resource which did not match each other. Update the manifest
entries to match in order to resolve this error. See the documentation for
<a href="policy.html">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_INVALID_RESOURCE_FIELD"></a></p>
<h3><code>ERR_MANIFEST_INVALID_RESOURCE_FIELD</code><span><a class="mark" href="#errors_err_manifest_invalid_resource_field" id="errors_err_manifest_invalid_resource_field">#</a></span></h3>
<p>A policy manifest resource had an invalid value for one of its fields. Update
the manifest entry to match in order to resolve this error. See the
documentation for <a href="policy.html">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_PARSE_POLICY"></a></p>
<h3><code>ERR_MANIFEST_PARSE_POLICY</code><span><a class="mark" href="#errors_err_manifest_parse_policy" id="errors_err_manifest_parse_policy">#</a></span></h3>
<p>An attempt was made to load a policy manifest, but the manifest was unable to
be parsed. See the documentation for <a href="policy.html">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_TDZ"></a></p>
<h3><code>ERR_MANIFEST_TDZ</code><span><a class="mark" href="#errors_err_manifest_tdz" id="errors_err_manifest_tdz">#</a></span></h3>
<p>An attempt was made to read from a policy manifest, but the manifest
initialization has not yet taken place. This is likely a bug in Node.js.</p>
<p><a id="ERR_MANIFEST_UNKNOWN_ONERROR"></a></p>
<h3><code>ERR_MANIFEST_UNKNOWN_ONERROR</code><span><a class="mark" href="#errors_err_manifest_unknown_onerror" id="errors_err_manifest_unknown_onerror">#</a></span></h3>
<p>A policy manifest was loaded, but had an unknown value for its "onerror"
behavior. See the documentation for <a href="policy.html">policy</a> manifests for more information.</p>
<p><a id="ERR_MEMORY_ALLOCATION_FAILED"></a></p>
<h3><code>ERR_MEMORY_ALLOCATION_FAILED</code><span><a class="mark" href="#errors_err_memory_allocation_failed" id="errors_err_memory_allocation_failed">#</a></span></h3>
<p>An attempt was made to allocate memory (usually in the C++ layer) but it
failed.</p>
<p><a id="ERR_METHOD_NOT_IMPLEMENTED"></a></p>
<h3><code>ERR_METHOD_NOT_IMPLEMENTED</code><span><a class="mark" href="#errors_err_method_not_implemented" id="errors_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><code>ERR_MISSING_ARGS</code><span><a class="mark" href="#errors_err_missing_args" id="errors_err_missing_args">#</a></span></h3>
<p>A required argument of a Node.js API was not passed. This is only used for
strict compliance with the API specification (which in some cases may accept
<code>func(undefined)</code> but not <code>func()</code>). In most native Node.js APIs,
<code>func(undefined)</code> and <code>func()</code> are treated identically, and the
<a href="#ERR_INVALID_ARG_TYPE"><code>ERR_INVALID_ARG_TYPE</code></a> error code may be used instead.</p>
<p><a id="ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK"></a></p>
<h3><code>ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK</code><span><a class="mark" href="#errors_err_missing_dynamic_instantiate_hook" id="errors_err_missing_dynamic_instantiate_hook">#</a></span></h3>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>An <a href="esm.html">ES Module</a> loader hook specified <code>format: 'dynamic'</code> but did not provide
a <code>dynamicInstantiate</code> hook.</p>
<p><a id="ERR_MISSING_OPTION"></a></p>
<h3><code>ERR_MISSING_OPTION</code><span><a class="mark" href="#errors_err_missing_option" id="errors_err_missing_option">#</a></span></h3>
<p>For APIs that accept options objects, some options might be mandatory. This code
is thrown if a required option is missing.</p>
<p><a id="ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST"></a></p>
<h3><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code><span><a class="mark" href="#errors_err_missing_message_port_in_transfer_list" id="errors_err_missing_message_port_in_transfer_list">#</a></span></h3>
<p>A <code>MessagePort</code> was found in the object passed to a <code>postMessage()</code> call,
but not provided in the <code>transferList</code> for that call.</p>
<p><a id="ERR_MISSING_PASSPHRASE"></a></p>
<h3><code>ERR_MISSING_PASSPHRASE</code><span><a class="mark" href="#errors_err_missing_passphrase" id="errors_err_missing_passphrase">#</a></span></h3>
<p>An attempt was made to read an encrypted key without specifying a passphrase.</p>
<p><a id="ERR_MISSING_PLATFORM_FOR_WORKER"></a></p>
<h3><code>ERR_MISSING_PLATFORM_FOR_WORKER</code><span><a class="mark" href="#errors_err_missing_platform_for_worker" id="errors_err_missing_platform_for_worker">#</a></span></h3>
<p>The V8 platform used by this instance of Node.js does not support creating
Workers. This is caused by lack of embedder support for Workers. In particular,
this error will not occur with standard builds of Node.js.</p>
<p><a id="ERR_MODULE_NOT_FOUND"></a></p>
<h3><code>ERR_MODULE_NOT_FOUND</code><span><a class="mark" href="#errors_err_module_not_found" id="errors_err_module_not_found">#</a></span></h3>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>An <a href="esm.html">ES Module</a> could not be resolved.</p>
<p><a id="ERR_MULTIPLE_CALLBACK"></a></p>
<h3><code>ERR_MULTIPLE_CALLBACK</code><span><a class="mark" href="#errors_err_multiple_callback" id="errors_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><code>ERR_NAPI_CONS_FUNCTION</code><span><a class="mark" href="#errors_err_napi_cons_function" id="errors_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><code>ERR_NAPI_INVALID_DATAVIEW_ARGS</code><span><a class="mark" href="#errors_err_napi_invalid_dataview_args" id="errors_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><code>ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT</code><span><a class="mark" href="#errors_err_napi_invalid_typedarray_alignment" id="errors_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><code>ERR_NAPI_INVALID_TYPEDARRAY_LENGTH</code><span><a class="mark" href="#errors_err_napi_invalid_typedarray_length" id="errors_err_napi_invalid_typedarray_length">#</a></span></h3>
<p>While calling <code>napi_create_typedarray()</code>, <code>(length * size_of_element) + byte_offset</code> was larger than the length of given <code>buffer</code>.</p>
<p><a id="ERR_NAPI_TSFN_CALL_JS"></a></p>
<h3><code>ERR_NAPI_TSFN_CALL_JS</code><span><a class="mark" href="#errors_err_napi_tsfn_call_js" id="errors_err_napi_tsfn_call_js">#</a></span></h3>
<p>An error occurred while invoking the JavaScript portion of the thread-safe
function.</p>
<p><a id="ERR_NAPI_TSFN_GET_UNDEFINED"></a></p>
<h3><code>ERR_NAPI_TSFN_GET_UNDEFINED</code><span><a class="mark" href="#errors_err_napi_tsfn_get_undefined" id="errors_err_napi_tsfn_get_undefined">#</a></span></h3>
<p>An error occurred while attempting to retrieve the JavaScript <code>undefined</code>
value.</p>
<p><a id="ERR_NAPI_TSFN_START_IDLE_LOOP"></a></p>
<h3><code>ERR_NAPI_TSFN_START_IDLE_LOOP</code><span><a class="mark" href="#errors_err_napi_tsfn_start_idle_loop" id="errors_err_napi_tsfn_start_idle_loop">#</a></span></h3>
<p>On the main thread, values are removed from the queue associated with the
thread-safe function in an idle loop. This error indicates that an error
has occurred when attempting to start the loop.</p>
<p><a id="ERR_NAPI_TSFN_STOP_IDLE_LOOP"></a></p>
<h3><code>ERR_NAPI_TSFN_STOP_IDLE_LOOP</code><span><a class="mark" href="#errors_err_napi_tsfn_stop_idle_loop" id="errors_err_napi_tsfn_stop_idle_loop">#</a></span></h3>
<p>Once no more items are left in the queue, the idle loop must be suspended. This
error indicates that the idle loop has failed to stop.</p>
<p><a id="ERR_NO_CRYPTO"></a></p>
<h3><code>ERR_NO_CRYPTO</code><span><a class="mark" href="#errors_err_no_crypto" id="errors_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><code>ERR_NO_ICU</code><span><a class="mark" href="#errors_err_no_icu" id="errors_err_no_icu">#</a></span></h3>
<p>An attempt was made to use features that require <a href="#intl_internationalization_support">ICU</a>, but Node.js was not
compiled with ICU support.</p>
<p><a id="ERR_NON_CONTEXT_AWARE_DISABLED"></a></p>
<h3><code>ERR_NON_CONTEXT_AWARE_DISABLED</code><span><a class="mark" href="#errors_err_non_context_aware_disabled" id="errors_err_non_context_aware_disabled">#</a></span></h3>
<p>A non-context-aware native addon was loaded in a process that disallows them.</p>
<p><a id="ERR_OUT_OF_RANGE"></a></p>
<h3><code>ERR_OUT_OF_RANGE</code><span><a class="mark" href="#errors_err_out_of_range" id="errors_err_out_of_range">#</a></span></h3>
<p>A given value is out of the accepted range.</p>
<p><a id="ERR_PACKAGE_PATH_NOT_EXPORTED"></a></p>
<h3><code>ERR_PACKAGE_PATH_NOT_EXPORTED</code><span><a class="mark" href="#errors_err_package_path_not_exported" id="errors_err_package_path_not_exported">#</a></span></h3>
<p>The <code>package.json</code> <a href="#esm_package_entry_points">exports</a> field does not export the requested subpath.
Because exports are encapsulated, private internal modules that are not exported
cannot be imported through the package resolution, unless using an absolute URL.</p>
<p><a id="ERR_PROTO_ACCESS"></a></p>
<h3><code>ERR_PROTO_ACCESS</code><span><a class="mark" href="#errors_err_proto_access" id="errors_err_proto_access">#</a></span></h3>
<p>Accessing <code>Object.prototype.__proto__</code> has been forbidden using
<a href="#cli_disable_proto_mode"><code>--disable-proto=throw</code></a>. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf"><code>Object.getPrototypeOf</code></a> and
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf"><code>Object.setPrototypeOf</code></a> should be used to get and set the prototype of an
object.</p>
<p><a id="ERR_REQUIRE_ESM"></a></p>
<h3><code>ERR_REQUIRE_ESM</code><span><a class="mark" href="#errors_err_require_esm" id="errors_err_require_esm">#</a></span></h3>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>An attempt was made to <code>require()</code> an <a href="esm.html">ES Module</a>.</p>
<p><a id="ERR_SCRIPT_EXECUTION_INTERRUPTED"></a></p>
<h3><code>ERR_SCRIPT_EXECUTION_INTERRUPTED</code><span><a class="mark" href="#errors_err_script_execution_interrupted" id="errors_err_script_execution_interrupted">#</a></span></h3>
<p>Script execution was interrupted by <code>SIGINT</code> (For example, when Ctrl+C was
pressed).</p>
<p><a id="ERR_SCRIPT_EXECUTION_TIMEOUT"></a></p>
<h3><code>ERR_SCRIPT_EXECUTION_TIMEOUT</code><span><a class="mark" href="#errors_err_script_execution_timeout" id="errors_err_script_execution_timeout">#</a></span></h3>
<p>Script execution timed out, possibly due to bugs in the script being executed.</p>
<p><a id="ERR_SERVER_ALREADY_LISTEN"></a></p>
<h3><code>ERR_SERVER_ALREADY_LISTEN</code><span><a class="mark" href="#errors_err_server_already_listen" id="errors_err_server_already_listen">#</a></span></h3>
<p>The <a href="#net_server_listen"><code>server.listen()</code></a> method was called while a <code>net.Server</code> was already
listening. This applies to all instances of <code>net.Server</code>, including HTTP, HTTPS,
and HTTP/2 <code>Server</code> instances.</p>
<p><a id="ERR_SERVER_NOT_RUNNING"></a></p>
<h3><code>ERR_SERVER_NOT_RUNNING</code><span><a class="mark" href="#errors_err_server_not_running" id="errors_err_server_not_running">#</a></span></h3>
<p>The <a href="#net_server_close_callback"><code>server.close()</code></a> method was called when a <code>net.Server</code> was not
running. This applies to all instances of <code>net.Server</code>, including HTTP, HTTPS,
and HTTP/2 <code>Server</code> instances.</p>
<p><a id="ERR_SOCKET_ALREADY_BOUND"></a></p>
<h3><code>ERR_SOCKET_ALREADY_BOUND</code><span><a class="mark" href="#errors_err_socket_already_bound" id="errors_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><code>ERR_SOCKET_BAD_BUFFER_SIZE</code><span><a class="mark" href="#errors_err_socket_bad_buffer_size" id="errors_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><code>ERR_SOCKET_BAD_PORT</code><span><a class="mark" href="#errors_err_socket_bad_port" id="errors_err_socket_bad_port">#</a></span></h3>
<p>An API function expecting a port >= 0 and &#x3C; 65536 received an invalid value.</p>
<p><a id="ERR_SOCKET_BAD_TYPE"></a></p>
<h3><code>ERR_SOCKET_BAD_TYPE</code><span><a class="mark" href="#errors_err_socket_bad_type" id="errors_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><code>ERR_SOCKET_BUFFER_SIZE</code><span><a class="mark" href="#errors_err_socket_buffer_size" id="errors_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><code>ERR_SOCKET_CANNOT_SEND</code><span><a class="mark" href="#errors_err_socket_cannot_send" id="errors_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><code>ERR_SOCKET_CLOSED</code><span><a class="mark" href="#errors_err_socket_closed" id="errors_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_IS_CONNECTED"></a></p>
<h3><code>ERR_SOCKET_DGRAM_IS_CONNECTED</code><span><a class="mark" href="#errors_err_socket_dgram_is_connected" id="errors_err_socket_dgram_is_connected">#</a></span></h3>
<p>A <a href="#dgram_socket_connect_port_address_callback"><code>dgram.connect()</code></a> call was made on an already connected socket.</p>
<p><a id="ERR_SOCKET_DGRAM_NOT_CONNECTED"></a></p>
<h3><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code><span><a class="mark" href="#errors_err_socket_dgram_not_connected" id="errors_err_socket_dgram_not_connected">#</a></span></h3>
<p>A <a href="#dgram_socket_disconnect"><code>dgram.disconnect()</code></a> or <a href="#dgram_socket_remoteaddress"><code>dgram.remoteAddress()</code></a> call was made on a
disconnected socket.</p>
<p><a id="ERR_SOCKET_DGRAM_NOT_RUNNING"></a></p>
<h3><code>ERR_SOCKET_DGRAM_NOT_RUNNING</code><span><a class="mark" href="#errors_err_socket_dgram_not_running" id="errors_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_SRI_PARSE"></a></p>
<h3><code>ERR_SRI_PARSE</code><span><a class="mark" href="#errors_err_sri_parse" id="errors_err_sri_parse">#</a></span></h3>
<p>A string was provided for a Subresource Integrity check, but was unable to be
parsed. Check the format of integrity attributes by looking at the
<a href="https://www.w3.org/TR/SRI/#the-integrity-attribute">Subresource Integrity specification</a>.</p>
<p><a id="ERR_STREAM_CANNOT_PIPE"></a></p>
<h3><code>ERR_STREAM_CANNOT_PIPE</code><span><a class="mark" href="#errors_err_stream_cannot_pipe" id="errors_err_stream_cannot_pipe">#</a></span></h3>
<p>An attempt was made to call <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> on a <a href="#stream_class_stream_writable"><code>Writable</code></a> stream.</p>
<p><a id="ERR_STREAM_DESTROYED"></a></p>
<h3><code>ERR_STREAM_DESTROYED</code><span><a class="mark" href="#errors_err_stream_destroyed" id="errors_err_stream_destroyed">#</a></span></h3>
<p>A stream method was called that cannot complete because the stream was
destroyed using <code>stream.destroy()</code>.</p>
<p><a id="ERR_STREAM_NULL_VALUES"></a></p>
<h3><code>ERR_STREAM_NULL_VALUES</code><span><a class="mark" href="#errors_err_stream_null_values" id="errors_err_stream_null_values">#</a></span></h3>
<p>An attempt was made to call <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> with a <code>null</code> chunk.</p>
<p><a id="ERR_STREAM_PREMATURE_CLOSE"></a></p>
<h3><code>ERR_STREAM_PREMATURE_CLOSE</code><span><a class="mark" href="#errors_err_stream_premature_close" id="errors_err_stream_premature_close">#</a></span></h3>
<p>An error returned by <code>stream.finished()</code> and <code>stream.pipeline()</code>, when a stream
or a pipeline ends non gracefully with no explicit error.</p>
<p><a id="ERR_STREAM_PUSH_AFTER_EOF"></a></p>
<h3><code>ERR_STREAM_PUSH_AFTER_EOF</code><span><a class="mark" href="#errors_err_stream_push_after_eof" id="errors_err_stream_push_after_eof">#</a></span></h3>
<p>An attempt was made to call <a href="#stream_readable_push_chunk_encoding"><code>stream.push()</code></a> after a <code>null</code>(EOF) had been
pushed to the stream.</p>
<p><a id="ERR_STREAM_UNSHIFT_AFTER_END_EVENT"></a></p>
<h3><code>ERR_STREAM_UNSHIFT_AFTER_END_EVENT</code><span><a class="mark" href="#errors_err_stream_unshift_after_end_event" id="errors_err_stream_unshift_after_end_event">#</a></span></h3>
<p>An attempt was made to call <a href="#stream_readable_unshift_chunk_encoding"><code>stream.unshift()</code></a> after the <code>'end'</code> event was
emitted.</p>
<p><a id="ERR_STREAM_WRAP"></a></p>
<h3><code>ERR_STREAM_WRAP</code><span><a class="mark" href="#errors_err_stream_wrap" id="errors_err_stream_wrap">#</a></span></h3>
<p>Prevents an abort if a string decoder was set on the Socket or if the decoder
is in <code>objectMode</code>.</p>
<pre><code class="language-js">const Socket = require('net').Socket;
const instance = new Socket();

instance.setEncoding('utf8');
</code></pre>
<p><a id="ERR_STREAM_WRITE_AFTER_END"></a></p>
<h3><code>ERR_STREAM_WRITE_AFTER_END</code><span><a class="mark" href="#errors_err_stream_write_after_end" id="errors_err_stream_write_after_end">#</a></span></h3>
<p>An attempt was made to call <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> after <code>stream.end()</code> has been
called.</p>
<p><a id="ERR_STRING_TOO_LONG"></a></p>
<h3><code>ERR_STRING_TOO_LONG</code><span><a class="mark" href="#errors_err_string_too_long" id="errors_err_string_too_long">#</a></span></h3>
<p>An attempt has been made to create a string longer than the maximum allowed
length.</p>
<p><a id="ERR_SYNTHETIC"></a></p>
<h3><code>ERR_SYNTHETIC</code><span><a class="mark" href="#errors_err_synthetic" id="errors_err_synthetic">#</a></span></h3>
<p>An artificial error object used to capture the call stack for diagnostic
reports.</p>
<p><a id="ERR_SYSTEM_ERROR"></a></p>
<h3><code>ERR_SYSTEM_ERROR</code><span><a class="mark" href="#errors_err_system_error" id="errors_err_system_error">#</a></span></h3>
<p>An unspecified or non-specific system error has occurred within the Node.js
process. The error object will have an <code>err.info</code> object property with
additional details.</p>
<p><a id="ERR_TLS_CERT_ALTNAME_INVALID"></a></p>
<h3><code>ERR_TLS_CERT_ALTNAME_INVALID</code><span><a class="mark" href="#errors_err_tls_cert_altname_invalid" id="errors_err_tls_cert_altname_invalid">#</a></span></h3>
<p>While using TLS, the host name/IP of the peer did not match any of the
<code>subjectAltNames</code> in its certificate.</p>
<p><a id="ERR_TLS_DH_PARAM_SIZE"></a></p>
<h3><code>ERR_TLS_DH_PARAM_SIZE</code><span><a class="mark" href="#errors_err_tls_dh_param_size" id="errors_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><code>ERR_TLS_HANDSHAKE_TIMEOUT</code><span><a class="mark" href="#errors_err_tls_handshake_timeout" id="errors_err_tls_handshake_timeout">#</a></span></h3>
<p>A TLS/SSL handshake timed out. In this case, the server must also abort the
connection.</p>
<p><a id="ERR_TLS_INVALID_CONTEXT"></a></p>
<h3><code>ERR_TLS_INVALID_CONTEXT</code><span><a class="mark" href="#errors_err_tls_invalid_context" id="errors_err_tls_invalid_context">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p>The context must be a <code>SecureContext</code>.</p>
<p><a id="ERR_TLS_INVALID_STATE"></a></p>
<h3><code>ERR_TLS_INVALID_STATE</code><span><a class="mark" href="#errors_err_tls_invalid_state" id="errors_err_tls_invalid_state">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<p>The TLS socket must be connected and securily established. Ensure the 'secure'
event is emitted before continuing.</p>
<p><a id="ERR_TLS_INVALID_PROTOCOL_METHOD"></a></p>
<h3><code>ERR_TLS_INVALID_PROTOCOL_METHOD</code><span><a class="mark" href="#errors_err_tls_invalid_protocol_method" id="errors_err_tls_invalid_protocol_method">#</a></span></h3>
<p>The specified  <code>secureProtocol</code> method is invalid. It is  either unknown, or
disabled because it is insecure.</p>
<p><a id="ERR_TLS_INVALID_PROTOCOL_VERSION"></a></p>
<h3><code>ERR_TLS_INVALID_PROTOCOL_VERSION</code><span><a class="mark" href="#errors_err_tls_invalid_protocol_version" id="errors_err_tls_invalid_protocol_version">#</a></span></h3>
<p>Valid TLS protocol versions are <code>'TLSv1'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1.2'</code>.</p>
<p><a id="ERR_TLS_PROTOCOL_VERSION_CONFLICT"></a></p>
<h3><code>ERR_TLS_PROTOCOL_VERSION_CONFLICT</code><span><a class="mark" href="#errors_err_tls_protocol_version_conflict" id="errors_err_tls_protocol_version_conflict">#</a></span></h3>
<p>Attempting to set a TLS protocol <code>minVersion</code> or <code>maxVersion</code> conflicts with an
attempt to set the <code>secureProtocol</code> explicitly. Use one mechanism or the other.</p>
<p><a id="ERR_TLS_RENEGOTIATION_DISABLED"></a></p>
<h3><code>ERR_TLS_RENEGOTIATION_DISABLED</code><span><a class="mark" href="#errors_err_tls_renegotiation_disabled" id="errors_err_tls_renegotiation_disabled">#</a></span></h3>
<p>An attempt was made to renegotiate TLS on a socket instance with TLS disabled.</p>
<p><a id="ERR_TLS_REQUIRED_SERVER_NAME"></a></p>
<h3><code>ERR_TLS_REQUIRED_SERVER_NAME</code><span><a class="mark" href="#errors_err_tls_required_server_name" id="errors_err_tls_required_server_name">#</a></span></h3>
<p>While using TLS, the <code>server.addContext()</code> method was called without providing
a host name in the first parameter.</p>
<p><a id="ERR_TLS_SESSION_ATTACK"></a></p>
<h3><code>ERR_TLS_SESSION_ATTACK</code><span><a class="mark" href="#errors_err_tls_session_attack" id="errors_err_tls_session_attack">#</a></span></h3>
<p>An excessive amount of TLS renegotiations is detected, which is a potential
vector for denial-of-service attacks.</p>
<p><a id="ERR_TLS_SNI_FROM_SERVER"></a></p>
<h3><code>ERR_TLS_SNI_FROM_SERVER</code><span><a class="mark" href="#errors_err_tls_sni_from_server" id="errors_err_tls_sni_from_server">#</a></span></h3>
<p>An attempt was made to issue Server Name Indication from a TLS server-side
socket, which is only valid from a client.</p>
<p><a id="ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED"></a></p>
<h3>ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED<span><a class="mark" href="#errors_err_tls_psk_set_identiy_hint_failed" id="errors_err_tls_psk_set_identiy_hint_failed">#</a></span><span><a class="mark" href="#ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED" id="ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED">#</a></span></h3>
<p>Failed to set PSK identity hint. Hint may be too long.</p>
<p><a id="ERR_TRACE_EVENTS_CATEGORY_REQUIRED"></a></p>
<h3><code>ERR_TRACE_EVENTS_CATEGORY_REQUIRED</code><span><a class="mark" href="#errors_err_trace_events_category_required" id="errors_err_trace_events_category_required">#</a></span></h3>
<p>The <code>trace_events.createTracing()</code> method requires at least one trace event
category.</p>
<p><a id="ERR_TRACE_EVENTS_UNAVAILABLE"></a></p>
<h3><code>ERR_TRACE_EVENTS_UNAVAILABLE</code><span><a class="mark" href="#errors_err_trace_events_unavailable" id="errors_err_trace_events_unavailable">#</a></span></h3>
<p>The <code>trace_events</code> module could not be loaded because Node.js was compiled with
the <code>--without-v8-platform</code> flag.</p>
<p><a id="ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER"></a></p>
<h3><code>ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER</code><span><a class="mark" href="#errors_err_transferring_externalized_sharedarraybuffer" id="errors_err_transferring_externalized_sharedarraybuffer">#</a></span></h3>
<p>A <code>SharedArrayBuffer</code> whose memory is not managed by the JavaScript engine
or by Node.js was encountered during serialization. Such a <code>SharedArrayBuffer</code>
cannot be serialized.</p>
<p>This can only happen when native addons create <code>SharedArrayBuffer</code>s in
"externalized" mode, or put existing <code>SharedArrayBuffer</code> into externalized mode.</p>
<p><a id="ERR_TRANSFORM_ALREADY_TRANSFORMING"></a></p>
<h3><code>ERR_TRANSFORM_ALREADY_TRANSFORMING</code><span><a class="mark" href="#errors_err_transform_already_transforming" id="errors_err_transform_already_transforming">#</a></span></h3>
<p>A <code>Transform</code> stream finished while it was still transforming.</p>
<p><a id="ERR_TRANSFORM_WITH_LENGTH_0"></a></p>
<h3><code>ERR_TRANSFORM_WITH_LENGTH_0</code><span><a class="mark" href="#errors_err_transform_with_length_0" id="errors_err_transform_with_length_0">#</a></span></h3>
<p>A <code>Transform</code> stream finished with data still in the write buffer.</p>
<p><a id="ERR_TTY_INIT_FAILED"></a></p>
<h3><code>ERR_TTY_INIT_FAILED</code><span><a class="mark" href="#errors_err_tty_init_failed" id="errors_err_tty_init_failed">#</a></span></h3>
<p>The initialization of a TTY failed due to a system error.</p>
<p><a id="ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET"></a></p>
<h3><code>ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET</code><span><a class="mark" href="#errors_err_uncaught_exception_capture_already_set" id="errors_err_uncaught_exception_capture_already_set">#</a></span></h3>
<p><a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> was called twice,
without first resetting the callback to <code>null</code>.</p>
<p>This error is designed to prevent accidentally overwriting a callback registered
from another module.</p>
<p><a id="ERR_UNESCAPED_CHARACTERS"></a></p>
<h3><code>ERR_UNESCAPED_CHARACTERS</code><span><a class="mark" href="#errors_err_unescaped_characters" id="errors_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><code>ERR_UNHANDLED_ERROR</code><span><a class="mark" href="#errors_err_unhandled_error" id="errors_err_unhandled_error">#</a></span></h3>
<p>An unhandled error occurred (for instance, when an <code>'error'</code> event is emitted
by an <a href="#events_class_eventemitter"><code>EventEmitter</code></a> but an <code>'error'</code> handler is not registered).</p>
<p><a id="ERR_UNKNOWN_BUILTIN_MODULE"></a></p>
<h3><code>ERR_UNKNOWN_BUILTIN_MODULE</code><span><a class="mark" href="#errors_err_unknown_builtin_module" id="errors_err_unknown_builtin_module">#</a></span></h3>
<p>Used to identify a specific kind of internal Node.js error that should not
typically be triggered by user code. Instances of this error point to an
internal bug within the Node.js binary itself.</p>
<p><a id="ERR_UNKNOWN_CREDENTIAL"></a></p>
<h3><code>ERR_UNKNOWN_CREDENTIAL</code><span><a class="mark" href="#errors_err_unknown_credential" id="errors_err_unknown_credential">#</a></span></h3>
<p>A Unix group or user identifier that does not exist was passed.</p>
<p><a id="ERR_UNKNOWN_ENCODING"></a></p>
<h3><code>ERR_UNKNOWN_ENCODING</code><span><a class="mark" href="#errors_err_unknown_encoding" id="errors_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><code>ERR_UNKNOWN_FILE_EXTENSION</code><span><a class="mark" href="#errors_err_unknown_file_extension" id="errors_err_unknown_file_extension">#</a></span></h3>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>An attempt was made to load a module with an unknown or unsupported file
extension.</p>
<p><a id="ERR_UNKNOWN_MODULE_FORMAT"></a></p>
<h3><code>ERR_UNKNOWN_MODULE_FORMAT</code><span><a class="mark" href="#errors_err_unknown_module_format" id="errors_err_unknown_module_format">#</a></span></h3>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>An attempt was made to load a module with an unknown or unsupported format.</p>
<p><a id="ERR_UNKNOWN_SIGNAL"></a></p>
<h3><code>ERR_UNKNOWN_SIGNAL</code><span><a class="mark" href="#errors_err_unknown_signal" id="errors_err_unknown_signal">#</a></span></h3>
<p>An invalid or unknown process signal was passed to an API expecting a valid
signal (such as <a href="#child_process_subprocess_kill_signal"><code>subprocess.kill()</code></a>).</p>
<p><a id="ERR_UNSUPPORTED_DIR_IMPORT"></a></p>
<h3><code>ERR_UNSUPPORTED_DIR_IMPORT</code><span><a class="mark" href="#errors_err_unsupported_dir_import" id="errors_err_unsupported_dir_import">#</a></span></h3>
<p><code>import</code> a directory URL is unsupported. Instead, you can
<a href="#esm_self_referencing_a_package_using_its_name">self-reference a package using its name</a> and <a href="#esm_subpath_exports">define a custom subpath</a> in
the <code>"exports"</code> field of the <code>package.json</code> file.</p>
<!-- eslint-skip -->
<pre><code class="language-js">import './'; // unsupported
import './index.js'; // supported
import 'package-name'; // supported
</code></pre>
<p><a id="ERR_UNSUPPORTED_ESM_URL_SCHEME"></a></p>
<h3><code>ERR_UNSUPPORTED_ESM_URL_SCHEME</code><span><a class="mark" href="#errors_err_unsupported_esm_url_scheme" id="errors_err_unsupported_esm_url_scheme">#</a></span></h3>
<p><code>import</code> with URL schemes other than <code>file</code> and <code>data</code> is unsupported.</p>
<p><a id="ERR_V8BREAKITERATOR"></a></p>
<h3><code>ERR_V8BREAKITERATOR</code><span><a class="mark" href="#errors_err_v8breakiterator" id="errors_err_v8breakiterator">#</a></span></h3>
<p>The V8 <code>BreakIterator</code> API was used but the full ICU data set is not installed.</p>
<p><a id="ERR_VALID_PERFORMANCE_ENTRY_TYPE"></a></p>
<h3><code>ERR_VALID_PERFORMANCE_ENTRY_TYPE</code><span><a class="mark" href="#errors_err_valid_performance_entry_type" id="errors_err_valid_performance_entry_type">#</a></span></h3>
<p>While using the Performance Timing API (<code>perf_hooks</code>), no valid performance
entry types were found.</p>
<p><a id="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"></a></p>
<h3><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code><span><a class="mark" href="#errors_err_vm_dynamic_import_callback_missing" id="errors_err_vm_dynamic_import_callback_missing">#</a></span></h3>
<p>A dynamic import callback was not specified.</p>
<p><a id="ERR_VM_MODULE_ALREADY_LINKED"></a></p>
<h3><code>ERR_VM_MODULE_ALREADY_LINKED</code><span><a class="mark" href="#errors_err_vm_module_already_linked" id="errors_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_CACHED_DATA_REJECTED"></a></p>
<h3><code>ERR_VM_MODULE_CACHED_DATA_REJECTED</code><span><a class="mark" href="#errors_err_vm_module_cached_data_rejected" id="errors_err_vm_module_cached_data_rejected">#</a></span></h3>
<p>The <code>cachedData</code> option passed to a module constructor is invalid.</p>
<p><a id="ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA"></a></p>
<h3><code>ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA</code><span><a class="mark" href="#errors_err_vm_module_cannot_create_cached_data" id="errors_err_vm_module_cannot_create_cached_data">#</a></span></h3>
<p>Cached data cannot be created for modules which have already been evaluated.</p>
<p><a id="ERR_VM_MODULE_DIFFERENT_CONTEXT"></a></p>
<h3><code>ERR_VM_MODULE_DIFFERENT_CONTEXT</code><span><a class="mark" href="#errors_err_vm_module_different_context" id="errors_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><code>ERR_VM_MODULE_LINKING_ERRORED</code><span><a class="mark" href="#errors_err_vm_module_linking_errored" id="errors_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_MODULE"></a></p>
<h3><code>ERR_VM_MODULE_NOT_MODULE</code><span><a class="mark" href="#errors_err_vm_module_not_module" id="errors_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><code>ERR_VM_MODULE_STATUS</code><span><a class="mark" href="#errors_err_vm_module_status" id="errors_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_WASI_ALREADY_STARTED"></a></p>
<h3><code>ERR_WASI_ALREADY_STARTED</code><span><a class="mark" href="#errors_err_wasi_already_started" id="errors_err_wasi_already_started">#</a></span></h3>
<p>The WASI instance has already started.</p>
<p><a id="ERR_WASI_NOT_STARTED"></a></p>
<h3><code>ERR_WASI_NOT_STARTED</code><span><a class="mark" href="#errors_err_wasi_not_started" id="errors_err_wasi_not_started">#</a></span></h3>
<p>The WASI instance has not been started.</p>
<p><a id="ERR_WORKER_INIT_FAILED"></a></p>
<h3><code>ERR_WORKER_INIT_FAILED</code><span><a class="mark" href="#errors_err_worker_init_failed" id="errors_err_worker_init_failed">#</a></span></h3>
<p>The <code>Worker</code> initialization failed.</p>
<p><a id="ERR_WORKER_INVALID_EXEC_ARGV"></a></p>
<h3><code>ERR_WORKER_INVALID_EXEC_ARGV</code><span><a class="mark" href="#errors_err_worker_invalid_exec_argv" id="errors_err_worker_invalid_exec_argv">#</a></span></h3>
<p>The <code>execArgv</code> option passed to the <code>Worker</code> constructor contains
invalid flags.</p>
<p><a id="ERR_WORKER_NOT_RUNNING"></a></p>
<h3><code>ERR_WORKER_NOT_RUNNING</code><span><a class="mark" href="#errors_err_worker_not_running" id="errors_err_worker_not_running">#</a></span></h3>
<p>An operation failed because the <code>Worker</code> instance is not currently running.</p>
<p><a id="ERR_WORKER_OUT_OF_MEMORY"></a></p>
<h3><code>ERR_WORKER_OUT_OF_MEMORY</code><span><a class="mark" href="#errors_err_worker_out_of_memory" id="errors_err_worker_out_of_memory">#</a></span></h3>
<p>The <code>Worker</code> instance terminated because it reached its memory limit.</p>
<p><a id="ERR_WORKER_PATH"></a></p>
<h3><code>ERR_WORKER_PATH</code><span><a class="mark" href="#errors_err_worker_path" id="errors_err_worker_path">#</a></span></h3>
<p>The path for the main script of a worker is neither an absolute path
nor a relative path starting with <code>./</code> or <code>../</code>.</p>
<p><a id="ERR_WORKER_UNSERIALIZABLE_ERROR"></a></p>
<h3><code>ERR_WORKER_UNSERIALIZABLE_ERROR</code><span><a class="mark" href="#errors_err_worker_unserializable_error" id="errors_err_worker_unserializable_error">#</a></span></h3>
<p>All attempts at serializing an uncaught exception from a worker thread failed.</p>
<p><a id="ERR_WORKER_UNSUPPORTED_EXTENSION"></a></p>
<h3><code>ERR_WORKER_UNSUPPORTED_EXTENSION</code><span><a class="mark" href="#errors_err_worker_unsupported_extension" id="errors_err_worker_unsupported_extension">#</a></span></h3>
<p>The pathname used for the main script of a worker has an
unknown file extension.</p>
<p><a id="ERR_WORKER_UNSUPPORTED_OPERATION"></a></p>
<h3><code>ERR_WORKER_UNSUPPORTED_OPERATION</code><span><a class="mark" href="#errors_err_worker_unsupported_operation" id="errors_err_worker_unsupported_operation">#</a></span></h3>
<p>The requested functionality is not supported in worker threads.</p>
<p><a id="ERR_ZLIB_INITIALIZATION_FAILED"></a></p>
<h3><code>ERR_ZLIB_INITIALIZATION_FAILED</code><span><a class="mark" href="#errors_err_zlib_initialization_failed" id="errors_err_zlib_initialization_failed">#</a></span></h3>
<p>Creation of a <a href="zlib.html"><code>zlib</code></a> object failed due to incorrect configuration.</p>
<p><a id="HPE_HEADER_OVERFLOW"></a></p>
<h3><code>HPE_HEADER_OVERFLOW</code><span><a class="mark" href="#errors_hpe_header_overflow" id="errors_hpe_header_overflow">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.4.0</td>
<td><p>Max header size in <code>http_parser</code> was set to 8KB.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Too much HTTP header data was received. In order to protect against malicious or
malconfigured clients, if more than 8KB of HTTP header data is received then
HTTP parsing will abort without a request or response object being created, and
an <code>Error</code> with this code will be emitted.</p>
<p><a id="MODULE_NOT_FOUND"></a></p>
<h3><code>MODULE_NOT_FOUND</code><span><a class="mark" href="#errors_module_not_found" id="errors_module_not_found">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Added <code>requireStack</code> property.</p></td></tr>
</tbody></table>
</details>
</div>
<p>A module file could not be resolved while attempting a <a href="#modules_require_id"><code>require()</code></a> or
<code>import</code> operation.</p>
<h2>Legacy Node.js error codes<span><a class="mark" href="#errors_legacy_node_js_error_codes" id="errors_legacy_node_js_error_codes">#</a></span></h2>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated. These error codes are either inconsistent, or have
been removed.</div><p></p>
<p><a id="ERR_CANNOT_TRANSFER_OBJECT"></a></p>
<h3><code>ERR_CANNOT_TRANSFER_OBJECT</code><span><a class="mark" href="#errors_err_cannot_transfer_object" id="errors_err_cannot_transfer_object">#</a></span></h3>
<!--
added: v10.5.0
removed: v12.5.0
-->
<p>The value passed to <code>postMessage()</code> contained an object that is not supported
for transferring.</p>
<p><a id="ERR_CLOSED_MESSAGE_PORT"></a></p>
<h3><code>ERR_CLOSED_MESSAGE_PORT</code><span><a class="mark" href="#errors_err_closed_message_port" id="errors_err_closed_message_port">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span><span>Removed in: v11.12.0</span>
</div>
<p>There was an attempt to use a <code>MessagePort</code> instance in a closed
state, usually after <code>.close()</code> has been called.</p>
<p><a id="ERR_CRYPTO_HASH_DIGEST_NO_UTF16"></a></p>
<h3><code>ERR_CRYPTO_HASH_DIGEST_NO_UTF16</code><span><a class="mark" href="#errors_err_crypto_hash_digest_no_utf16" id="errors_err_crypto_hash_digest_no_utf16">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v12.12.0</span>
</div>
<p>The UTF-16 encoding was used with <a href="#crypto_hash_digest_encoding"><code>hash.digest()</code></a>. While the
<code>hash.digest()</code> method does allow an <code>encoding</code> argument to be passed in,
causing the method to return a string rather than a <code>Buffer</code>, the UTF-16
encoding (e.g. <code>ucs</code> or <code>utf16le</code>) is not supported.</p>
<p><a id="ERR_HTTP2_FRAME_ERROR"></a></p>
<h3><code>ERR_HTTP2_FRAME_ERROR</code><span><a class="mark" href="#errors_err_http2_frame_error" id="errors_err_http2_frame_error">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when a failure occurs sending an individual frame on the HTTP/2
session.</p>
<p><a id="ERR_HTTP2_HEADERS_OBJECT"></a></p>
<h3><code>ERR_HTTP2_HEADERS_OBJECT</code><span><a class="mark" href="#errors_err_http2_headers_object" id="errors_err_http2_headers_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when an HTTP/2 Headers Object is expected.</p>
<p><a id="ERR_HTTP2_HEADER_REQUIRED"></a></p>
<h3><code>ERR_HTTP2_HEADER_REQUIRED</code><span><a class="mark" href="#errors_err_http2_header_required" id="errors_err_http2_header_required">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when a required header is missing in an HTTP/2 message.</p>
<p><a id="ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND"></a></p>
<h3><code>ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND</code><span><a class="mark" href="#errors_err_http2_info_headers_after_respond" id="errors_err_http2_info_headers_after_respond">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>HTTP/2 informational headers must only be sent <em>prior</em> to calling the
<code>Http2Stream.prototype.respond()</code> method.</p>
<p><a id="ERR_HTTP2_STREAM_CLOSED"></a></p>
<h3><code>ERR_HTTP2_STREAM_CLOSED</code><span><a class="mark" href="#errors_err_http2_stream_closed" id="errors_err_http2_stream_closed">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when an action has been performed on an HTTP/2 Stream that has already
been closed.</p>
<p><a id="ERR_HTTP_INVALID_CHAR"></a></p>
<h3><code>ERR_HTTP_INVALID_CHAR</code><span><a class="mark" href="#errors_err_http_invalid_char" id="errors_err_http_invalid_char">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when an invalid character is found in an HTTP response status message
(reason phrase).</p>
<p><a id="ERR_INDEX_OUT_OF_RANGE"></a></p>
<h3><code>ERR_INDEX_OUT_OF_RANGE</code><span><a class="mark" href="#errors_err_index_out_of_range" id="errors_err_index_out_of_range">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span><span>Removed in: v11.0.0</span>
</div>
<p>A given index was out of the accepted range (e.g. negative offsets).</p>
<p><a id="ERR_NAPI_CONS_PROTOTYPE_OBJECT"></a></p>
<h3><code>ERR_NAPI_CONS_PROTOTYPE_OBJECT</code><span><a class="mark" href="#errors_err_napi_cons_prototype_object" id="errors_err_napi_cons_prototype_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used by the <code>N-API</code> when <code>Constructor.prototype</code> is not an object.</p>
<p><a id="ERR_NO_LONGER_SUPPORTED"></a></p>
<h3><code>ERR_NO_LONGER_SUPPORTED</code><span><a class="mark" href="#errors_err_no_longer_supported" id="errors_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_OUTOFMEMORY"></a></p>
<h3><code>ERR_OUTOFMEMORY</code><span><a class="mark" href="#errors_err_outofmemory" id="errors_err_outofmemory">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used generically to identify that an operation caused an out of memory
condition.</p>
<p><a id="ERR_PARSE_HISTORY_DATA"></a></p>
<h3><code>ERR_PARSE_HISTORY_DATA</code><span><a class="mark" href="#errors_err_parse_history_data" id="errors_err_parse_history_data">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>The <code>repl</code> module was unable to parse data from the REPL history file.</p>
<p><a id="ERR_STDERR_CLOSE"></a></p>
<h3><code>ERR_STDERR_CLOSE</code><span><a class="mark" href="#errors_err_stderr_close" id="errors_err_stderr_close">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.12.0</td>
<td><p>Rather than emitting an error, <code>process.stderr.end()</code> now only closes the stream side but not the underlying resource, making this error obsolete.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p><span>Removed in: v10.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An attempt was made to close the <code>process.stderr</code> stream. By design, Node.js
does not allow <code>stdout</code> or <code>stderr</code> streams to be closed by user code.</p>
<p><a id="ERR_STDOUT_CLOSE"></a></p>
<h3><code>ERR_STDOUT_CLOSE</code><span><a class="mark" href="#errors_err_stdout_close" id="errors_err_stdout_close">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.12.0</td>
<td><p>Rather than emitting an error, <code>process.stderr.end()</code> now only closes the stream side but not the underlying resource, making this error obsolete.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p><span>Removed in: v10.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An attempt was made to close the <code>process.stdout</code> stream. By design, Node.js
does not allow <code>stdout</code> or <code>stderr</code> streams to be closed by user code.</p>
<p><a id="ERR_STREAM_READ_NOT_IMPLEMENTED"></a></p>
<h3><code>ERR_STREAM_READ_NOT_IMPLEMENTED</code><span><a class="mark" href="#errors_err_stream_read_not_implemented" id="errors_err_stream_read_not_implemented">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when an attempt is made to use a readable stream that has not implemented
<a href="#stream_readable_read_size_1"><code>readable._read()</code></a>.</p>
<p><a id="ERR_TLS_RENEGOTIATION_FAILED"></a></p>
<h3><code>ERR_TLS_RENEGOTIATION_FAILED</code><span><a class="mark" href="#errors_err_tls_renegotiation_failed" id="errors_err_tls_renegotiation_failed">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when a TLS renegotiation request has failed in a non-specific way.</p>
<p><a id="ERR_UNKNOWN_BUILTIN_MODULE"></a></p>
<h3><code>ERR_UNKNOWN_BUILTIN_MODULE</code><span><a class="mark" href="#errors_err_unknown_builtin_module_1" id="errors_err_unknown_builtin_module_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span><span>Removed in: v9.0.0</span>
</div>
<p>The <code>'ERR_UNKNOWN_BUILTIN_MODULE'</code> error code is used to identify a specific
kind of internal Node.js error that should not typically be triggered by user
code. Instances of this error point to an internal bug within the Node.js
binary itself.</p>
<p><a id="ERR_UNKNOWN_STDIN_TYPE"></a></p>
<h3><code>ERR_UNKNOWN_STDIN_TYPE</code><span><a class="mark" href="#errors_err_unknown_stdin_type" id="errors_err_unknown_stdin_type">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span><span>Removed in: v11.7.0</span>
</div>
<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><code>ERR_UNKNOWN_STREAM_TYPE</code><span><a class="mark" href="#errors_err_unknown_stream_type" id="errors_err_unknown_stream_type">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span><span>Removed in: v11.7.0</span>
</div>
<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_VALUE_OUT_OF_RANGE"></a></p>
<h3><code>ERR_VALUE_OUT_OF_RANGE</code><span><a class="mark" href="#errors_err_value_out_of_range" id="errors_err_value_out_of_range">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when a given value is out of the accepted range.</p>
<p><a id="ERR_VM_MODULE_NOT_LINKED"></a></p>
<h3><code>ERR_VM_MODULE_NOT_LINKED</code><span><a class="mark" href="#errors_err_vm_module_not_linked" id="errors_err_vm_module_not_linked">#</a></span></h3>
<p>The module must be successfully linked before instantiation.</p>
<p><a id="ERR_ZLIB_BINDING_CLOSED"></a></p>
<h3><code>ERR_ZLIB_BINDING_CLOSED</code><span><a class="mark" href="#errors_err_zlib_binding_closed" id="errors_err_zlib_binding_closed">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used when an attempt is made to use a <code>zlib</code> object after it has already been
closed.</p>
<h3>Other error codes<span><a class="mark" href="#errors_other_error_codes" id="errors_other_error_codes">#</a></span></h3>
<p>These errors have never been released, but had been present on master between
releases.</p>
<p><a id="ERR_ENTRY_TYPE_MISMATCH"></a></p>
<h4><code>ERR_ENTRY_TYPE_MISMATCH</code><span><a class="mark" href="#errors_err_entry_type_mismatch" id="errors_err_entry_type_mismatch">#</a></span></h4>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>The <code>--entry-type=commonjs</code> flag was used to attempt to execute an <code>.mjs</code> file
or a <code>.js</code> file where the nearest parent <code>package.json</code> contains
<code>"type": "module"</code>; or
the <code>--entry-type=module</code> flag was used to attempt to execute a <code>.cjs</code> file or
a <code>.js</code> file where the nearest parent <code>package.json</code> either lacks a <code>"type"</code>
field or contains <code>"type": "commonjs"</code>.</p>
<p><a id="ERR_FS_WATCHER_ALREADY_STARTED"></a></p>
<h4><code>ERR_FS_WATCHER_ALREADY_STARTED</code><span><a class="mark" href="#errors_err_fs_watcher_already_started" id="errors_err_fs_watcher_already_started">#</a></span></h4>
<p>An attempt was made to start a watcher returned by <code>fs.watch()</code> that has
already been started.</p>
<p><a id="ERR_FS_WATCHER_NOT_STARTED"></a></p>
<h4><code>ERR_FS_WATCHER_NOT_STARTED</code><span><a class="mark" href="#errors_err_fs_watcher_not_started" id="errors_err_fs_watcher_not_started">#</a></span></h4>
<p>An attempt was made to initiate operations on a watcher returned by
<code>fs.watch()</code> that has not yet been started.</p>
<p><a id="ERR_HTTP2_ALREADY_SHUTDOWN"></a></p>
<h4><code>ERR_HTTP2_ALREADY_SHUTDOWN</code><span><a class="mark" href="#errors_err_http2_already_shutdown" id="errors_err_http2_already_shutdown">#</a></span></h4>
<p>Occurs with multiple attempts to shutdown an HTTP/2 session.</p>
<p><a id="ERR_HTTP2_ERROR"></a></p>
<h4><code>ERR_HTTP2_ERROR</code><span><a class="mark" href="#errors_err_http2_error_1" id="errors_err_http2_error_1">#</a></span></h4>
<p>A non-specific HTTP/2 error has occurred.</p>
<p><a id="ERR_INVALID_REPL_HISTORY"></a></p>
<h4><code>ERR_INVALID_REPL_HISTORY</code><span><a class="mark" href="#errors_err_invalid_repl_history" id="errors_err_invalid_repl_history">#</a></span></h4>
<p>Used in the <code>repl</code> in case the old history file is used and an error occurred
while trying to read and parse it.</p>
<p><a id="ERR_INVALID_REPL_TYPE"></a></p>
<h4><code>ERR_INVALID_REPL_TYPE</code><span><a class="mark" href="#errors_err_invalid_repl_type" id="errors_err_invalid_repl_type">#</a></span></h4>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>The <code>--entry-type=...</code> flag is not compatible with the Node.js REPL.</p>
<p><a id="ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK"></a></p>
<h4><code>ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK</code><span><a class="mark" href="#errors_err_missing_dynamic_instantiate_hook_1" id="errors_err_missing_dynamic_instantiate_hook_1">#</a></span></h4>
<p>Used when an <a href="esm.html">ES Module</a> loader hook specifies <code>format: 'dynamic'</code> but does
not provide a <code>dynamicInstantiate</code> hook.</p>
<p><a id="ERR_STREAM_HAS_STRINGDECODER"></a></p>
<h4><code>ERR_STREAM_HAS_STRINGDECODER</code><span><a class="mark" href="#errors_err_stream_has_stringdecoder" id="errors_err_stream_has_stringdecoder">#</a></span></h4>
<p>Used to prevent an abort if a string decoder was set on the Socket.</p>
<pre><code class="language-js">const Socket = require('net').Socket;
const instance = new Socket();

instance.setEncoding('utf8');
</code></pre>
<p><a id="ERR_STRING_TOO_LARGE"></a></p>
<h4><code>ERR_STRING_TOO_LARGE</code><span><a class="mark" href="#errors_err_string_too_large" id="errors_err_string_too_large">#</a></span></h4>
<p>An attempt has been made to create a string larger than the maximum allowed
size.</p>
<p><a id="ERR_TTY_WRITABLE_NOT_READABLE"></a></p>
<h4><code>ERR_TTY_WRITABLE_NOT_READABLE</code><span><a class="mark" href="#errors_err_tty_writable_not_readable" id="errors_err_tty_writable_not_readable">#</a></span></h4>
<p>This <code>Error</code> is thrown when a read is attempted on a TTY <code>WriteStream</code>,
such as <code>process.stdout.on('data')</code>.</p>
<h1>Events<span><a class="mark" href="#events_events" id="events_events">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>

<p>Much of the Node.js core API is built around an idiomatic asynchronous
event-driven architecture in which certain kinds of objects (called "emitters")
emit named events that cause <code>Function</code> objects ("listeners") to be called.</p>
<p>For instance: a <a href="#net_class_net_server"><code>net.Server</code></a> object emits an event each time a peer
connects to it; a <a href="#fs_class_fs_readstream"><code>fs.ReadStream</code></a> emits an event when the file is opened;
a <a href="stream.html">stream</a> emits an event whenever data is available to be read.</p>
<p>All objects that emit events are instances of the <code>EventEmitter</code> class. These
objects expose an <code>eventEmitter.on()</code> function that allows one or more
functions to be attached to named events emitted by the object. Typically,
event names are camel-cased strings but any valid JavaScript property key
can be used.</p>
<p>When the <code>EventEmitter</code> object emits an event, all of the functions attached
to that specific event are called <em>synchronously</em>. Any values returned by the
called listeners are <em>ignored</em> and will be discarded.</p>
<p>The following example shows a simple <code>EventEmitter</code> instance with a single
listener. The <code>eventEmitter.on()</code> method is used to register listeners, while
the <code>eventEmitter.emit()</code> method is used to trigger the event.</p>
<pre><code class="language-js">const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
  console.log('an event occurred!');
});
myEmitter.emit('event');
</code></pre>
<h2>Passing arguments and <code>this</code> to listeners<span><a class="mark" href="#events_passing_arguments_and_this_to_listeners" id="events_passing_arguments_and_this_to_listeners">#</a></span></h2>
<p>The <code>eventEmitter.emit()</code> method allows an arbitrary set of arguments to be
passed to the listener functions. Keep in mind that when
an ordinary listener function is called, the standard <code>this</code> keyword
is intentionally set to reference the <code>EventEmitter</code> instance to which the
listener is attached.</p>
<pre><code class="language-js">const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
  console.log(a, b, this, this === myEmitter);
  // Prints:
  //   a b MyEmitter {
  //     domain: null,
  //     _events: { event: [Function] },
  //     _eventsCount: 1,
  //     _maxListeners: undefined } true
});
myEmitter.emit('event', 'a', 'b');
</code></pre>
<p>It is possible to use ES6 Arrow Functions as listeners, however, when doing so,
the <code>this</code> keyword will no longer reference the <code>EventEmitter</code> instance:</p>
<pre><code class="language-js">const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  console.log(a, b, this);
  // Prints: a b {}
});
myEmitter.emit('event', 'a', 'b');
</code></pre>
<h2>Asynchronous vs. synchronous<span><a class="mark" href="#events_asynchronous_vs_synchronous" id="events_asynchronous_vs_synchronous">#</a></span></h2>
<p>The <code>EventEmitter</code> calls all listeners synchronously in the order in which
they were registered. This ensures the proper sequencing of
events and helps avoid race conditions and logic errors. When appropriate,
listener functions can switch to an asynchronous mode of operation using
the <code>setImmediate()</code> or <code>process.nextTick()</code> methods:</p>
<pre><code class="language-js">const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  setImmediate(() => {
    console.log('this happens asynchronously');
  });
});
myEmitter.emit('event', 'a', 'b');
</code></pre>
<h2>Handling events only once<span><a class="mark" href="#events_handling_events_only_once" id="events_handling_events_only_once">#</a></span></h2>
<p>When a listener is registered using the <code>eventEmitter.on()</code> method, that
listener will be invoked <em>every time</em> the named event is emitted.</p>
<pre><code class="language-js">const myEmitter = new MyEmitter();
let m = 0;
myEmitter.on('event', () => {
  console.log(++m);
});
myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Prints: 2
</code></pre>
<p>Using the <code>eventEmitter.once()</code> method, it is possible to register a listener
that is called at most once for a particular event. Once the event is emitted,
the listener is unregistered and <em>then</em> called.</p>
<pre><code class="language-js">const myEmitter = new MyEmitter();
let m = 0;
myEmitter.once('event', () => {
  console.log(++m);
});
myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Ignored
</code></pre>
<h2>Error events<span><a class="mark" href="#events_error_events" id="events_error_events">#</a></span></h2>
<p>When an error occurs within an <code>EventEmitter</code> instance, the typical action is
for an <code>'error'</code> event to be emitted. These are treated as special cases
within Node.js.</p>
<p>If an <code>EventEmitter</code> does <em>not</em> have at least one listener registered for the
<code>'error'</code> event, and an <code>'error'</code> event is emitted, the error is thrown, a
stack trace is printed, and the Node.js process exits.</p>
<pre><code class="language-js">const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
// Throws and crashes Node.js
</code></pre>
<p>To guard against crashing the Node.js process the <a href="domain.html"><code>domain</code></a> module can be
used. (Note, however, that the <code>domain</code> module is deprecated.)</p>
<p>As a best practice, listeners should always be added for the <code>'error'</code> events.</p>
<pre><code class="language-js">const myEmitter = new MyEmitter();
myEmitter.on('error', (err) => {
  console.error('whoops! there was an error');
});
myEmitter.emit('error', new Error('whoops!'));
// Prints: whoops! there was an error
</code></pre>
<p>It is possible to monitor <code>'error'</code> events without consuming the emitted error
by installing a listener using the symbol <code>errorMonitor</code>.</p>
<pre><code class="language-js">const myEmitter = new MyEmitter();
myEmitter.on(EventEmitter.errorMonitor, (err) => {
  MyMonitoringTool.log(err);
});
myEmitter.emit('error', new Error('whoops!'));
// Still throws and crashes Node.js
</code></pre>
<h2>Capture rejections of promises<span><a class="mark" href="#events_capture_rejections_of_promises" id="events_capture_rejections_of_promises">#</a></span></h2>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - captureRejections is experimental.</div><p></p>
<p>Using <code>async</code> functions with event handlers is problematic, because it
can lead to an unhandled rejection in case of a thrown exception:</p>
<pre><code class="language-js">const ee = new EventEmitter();
ee.on('something', async (value) => {
  throw new Error('kaboom');
});
</code></pre>
<p>The <code>captureRejections</code> option in the <code>EventEmitter</code> constructor or the global
setting change this behavior, installing a <code>.then(undefined, handler)</code>
handler on the <code>Promise</code>. This handler routes the exception
asynchronously to the <a href="#events_emitter_symbol_for_nodejs_rejection_err_eventname_args"><code>Symbol.for('nodejs.rejection')</code></a> method
if there is one, or to <a href="#events_error_events"><code>'error'</code></a> event handler if there is none.</p>
<pre><code class="language-js">const ee1 = new EventEmitter({ captureRejections: true });
ee1.on('something', async (value) => {
  throw new Error('kaboom');
});

ee1.on('error', console.log);

const ee2 = new EventEmitter({ captureRejections: true });
ee2.on('something', async (value) => {
  throw new Error('kaboom');
});

ee2[Symbol.for('nodejs.rejection')] = console.log;
</code></pre>
<p>Setting <code>EventEmitter.captureRejections = true</code> will change the default for all
new instances of <code>EventEmitter</code>.</p>
<pre><code class="language-js">EventEmitter.captureRejections = true;
const ee1 = new EventEmitter();
ee1.on('something', async (value) => {
  throw new Error('kaboom');
});

ee1.on('error', console.log);
</code></pre>
<p>The <code>'error'</code> events that are generated by the <code>captureRejections</code> behavior
do not have a catch handler to avoid infinite error loops: the
recommendation is to <strong>not use <code>async</code> functions as <code>'error'</code> event handlers</strong>.</p>
<h2>Class: <code>EventEmitter</code><span><a class="mark" href="#events_class_eventemitter" id="events_class_eventemitter">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>Added captureRejections option.</p></td></tr>
<tr><td>v0.1.26</td>
<td><p><span>Added in: v0.1.26</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>EventEmitter</code> class is defined and exposed by the <code>events</code> module:</p>
<pre><code class="language-js">const EventEmitter = require('events');
</code></pre>
<p>All <code>EventEmitter</code>s emit the event <code>'newListener'</code> when new listeners are
added and <code>'removeListener'</code> when existing listeners are removed.</p>
<p>It supports the following option:</p>
<ul>
<li><code>captureRejections</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> It enables
<a href="#events_capture_rejections_of_promises">automatic capturing of promise rejection</a>.
Default: <code>false</code>.</li>
</ul>
<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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;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">&#x3C;Function></a> The event handler function</li>
</ul>
<p>The <code>EventEmitter</code> instance will emit its own <code>'newListener'</code> event <em>before</em>
a listener is added to its internal array of listeners.</p>
<p>Listeners registered for the <code>'newListener'</code> event will be passed the event
name and a reference to the listener being added.</p>
<p>The fact that the event is triggered before adding the listener has a subtle
but important side effect: any <em>additional</em> listeners registered to the same
<code>name</code> <em>within</em> the <code>'newListener'</code> callback will be inserted <em>before</em> the
listener that is in the process of being added.</p>
<pre><code class="language-js">const myEmitter = new MyEmitter();
// Only do this once so we don't loop forever
myEmitter.once('newListener', (event, listener) => {
  if (event === 'event') {
    // Insert a new listener in front
    myEmitter.on('event', () => {
      console.log('B');
    });
  }
});
myEmitter.on('event', () => {
  console.log('A');
});
myEmitter.emit('event');
// Prints:
//   B
//   A
</code></pre>
<h3>Event: <code>'removeListener'</code><span><a class="mark" href="#events_event_removelistener" id="events_event_removelistener">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.1.0, v4.7.0</td>
<td><p>For listeners attached using <code>.once()</code>, the <code>listener</code> argument now yields the original listener function.</p></td></tr>
<tr><td>v0.9.3</td>
<td><p><span>Added in: v0.9.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;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">&#x3C;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><code>EventEmitter.listenerCount(emitter, eventName)</code><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>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#events_emitter_listenercount_eventname"><code>emitter.listenerCount()</code></a> instead.</div><p></p>
<ul>
<li><code>emitter</code> <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a> The emitter to query</li>
<li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> The event name</li>
</ul>
<p>A class method that returns the number of listeners for the given <code>eventName</code>
registered on the given <code>emitter</code>.</p>
<pre><code class="language-js">const myEmitter = new MyEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(EventEmitter.listenerCount(myEmitter, 'event'));
// Prints: 2
</code></pre>
<h3><code>EventEmitter.defaultMaxListeners</code><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>This is not a hard limit. The <code>EventEmitter</code> instance will allow
more listeners to be added but will output a trace warning to stderr indicating
that a "possible EventEmitter memory leak" has been detected. For any single
<code>EventEmitter</code>, the <code>emitter.getMaxListeners()</code> and <code>emitter.setMaxListeners()</code>
methods can be used to temporarily avoid this warning:</p>
<pre><code class="language-js">emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
  // do stuff
  emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
</code></pre>
<p>The <a href="#cli_trace_warnings"><code>--trace-warnings</code></a> command line flag can be used to display the
stack trace for such warnings.</p>
<p>The emitted warning can be inspected with <a href="#process_event_warning"><code>process.on('warning')</code></a> and will
have the additional <code>emitter</code>, <code>type</code> and <code>count</code> properties, referring to
the event emitter instance, the event’s name and the number of attached
listeners, respectively.
Its <code>name</code> property is set to <code>'MaxListenersExceededWarning'</code>.</p>
<h3><code>EventEmitter.errorMonitor</code><span><a class="mark" href="#events_eventemitter_errormonitor" id="events_eventemitter_errormonitor">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<p>This symbol shall be used to install a listener for only monitoring <code>'error'</code>
events. Listeners installed using this symbol are called before the regular
<code>'error'</code> listeners are called.</p>
<p>Installing a listener using this symbol does not change the behavior once an
<code>'error'</code> event is emitted, therefore the process will still crash if no
regular <code>'error'</code> listener is installed.</p>
<h3><code>emitter.addListener(eventName, listener)</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a></li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Alias for <code>emitter.on(eventName, listener)</code>.</p>
<h3><code>emitter.emit(eventName[, ...args])</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Synchronously calls each of the listeners registered for the event named
<code>eventName</code>, in the order they were registered, passing the supplied arguments
to each.</p>
<p>Returns <code>true</code> if the event had listeners, <code>false</code> otherwise.</p>
<pre><code class="language-js">const EventEmitter = require('events');
const myEmitter = new EventEmitter();

// First listener
myEmitter.on('event', function firstListener() {
  console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
  console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
  const parameters = args.join(', ');
  console.log(`event with parameters ${parameters} in third listener`);
});

console.log(myEmitter.listeners('event'));

myEmitter.emit('event', 1, 2, 3, 4, 5);

// Prints:
// [
//   [Function: firstListener],
//   [Function: secondListener],
//   [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
</code></pre>
<h3><code>emitter.eventNames()</code><span><a class="mark" href="#events_emitter_eventnames" id="events_emitter_eventnames">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a></li>
</ul>
<p>Returns an array listing the events for which the emitter has registered
listeners. The values in the array will be strings or <code>Symbol</code>s.</p>
<pre><code class="language-js">const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});

const sym = Symbol('symbol');
myEE.on(sym, () => {});

console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
</code></pre>
<h3><code>emitter.getMaxListeners()</code><span><a class="mark" href="#events_emitter_getmaxlisteners" id="events_emitter_getmaxlisteners">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Returns the current max listener value for the <code>EventEmitter</code> which is either
set by <a href="#events_emitter_setmaxlisteners_n"><code>emitter.setMaxListeners(n)</code></a> or defaults to
<a href="#events_eventemitter_defaultmaxlisteners"><code>EventEmitter.defaultMaxListeners</code></a>.</p>
<h3><code>emitter.listenerCount(eventName)</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> The name of the event being listened for</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Returns the number of listeners listening to the event named <code>eventName</code>.</p>
<h3><code>emitter.listeners(eventName)</code><span><a class="mark" href="#events_emitter_listeners_eventname" id="events_emitter_listeners_eventname">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>For listeners attached using <code>.once()</code> this returns the original listeners instead of wrapper functions now.</p></td></tr>
<tr><td>v0.1.26</td>
<td><p><span>Added in: v0.1.26</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function[]></a></li>
</ul>
<p>Returns a copy of the array of listeners for the event named <code>eventName</code>.</p>
<pre><code class="language-js">server.on('connection', (stream) => {
  console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
</code></pre>
<h3><code>emitter.off(eventName, listener)</code><span><a class="mark" href="#events_emitter_off_eventname_listener" id="events_emitter_off_eventname_listener">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a></li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Alias for <a href="#events_emitter_removelistener_eventname_listener"><code>emitter.removeListener()</code></a>.</p>
<h3><code>emitter.on(eventName, listener)</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;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">&#x3C;Function></a> The callback function</li>
<li>Returns: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Adds the <code>listener</code> function to the end of the listeners array for the
event named <code>eventName</code>. No checks are made to see if the <code>listener</code> has
already been added. Multiple calls passing the same combination of <code>eventName</code>
and <code>listener</code> will result in the <code>listener</code> being added, and called, multiple
times.</p>
<pre><code class="language-js">server.on('connection', (stream) => {
  console.log('someone connected!');
});
</code></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<p>By default, event listeners are invoked in the order they are added. The
<code>emitter.prependListener()</code> method can be used as an alternative to add the
event listener to the beginning of the listeners array.</p>
<pre><code class="language-js">const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
//   b
//   a
</code></pre>
<h3><code>emitter.once(eventName, listener)</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;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">&#x3C;Function></a> The callback function</li>
<li>Returns: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Adds a <strong>one-time</strong> <code>listener</code> function for the event named <code>eventName</code>. The
next time <code>eventName</code> is triggered, this listener is removed and then invoked.</p>
<pre><code class="language-js">server.once('connection', (stream) => {
  console.log('Ah, we have our first user!');
});
</code></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<p>By default, event listeners are invoked in the order they are added. The
<code>emitter.prependOnceListener()</code> method can be used as an alternative to add the
event listener to the beginning of the listeners array.</p>
<pre><code class="language-js">const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
//   b
//   a
</code></pre>
<h3><code>emitter.prependListener(eventName, listener)</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;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">&#x3C;Function></a> The callback function</li>
<li>Returns: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Adds the <code>listener</code> function to the <em>beginning</em> of the listeners array for the
event named <code>eventName</code>. No checks are made to see if the <code>listener</code> has
already been added. Multiple calls passing the same combination of <code>eventName</code>
and <code>listener</code> will result in the <code>listener</code> being added, and called, multiple
times.</p>
<pre><code class="language-js">server.prependListener('connection', (stream) => {
  console.log('someone connected!');
});
</code></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<h3><code>emitter.prependOnceListener(eventName, listener)</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;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">&#x3C;Function></a> The callback function</li>
<li>Returns: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Adds a <strong>one-time</strong> <code>listener</code> function for the event named <code>eventName</code> to the
<em>beginning</em> of the listeners array. The next time <code>eventName</code> is triggered, this
listener is removed, and then invoked.</p>
<pre><code class="language-js">server.prependOnceListener('connection', (stream) => {
  console.log('Ah, we have our first user!');
});
</code></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<h3><code>emitter.removeAllListeners([eventName])</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a></li>
<li>Returns: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Removes all listeners, or those of the specified <code>eventName</code>.</p>
<p>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><code>emitter.removeListener(eventName, listener)</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a></li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Removes the specified <code>listener</code> from the listener array for the event named
<code>eventName</code>.</p>
<pre><code class="language-js">const callback = (stream) => {
  console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
</code></pre>
<p><code>removeListener()</code> will remove, at most, one instance of a listener from the
listener array. If any single listener has been added multiple times to the
listener array for the specified <code>eventName</code>, then <code>removeListener()</code> must be
called multiple times to remove each instance.</p>
<p>Once an event has been emitted, all listeners attached to it at the
time of emitting will be called in order. This implies that any
<code>removeListener()</code> or <code>removeAllListeners()</code> calls <em>after</em> emitting and
<em>before</em> the last listener finishes execution will not remove them from
<code>emit()</code> in progress. Subsequent events will behave as expected.</p>
<pre><code class="language-js">const myEmitter = new MyEmitter();

const callbackA = () => {
  console.log('A');
  myEmitter.removeListener('event', callbackB);
};

const callbackB = () => {
  console.log('B');
};

myEmitter.on('event', callbackA);

myEmitter.on('event', callbackB);

// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
//   A
//   B

// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
//   A
</code></pre>
<p>Because listeners are managed using an internal array, calling this will
change the position indices of any listener registered <em>after</em> the listener
being removed. This will not impact the order in which listeners are called,
but it means that any copies of the listener array as returned by
the <code>emitter.listeners()</code> method will need to be recreated.</p>
<p>When a single function has been added as a handler multiple times for a single
event (as in the example below), <code>removeListener()</code> will remove the most
recently added instance. In the example the <code>once('ping')</code>
listener is removed:</p>
<pre><code class="language-js">const ee = new EventEmitter();

function pong() {
  console.log('pong');
}

ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);

ee.emit('ping');
ee.emit('ping');
</code></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<h3><code>emitter.setMaxListeners(n)</code><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">&#x3C;integer></a></li>
<li>Returns: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>By default <code>EventEmitter</code>s will print a warning if more than <code>10</code> listeners are
added for a particular event. This is a useful default that helps finding
memory leaks. 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><code>emitter.rawListeners(eventName)</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function[]></a></li>
</ul>
<p>Returns a copy of the array of listeners for the event named <code>eventName</code>,
including any wrappers (such as those created by <code>.once()</code>).</p>
<pre><code class="language-js">const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));

// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];

// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();

// Logs "log once" to the console and removes the listener
logFnWrapper();

emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');

// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
</code></pre>
<h3><code>emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])</code><span><a class="mark" href="#events_emitter_symbol_for_nodejs_rejection_err_eventname_args" id="events_emitter_symbol_for_nodejs_rejection_err_eventname_args">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - captureRejections is experimental.</div><p></p>
<ul>
<li><code>err</code> Error</li>
<li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>The <code>Symbol.for('nodejs.rejection')</code> method is called in case a
promise rejection happens when emitting an event and
<a href="#events_capture_rejections_of_promises"><code>captureRejections</code></a> is enabled on the emitter.
It is possible to use <a href="#events_events_capturerejectionsymbol"><code>events.captureRejectionSymbol</code></a> in
place of <code>Symbol.for('nodejs.rejection')</code>.</p>
<pre><code class="language-js">const { EventEmitter, captureRejectionSymbol } = require('events');

class MyClass extends EventEmitter {
  constructor() {
    super({ captureRejections: true });
  }

  [captureRejectionSymbol](err, event, ...args) {
    console.log('rejection happened for', event, 'with', err, ...args);
    this.destroy(err);
  }

  destroy(err) {
    // Tear the resource down here.
  }
}
</code></pre>
<h2><code>events.once(emitter, name)</code><span><a class="mark" href="#events_events_once_emitter_name" id="events_events_once_emitter_name">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.13.0</span>
</div>
<ul>
<li><code>emitter</code> <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Creates a <code>Promise</code> that is fulfilled when the <code>EventEmitter</code> emits the given
event or that is rejected when the <code>EventEmitter</code> emits <code>'error'</code>.
The <code>Promise</code> will resolve with an array of all the arguments emitted to the
given event.</p>
<p>This method is intentionally generic and works with the web platform
<a href="https://dom.spec.whatwg.org/#interface-eventtarget">EventTarget</a> interface, which has no special
<code>'error'</code> event semantics and does not listen to the <code>'error'</code> event.</p>
<pre><code class="language-js">const { once, EventEmitter } = require('events');

async function run() {
  const ee = new EventEmitter();

  process.nextTick(() => {
    ee.emit('myevent', 42);
  });

  const [value] = await once(ee, 'myevent');
  console.log(value);

  const err = new Error('kaboom');
  process.nextTick(() => {
    ee.emit('error', err);
  });

  try {
    await once(ee, 'myevent');
  } catch (err) {
    console.log('error happened', err);
  }
}

run();
</code></pre>
<h2>events.captureRejections<span><a class="mark" href="#events_events_capturerejections" id="events_events_capturerejections">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - captureRejections is experimental.</div><p></p>
<p>Value: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></p>
<p>Change the default <code>captureRejections</code> option on all new <code>EventEmitter</code> objects.</p>
<h2>events.captureRejectionSymbol<span><a class="mark" href="#events_events_capturerejectionsymbol" id="events_events_capturerejectionsymbol">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - captureRejections is experimental.</div><p></p>
<p>Value: <code>Symbol.for('nodejs.rejection')</code></p>
<p>See how to write a custom <a href="#events_emitter_symbol_for_nodejs_rejection_err_eventname_args">rejection handler</a>.</p>
<h2>events.on(emitter, eventName)<a class="srclink" href="https://github.com/nodejs/node/blob/e3e0927bb93ed92bcdfe81e7ad9af3d78ccc74fb/lib/events.js#L667">[src]</a><span><a class="mark" href="#events_events_on_emitter_eventname" id="events_events_on_emitter_eventname">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li><code>emitter</code> <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
<li><code>eventName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> The name of the event being listened for</li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type">&#x3C;AsyncIterator></a> that iterates <code>eventName</code> events emitted by the <code>emitter</code></li>
</ul>
<pre><code class="language-js">const { on, EventEmitter } = require('events');

(async () => {
  const ee = new EventEmitter();

  // Emit later on
  process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
  });

  for await (const event of on(ee, 'foo')) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
  }
  // Unreachable here
})();
</code></pre>
<p>Returns an <code>AsyncIterator</code> that iterates <code>eventName</code> events. It will throw
if the <code>EventEmitter</code> emits <code>'error'</code>. It removes all listeners when
exiting the loop. The <code>value</code> returned by each iteration is an array
composed of the emitted event arguments.</p>
<h1>File system<span><a class="mark" href="#fs_file_system" id="fs_file_system">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>

<p>The <code>fs</code> module provides an API for interacting with the file system in a
manner closely modeled around standard POSIX functions.</p>
<p>To use this module:</p>
<pre><code class="language-js">const fs = require('fs');
</code></pre>
<p>All file system operations have synchronous and asynchronous forms.</p>
<p>The asynchronous form always takes a completion callback as its last argument.
The arguments passed to the completion callback depend on the method, but the
first argument is always reserved for an exception. If the operation was
completed successfully, then the first argument will be <code>null</code> or <code>undefined</code>.</p>
<pre><code class="language-js">const fs = require('fs');

fs.unlink('/tmp/hello', (err) => {
  if (err) throw err;
  console.log('successfully deleted /tmp/hello');
});
</code></pre>
<p>Exceptions that occur using synchronous operations are thrown immediately and
may be handled using <code>try…catch</code>, or may be allowed to bubble up.</p>
<pre><code class="language-js">const fs = require('fs');

try {
  fs.unlinkSync('/tmp/hello');
  console.log('successfully deleted /tmp/hello');
} catch (err) {
  // handle the error
}
</code></pre>
<p>There is no guaranteed ordering when using asynchronous methods. So the
following is prone to error because the <code>fs.stat()</code> operation may complete
before the <code>fs.rename()</code> operation:</p>
<pre><code class="language-js">fs.rename('/tmp/hello', '/tmp/world', (err) => {
  if (err) throw err;
  console.log('renamed complete');
});
fs.stat('/tmp/world', (err, stats) => {
  if (err) throw err;
  console.log(`stats: ${JSON.stringify(stats)}`);
});
</code></pre>
<p>To correctly order the operations, move the <code>fs.stat()</code> call into the callback
of the <code>fs.rename()</code> operation:</p>
<pre><code class="language-js">fs.rename('/tmp/hello', '/tmp/world', (err) => {
  if (err) throw err;
  fs.stat('/tmp/world', (err, stats) => {
    if (err) throw err;
    console.log(`stats: ${JSON.stringify(stats)}`);
  });
});
</code></pre>
<p>In busy processes, use the asynchronous versions of these calls. The synchronous
versions will block the entire process until they complete, halting all
connections.</p>
<p>While it is not recommended, most fs functions allow the callback argument to
be omitted, in which case a default callback is used that rethrows errors. To
get a trace to the original call site, set the <code>NODE_DEBUG</code> environment
variable:</p>
<p>Omitting the callback function on asynchronous fs functions is deprecated and
may result in an error being thrown in the future.</p>
<pre><code class="language-console">$ 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
    &#x3C;stack trace.>
</code></pre>
<h2>File paths<span><a class="mark" href="#fs_file_paths" id="fs_file_paths">#</a></span></h2>
<p>Most <code>fs</code> operations accept filepaths that may be specified in the form of
a string, a <a href="#buffer_buffer"><code>Buffer</code></a>, or a <a href="#url_the_whatwg_url_api"><code>URL</code></a> object using the <code>file:</code> protocol.</p>
<p>String form paths are interpreted as UTF-8 character sequences identifying
the absolute or relative filename. Relative paths will be resolved relative
to the current working directory as specified by <code>process.cwd()</code>.</p>
<p>Example using an absolute path on POSIX:</p>
<pre><code class="language-js">const fs = require('fs');

fs.open('/open/some/file.txt', 'r', (err, fd) => {
  if (err) throw err;
  fs.close(fd, (err) => {
    if (err) throw err;
  });
});
</code></pre>
<p>Example using a relative path on POSIX (relative to <code>process.cwd()</code>):</p>
<pre><code class="language-js">fs.open('file.txt', 'r', (err, fd) => {
  if (err) throw err;
  fs.close(fd, (err) => {
    if (err) throw err;
  });
});
</code></pre>
<p>Paths specified using a <a href="#buffer_buffer"><code>Buffer</code></a> are useful primarily on certain POSIX
operating systems that treat file paths as opaque byte sequences. On such
systems, it is possible for a single file path to contain sub-sequences that
use multiple character encodings. As with string paths, <code>Buffer</code> paths may
be relative or absolute:</p>
<p>Example using an absolute path on POSIX:</p>
<pre><code class="language-js">fs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => {
  if (err) throw err;
  fs.close(fd, (err) => {
    if (err) throw err;
  });
});
</code></pre>
<p>On Windows, Node.js follows the concept of per-drive working directory. This
behavior can be observed when using a drive path without a backslash. For
example <code>fs.readdirSync('C:\\')</code> can potentially return a different result than
<code>fs.readdirSync('C:')</code>. For more information, see
<a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths">this MSDN page</a>.</p>
<h3>URL object support<span><a class="mark" href="#fs_url_object_support" id="fs_url_object_support">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.6.0</span>
</div>
<p>For most <code>fs</code> module functions, the <code>path</code> or <code>filename</code> argument may be passed
as a WHATWG <a href="#url_the_whatwg_url_api"><code>URL</code></a> object. Only <a href="#url_the_whatwg_url_api"><code>URL</code></a> objects using the <code>file:</code> protocol
are supported.</p>
<pre><code class="language-js">const fs = require('fs');
const fileUrl = new URL('file:///tmp/hello');

fs.readFileSync(fileUrl);
</code></pre>
<p><code>file:</code> URLs are always absolute paths.</p>
<p>Using WHATWG <a href="#url_the_whatwg_url_api"><code>URL</code></a> objects might introduce platform-specific behaviors.</p>
<p>On Windows, <code>file:</code> URLs with a host name convert to UNC paths, while <code>file:</code>
URLs with drive letters convert to local absolute paths. <code>file:</code> URLs without a
host name nor a drive letter will result in a throw:</p>
<pre><code class="language-js">// On Windows :

// - WHATWG file URLs with hostname convert to UNC path
// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file
fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));

// - WHATWG file URLs with drive letters convert to absolute path
// file:///C:/tmp/hello => C:\tmp\hello
fs.readFileSync(new URL('file:///C:/tmp/hello'));

// - WHATWG file URLs without hostname must have a drive letters
fs.readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));
fs.readFileSync(new URL('file:///c/p/a/t/h/file'));
// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
</code></pre>
<p><code>file:</code> URLs with drive letters must use <code>:</code> as a separator just after
the drive letter. Using another separator will result in a throw.</p>
<p>On all other platforms, <code>file:</code> URLs with a host name are unsupported and will
result in a throw:</p>
<pre><code class="language-js">// On other platforms:

// - WHATWG file URLs with hostname are unsupported
// file://hostname/p/a/t/h/file => throw!
fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute

// - WHATWG file URLs convert to absolute path
// file:///tmp/hello => /tmp/hello
fs.readFileSync(new URL('file:///tmp/hello'));
</code></pre>
<p>A <code>file:</code> URL having encoded slash characters will result in a throw on all
platforms:</p>
<pre><code class="language-js">// On Windows
fs.readFileSync(new URL('file:///C:/p/a/t/h/%2F'));
fs.readFileSync(new URL('file:///C:/p/a/t/h/%2f'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */

// On POSIX
fs.readFileSync(new URL('file:///p/a/t/h/%2F'));
fs.readFileSync(new URL('file:///p/a/t/h/%2f'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
/ characters */
</code></pre>
<p>On Windows, <code>file:</code> URLs having encoded backslash will result in a throw:</p>
<pre><code class="language-js">// On Windows
fs.readFileSync(new URL('file:///C:/path/%5C'));
fs.readFileSync(new URL('file:///C:/path/%5c'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */
</code></pre>
<h2>File descriptors<span><a class="mark" href="#fs_file_descriptors" id="fs_file_descriptors">#</a></span></h2>
<p>On POSIX systems, for every process, the kernel maintains a table of currently
open files and resources. Each open file is assigned a simple numeric
identifier called a <em>file descriptor</em>. At the system-level, all file system
operations use these file descriptors to identify and track each specific
file. Windows systems use a different but conceptually similar mechanism for
tracking resources. To simplify things for users, Node.js abstracts away the
specific differences between operating systems and assigns all open files a
numeric file descriptor.</p>
<p>The <code>fs.open()</code> method is used to allocate a new file descriptor. Once
allocated, the file descriptor may be used to read data from, write data to,
or request information about the file.</p>
<pre><code class="language-js">fs.open('/open/some/file.txt', 'r', (err, fd) => {
  if (err) throw err;
  fs.fstat(fd, (err, stat) => {
    if (err) throw err;
    // use stat

    // always close the file descriptor!
    fs.close(fd, (err) => {
      if (err) throw err;
    });
  });
});
</code></pre>
<p>Most operating systems limit the number of file descriptors that may be open
at any given time so it is critical to close the descriptor when operations
are completed. Failure to do so will result in a memory leak that will
eventually cause an application to crash.</p>
<h2>Threadpool usage<span><a class="mark" href="#fs_threadpool_usage" id="fs_threadpool_usage">#</a></span></h2>
<p>All file system APIs except <code>fs.FSWatcher()</code> and those that are explicitly
synchronous use libuv's threadpool, which can have surprising and negative
performance implications for some applications. See the
<a href="#cli_uv_threadpool_size_size"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>
<h2>Class: <code>fs.Dir</code><span><a class="mark" href="#fs_class_fs_dir" id="fs_class_fs_dir">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<p>A class representing a directory stream.</p>
<p>Created by <a href="#fs_fs_opendir_path_options_callback"><code>fs.opendir()</code></a>, <a href="#fs_fs_opendirsync_path_options"><code>fs.opendirSync()</code></a>, or
<a href="#fs_fspromises_opendir_path_options"><code>fsPromises.opendir()</code></a>.</p>
<pre><code class="language-js">const fs = require('fs');

async function print(path) {
  const dir = await fs.promises.opendir(path);
  for await (const dirent of dir) {
    console.log(dirent.name);
  }
}
print('./').catch(console.error);
</code></pre>
<h3><code>dir.close()</code><span><a class="mark" href="#fs_dir_close" id="fs_dir_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronously close the directory's underlying resource handle.
Subsequent reads will result in errors.</p>
<p>A <code>Promise</code> is returned that will be resolved after the resource has been
closed.</p>
<h3><code>dir.close(callback)</code><span><a class="mark" href="#fs_dir_close_callback" id="fs_dir_close_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronously close the directory's underlying resource handle.
Subsequent reads will result in errors.</p>
<p>The <code>callback</code> will be called after the resource handle has been closed.</p>
<h3><code>dir.closeSync()</code><span><a class="mark" href="#fs_dir_closesync" id="fs_dir_closesync">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<p>Synchronously close the directory's underlying resource handle.
Subsequent reads will result in errors.</p>
<h3><code>dir.path</code><span><a class="mark" href="#fs_dir_path" id="fs_dir_path">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The read-only path of this directory as was provided to <a href="#fs_fs_opendir_path_options_callback"><code>fs.opendir()</code></a>,
<a href="#fs_fs_opendirsync_path_options"><code>fs.opendirSync()</code></a>, or <a href="#fs_fspromises_opendir_path_options"><code>fsPromises.opendir()</code></a>.</p>
<h3><code>dir.read()</code><span><a class="mark" href="#fs_dir_read" id="fs_dir_read">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> containing <a href="#fs_class_fs_dirent" class="type">&#x3C;fs.Dirent></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
</ul>
<p>Asynchronously read the next directory entry via <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> as an
<a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a>.</p>
<p>After the read is completed, a <code>Promise</code> is returned that will be resolved with
an <a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a>, or <code>null</code> if there are no more directory entries to read.</p>
<p>Directory entries returned by this function are in no particular order as
provided by the operating system's underlying directory mechanisms.
Entries added or removed while iterating over the directory may or may not be
included in the iteration results.</p>
<h3><code>dir.read(callback)</code><span><a class="mark" href="#fs_dir_read_callback" id="fs_dir_read_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>dirent</code> <a href="#fs_class_fs_dirent" class="type">&#x3C;fs.Dirent></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
</ul>
</li>
</ul>
<p>Asynchronously read the next directory entry via <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> as an
<a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a>.</p>
<p>After the read is completed, the <code>callback</code> will be called with an
<a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a>, or <code>null</code> if there are no more directory entries to read.</p>
<p>Directory entries returned by this function are in no particular order as
provided by the operating system's underlying directory mechanisms.
Entries added or removed while iterating over the directory may or may not be
included in the iteration results.</p>
<h3><code>dir.readSync()</code><span><a class="mark" href="#fs_dir_readsync" id="fs_dir_readsync">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li>Returns: <a href="#fs_class_fs_dirent" class="type">&#x3C;fs.Dirent></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
</ul>
<p>Synchronously read the next directory entry via <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> as an
<a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a>.</p>
<p>If there are no more directory entries to read, <code>null</code> will be returned.</p>
<p>Directory entries returned by this function are in no particular order as
provided by the operating system's underlying directory mechanisms.
Entries added or removed while iterating over the directory may or may not be
included in the iteration results.</p>
<h3><code>dir[Symbol.asyncIterator]()</code><span><a class="mark" href="#fs_dir_symbol_asynciterator" id="fs_dir_symbol_asynciterator">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type">&#x3C;AsyncIterator></a> of <a href="#fs_class_fs_dirent" class="type">&#x3C;fs.Dirent></a></li>
</ul>
<p>Asynchronously iterates over the directory via <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> until all entries have
been read.</p>
<p>Entries returned by the async iterator are always an <a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a>.
The <code>null</code> case from <code>dir.read()</code> is handled internally.</p>
<p>See <a href="#fs_class_fs_dir"><code>fs.Dir</code></a> for an example.</p>
<p>Directory entries returned by this iterator are in no particular order as
provided by the operating system's underlying directory mechanisms.
Entries added or removed while iterating over the directory may or may not be
included in the iteration results.</p>
<h2>Class: <code>fs.Dirent</code><span><a class="mark" href="#fs_class_fs_dirent" id="fs_class_fs_dirent">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<p>A representation of a directory entry, which can be a file or a subdirectory
within the directory, as returned by reading from an <a href="#fs_class_fs_dir"><code>fs.Dir</code></a>. The
directory entry is a combination of the file name and file type pairs.</p>
<p>Additionally, when <a href="#fs_fs_readdir_path_options_callback"><code>fs.readdir()</code></a> or <a href="#fs_fs_readdirsync_path_options"><code>fs.readdirSync()</code></a> is called with
the <code>withFileTypes</code> option set to <code>true</code>, the resulting array is filled with
<code>fs.Dirent</code> objects, rather than strings or <code>Buffers</code>.</p>
<h3><code>dirent.isBlockDevice()</code><span><a class="mark" href="#fs_dirent_isblockdevice" id="fs_dirent_isblockdevice">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a block device.</p>
<h3><code>dirent.isCharacterDevice()</code><span><a class="mark" href="#fs_dirent_ischaracterdevice" id="fs_dirent_ischaracterdevice">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a character device.</p>
<h3><code>dirent.isDirectory()</code><span><a class="mark" href="#fs_dirent_isdirectory" id="fs_dirent_isdirectory">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a file system
directory.</p>
<h3><code>dirent.isFIFO()</code><span><a class="mark" href="#fs_dirent_isfifo" id="fs_dirent_isfifo">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a first-in-first-out
(FIFO) pipe.</p>
<h3><code>dirent.isFile()</code><span><a class="mark" href="#fs_dirent_isfile" id="fs_dirent_isfile">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a regular file.</p>
<h3><code>dirent.isSocket()</code><span><a class="mark" href="#fs_dirent_issocket" id="fs_dirent_issocket">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a socket.</p>
<h3><code>dirent.isSymbolicLink()</code><span><a class="mark" href="#fs_dirent_issymboliclink" id="fs_dirent_issymboliclink">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Dirent</code> object describes a symbolic link.</p>
<h3><code>dirent.name</code><span><a class="mark" href="#fs_dirent_name" id="fs_dirent_name">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>The file name that this <code>fs.Dirent</code> object refers to. The type of this
value is determined by the <code>options.encoding</code> passed to <a href="#fs_fs_readdir_path_options_callback"><code>fs.readdir()</code></a> or
<a href="#fs_fs_readdirsync_path_options"><code>fs.readdirSync()</code></a>.</p>
<h2>Class: <code>fs.FSWatcher</code><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>
<ul>
<li>Extends <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<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 emit a <code>'change'</code> event whenever a specific watched
file is modified.</p>
<h3>Event: <code>'change'</code><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">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The filename that changed (if relevant/available)</li>
</ul>
<p>Emitted when something changes in a watched directory or file.
See more details in <a href="#fs_fs_watch_filename_options_listener"><code>fs.watch()</code></a>.</p>
<p>The <code>filename</code> argument may not be provided depending on operating system
support. If <code>filename</code> is provided, it will be provided as a <code>Buffer</code> if
<code>fs.watch()</code> is called with its <code>encoding</code> option set to <code>'buffer'</code>, otherwise
<code>filename</code> will be a UTF-8 string.</p>
<pre><code class="language-js">// Example when handled through fs.watch() listener
fs.watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
  if (filename) {
    console.log(filename);
    // Prints: &#x3C;Buffer ...>
  }
});
</code></pre>
<h3>Event: <code>'close'</code><span><a class="mark" href="#fs_event_close" id="fs_event_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>Emitted when the watcher stops watching for changes. The closed
<code>fs.FSWatcher</code> object is no longer usable in the event handler.</p>
<h3>Event: <code>'error'</code><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">&#x3C;Error></a></li>
</ul>
<p>Emitted when an error occurs while watching the file. The errored
<code>fs.FSWatcher</code> object is no longer usable in the event handler.</p>
<h3><code>watcher.close()</code><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: <code>fs.ReadStream</code><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>
<ul>
<li>Extends: <a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>A successful call to <code>fs.createReadStream()</code> will return a new <code>fs.ReadStream</code>
object.</p>
<h3>Event: <code>'close'</code><span><a class="mark" href="#fs_event_close_1" id="fs_event_close_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<p>Emitted when the <code>fs.ReadStream</code>'s underlying file descriptor has been closed.</p>
<h3>Event: <code>'open'</code><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">&#x3C;integer></a> Integer file descriptor used by the <code>ReadStream</code>.</li>
</ul>
<p>Emitted when the <code>fs.ReadStream</code>'s file descriptor has been opened.</p>
<h3>Event: <code>'ready'</code><span><a class="mark" href="#fs_event_ready" id="fs_event_ready">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.11.0</span>
</div>
<p>Emitted when the <code>fs.ReadStream</code> is ready to be used.</p>
<p>Fires immediately after <code>'open'</code>.</p>
<h3><code>readStream.bytesRead</code><span><a class="mark" href="#fs_readstream_bytesread" id="fs_readstream_bytesread">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The number of bytes that have been read so far.</p>
<h3><code>readStream.path</code><span><a class="mark" href="#fs_readstream_path" id="fs_readstream_path">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>The path to the file the stream is reading from as specified in the first
argument to <code>fs.createReadStream()</code>. If <code>path</code> is passed as a string, then
<code>readStream.path</code> will be a string. If <code>path</code> is passed as a <code>Buffer</code>, then
<code>readStream.path</code> will be a <code>Buffer</code>.</p>
<h3><code>readStream.pending</code><span><a class="mark" href="#fs_readstream_pending" id="fs_readstream_pending">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.2.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>This property is <code>true</code> if the underlying file has not been opened yet,
i.e. before the <code>'ready'</code> event is emitted.</p>
<h2>Class: <code>fs.Stats</code><span><a class="mark" href="#fs_class_fs_stats" id="fs_class_fs_stats">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.1.0</td>
<td><p>Added times as numbers.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>A <code>fs.Stats</code> object provides information about a file.</p>
<p>Objects returned from <a href="#fs_fs_stat_path_options_callback"><code>fs.stat()</code></a>, <a href="#fs_fs_lstat_path_options_callback"><code>fs.lstat()</code></a> and <a href="#fs_fs_fstat_fd_options_callback"><code>fs.fstat()</code></a> and
their synchronous counterparts are of this type.
If <code>bigint</code> in the <code>options</code> passed to those methods is true, the numeric values
will be <code>bigint</code> instead of <code>number</code>, and the object will contain additional
nanosecond-precision properties suffixed with <code>Ns</code>.</p>
<pre><code class="language-console">Stats {
  dev: 2114,
  ino: 48064969,
  mode: 33188,
  nlink: 1,
  uid: 85,
  gid: 100,
  rdev: 0,
  size: 527,
  blksize: 4096,
  blocks: 8,
  atimeMs: 1318289051000.1,
  mtimeMs: 1318289051000.1,
  ctimeMs: 1318289051000.1,
  birthtimeMs: 1318289051000.1,
  atime: Mon, 10 Oct 2011 23:24:11 GMT,
  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
</code></pre>
<p><code>bigint</code> version:</p>
<pre><code class="language-console">BigIntStats {
  dev: 2114n,
  ino: 48064969n,
  mode: 33188n,
  nlink: 1n,
  uid: 85n,
  gid: 100n,
  rdev: 0n,
  size: 527n,
  blksize: 4096n,
  blocks: 8n,
  atimeMs: 1318289051000n,
  mtimeMs: 1318289051000n,
  ctimeMs: 1318289051000n,
  birthtimeMs: 1318289051000n,
  atimeNs: 1318289051000000000n,
  mtimeNs: 1318289051000000000n,
  ctimeNs: 1318289051000000000n,
  birthtimeNs: 1318289051000000000n,
  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><code>stats.isBlockDevice()</code><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">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a block device.</p>
<h3><code>stats.isCharacterDevice()</code><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">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a character device.</p>
<h3><code>stats.isDirectory()</code><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">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a file system directory.</p>
<h3><code>stats.isFIFO()</code><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">&#x3C;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><code>stats.isFile()</code><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">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a regular file.</p>
<h3><code>stats.isSocket()</code><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">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a socket.</p>
<h3><code>stats.isSymbolicLink()</code><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">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>fs.Stats</code> object describes a symbolic link.</p>
<p>This method is only valid when using <a href="#fs_fs_lstat_path_options_callback"><code>fs.lstat()</code></a>.</p>
<h3><code>stats.dev</code><span><a class="mark" href="#fs_stats_dev" id="fs_stats_dev">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The numeric identifier of the device containing the file.</p>
<h3><code>stats.ino</code><span><a class="mark" href="#fs_stats_ino" id="fs_stats_ino">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The file system specific "Inode" number for the file.</p>
<h3><code>stats.mode</code><span><a class="mark" href="#fs_stats_mode" id="fs_stats_mode">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>A bit-field describing the file type and mode.</p>
<h3><code>stats.nlink</code><span><a class="mark" href="#fs_stats_nlink" id="fs_stats_nlink">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The number of hard-links that exist for the file.</p>
<h3><code>stats.uid</code><span><a class="mark" href="#fs_stats_uid" id="fs_stats_uid">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The numeric user identifier of the user that owns the file (POSIX).</p>
<h3><code>stats.gid</code><span><a class="mark" href="#fs_stats_gid" id="fs_stats_gid">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The numeric group identifier of the group that owns the file (POSIX).</p>
<h3><code>stats.rdev</code><span><a class="mark" href="#fs_stats_rdev" id="fs_stats_rdev">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>A numeric device identifier if the file is considered "special".</p>
<h3><code>stats.size</code><span><a class="mark" href="#fs_stats_size" id="fs_stats_size">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The size of the file in bytes.</p>
<h3><code>stats.blksize</code><span><a class="mark" href="#fs_stats_blksize" id="fs_stats_blksize">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The file system block size for i/o operations.</p>
<h3><code>stats.blocks</code><span><a class="mark" href="#fs_stats_blocks" id="fs_stats_blocks">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The number of blocks allocated for this file.</p>
<h3><code>stats.atimeMs</code><span><a class="mark" href="#fs_stats_atimems" id="fs_stats_atimems">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The timestamp indicating the last time this file was accessed expressed in
milliseconds since the POSIX Epoch.</p>
<h3><code>stats.mtimeMs</code><span><a class="mark" href="#fs_stats_mtimems" id="fs_stats_mtimems">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The timestamp indicating the last time this file was modified expressed in
milliseconds since the POSIX Epoch.</p>
<h3><code>stats.ctimeMs</code><span><a class="mark" href="#fs_stats_ctimems" id="fs_stats_ctimems">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The timestamp indicating the last time the file status was changed expressed
in milliseconds since the POSIX Epoch.</p>
<h3><code>stats.birthtimeMs</code><span><a class="mark" href="#fs_stats_birthtimems" id="fs_stats_birthtimems">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The timestamp indicating the creation time of this file expressed in
milliseconds since the POSIX Epoch.</p>
<h3><code>stats.atimeNs</code><span><a class="mark" href="#fs_stats_atimens" id="fs_stats_atimens">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>Only present when <code>bigint: true</code> is passed into the method that generates
the object.
The timestamp indicating the last time this file was accessed expressed in
nanoseconds since the POSIX Epoch.</p>
<h3><code>stats.mtimeNs</code><span><a class="mark" href="#fs_stats_mtimens" id="fs_stats_mtimens">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>Only present when <code>bigint: true</code> is passed into the method that generates
the object.
The timestamp indicating the last time this file was modified expressed in
nanoseconds since the POSIX Epoch.</p>
<h3><code>stats.ctimeNs</code><span><a class="mark" href="#fs_stats_ctimens" id="fs_stats_ctimens">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>Only present when <code>bigint: true</code> is passed into the method that generates
the object.
The timestamp indicating the last time the file status was changed expressed
in nanoseconds since the POSIX Epoch.</p>
<h3><code>stats.birthtimeNs</code><span><a class="mark" href="#fs_stats_birthtimens" id="fs_stats_birthtimens">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>Only present when <code>bigint: true</code> is passed into the method that generates
the object.
The timestamp indicating the creation time of this file expressed in
nanoseconds since the POSIX Epoch.</p>
<h3><code>stats.atime</code><span><a class="mark" href="#fs_stats_atime" id="fs_stats_atime">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
</ul>
<p>The timestamp indicating the last time this file was accessed.</p>
<h3><code>stats.mtime</code><span><a class="mark" href="#fs_stats_mtime" id="fs_stats_mtime">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
</ul>
<p>The timestamp indicating the last time this file was modified.</p>
<h3><code>stats.ctime</code><span><a class="mark" href="#fs_stats_ctime" id="fs_stats_ctime">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
</ul>
<p>The timestamp indicating the last time the file status was changed.</p>
<h3><code>stats.birthtime</code><span><a class="mark" href="#fs_stats_birthtime" id="fs_stats_birthtime">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;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
numeric values that hold the corresponding times in milliseconds. Their
precision is platform specific. When <code>bigint: true</code> is passed into the
method that generates the object, the properties will be <a href="https://tc39.github.io/proposal-bigint">bigints</a>,
otherwise they will be <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type">numbers</a>.</p>
<p>The <code>atimeNs</code>, <code>mtimeNs</code>, <code>ctimeNs</code>, <code>birthtimeNs</code> properties are
<a href="https://tc39.github.io/proposal-bigint">bigints</a> that hold the corresponding times in nanoseconds. They are
only present when <code>bigint: true</code> is passed into the method that generates
the object. Their precision is platform specific.</p>
<p><code>atime</code>, <code>mtime</code>, <code>ctime</code>, and <code>birthtime</code> are
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date"><code>Date</code></a> object alternate representations of the various times. The
<code>Date</code> and number values are not connected. Assigning a new number value, or
mutating the <code>Date</code> value, will not be reflected in the corresponding alternate
representation.</p>
<p>The times in the stat object have the following semantics:</p>
<ul>
<li><code>atime</code> "Access Time": Time when file data last accessed. Changed
by the <a href="http://man7.org/linux/man-pages/man2/mknod.2.html"><code>mknod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a>, and <a href="http://man7.org/linux/man-pages/man2/read.2.html"><code>read(2)</code></a> system calls.</li>
<li><code>mtime</code> "Modified Time": Time when file data last modified.
Changed by the <a href="http://man7.org/linux/man-pages/man2/mknod.2.html"><code>mknod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a>, and <a href="http://man7.org/linux/man-pages/man2/write.2.html"><code>write(2)</code></a> system calls.</li>
<li><code>ctime</code> "Change Time": Time when file status was last changed
(inode data modification). Changed by the <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a>,
<a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/mknod.2.html"><code>mknod(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/rename.2.html"><code>rename(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a>,
<a href="http://man7.org/linux/man-pages/man2/read.2.html"><code>read(2)</code></a>, and <a href="http://man7.org/linux/man-pages/man2/write.2.html"><code>write(2)</code></a> system calls.</li>
<li><code>birthtime</code> "Birth Time": Time of file creation. Set once when the
file is created. On filesystems where birthtime is not available,
this field may instead hold either the <code>ctime</code> or
<code>1970-01-01T00:00Z</code> (ie, Unix epoch timestamp <code>0</code>). This value may be greater
than <code>atime</code> or <code>mtime</code> in this case. On Darwin and other FreeBSD variants,
also set if the <code>atime</code> is explicitly set to an earlier value than the current
<code>birthtime</code> using the <a href="http://man7.org/linux/man-pages/man2/utimes.2.html"><code>utimes(2)</code></a> system call.</li>
</ul>
<p>Prior to Node.js 0.12, the <code>ctime</code> held the <code>birthtime</code> on Windows systems. As
of 0.12, <code>ctime</code> is not "creation time", and on Unix systems, it never was.</p>
<h2>Class: <code>fs.WriteStream</code><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>
<ul>
<li>Extends <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a></li>
</ul>
<h3>Event: <code>'close'</code><span><a class="mark" href="#fs_event_close_2" id="fs_event_close_2">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<p>Emitted when the <code>WriteStream</code>'s underlying file descriptor has been closed.</p>
<h3>Event: <code>'open'</code><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">&#x3C;integer></a> Integer file descriptor used by the <code>WriteStream</code>.</li>
</ul>
<p>Emitted when the <code>WriteStream</code>'s file is opened.</p>
<h3>Event: <code>'ready'</code><span><a class="mark" href="#fs_event_ready_1" id="fs_event_ready_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.11.0</span>
</div>
<p>Emitted when the <code>fs.WriteStream</code> is ready to be used.</p>
<p>Fires immediately after <code>'open'</code>.</p>
<h3><code>writeStream.bytesWritten</code><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><code>writeStream.path</code><span><a class="mark" href="#fs_writestream_path" id="fs_writestream_path">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<p>The path to the file the stream is writing to as specified in the first
argument to <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a>. If <code>path</code> is passed as a string, then
<code>writeStream.path</code> will be a string. If <code>path</code> is passed as a <code>Buffer</code>, then
<code>writeStream.path</code> will be a <code>Buffer</code>.</p>
<h3><code>writeStream.pending</code><span><a class="mark" href="#fs_writestream_pending" id="fs_writestream_pending">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.2.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>This property is <code>true</code> if the underlying file has not been opened yet,
i.e. before the <code>'ready'</code> event is emitted.</p>
<h2><code>fs.access(path[, mode], callback)</code><span><a class="mark" href="#fs_fs_access_path_mode_callback" id="fs_fs_access_path_mode_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The constants like <code>fs.R_OK</code>, etc which were present directly on <code>fs</code> were moved into <code>fs.constants</code> as a soft deprecation. Thus for Node.js <code>&#x3C; v6.3.0</code> use <code>fs</code> to access those constants, or do something like <code>(fs.constants || fs).R_OK</code> to work with all versions.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>fs.constants.F_OK</code></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Tests a user's permissions for the file or directory specified by <code>path</code>.
The <code>mode</code> argument is an optional integer that specifies the accessibility
checks to be performed. Check <a href="#fs_file_access_constants">File access constants</a> for possible values
of <code>mode</code>. It is possible to create a mask consisting of the bitwise OR of
two or more values (e.g. <code>fs.constants.W_OK | fs.constants.R_OK</code>).</p>
<p>The final argument, <code>callback</code>, is a callback function that is invoked with
a possible error argument. If any of the accessibility checks fail, the error
argument will be an <code>Error</code> object. The following examples check if
<code>package.json</code> exists, and if it is readable or writable.</p>
<pre><code class="language-js">const file = 'package.json';

// Check if the file exists in the current directory.
fs.access(file, fs.constants.F_OK, (err) => {
  console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});

// Check if the file is readable.
fs.access(file, fs.constants.R_OK, (err) => {
  console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});

// Check if the file is writable.
fs.access(file, fs.constants.W_OK, (err) => {
  console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
});

// Check if the file exists in the current directory, and if it is writable.
fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
  if (err) {
    console.error(
      `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
  } else {
    console.log(`${file} exists, and it is writable`);
  }
});
</code></pre>
<p>Using <code>fs.access()</code> to check for the accessibility of a file before calling
<code>fs.open()</code>, <code>fs.readFile()</code> or <code>fs.writeFile()</code> is not recommended. Doing
so introduces a race condition, since other processes may change the file's
state between the two calls. Instead, user code should open/read/write the
file directly and handle the error raised if the file is not accessible.</p>
<p><strong>write (NOT RECOMMENDED)</strong></p>
<pre><code class="language-js">fs.access('myfile', (err) => {
  if (!err) {
    console.error('myfile already exists');
    return;
  }

  fs.open('myfile', 'wx', (err, fd) => {
    if (err) throw err;
    writeMyData(fd);
  });
});
</code></pre>
<p><strong>write (RECOMMENDED)</strong></p>
<pre><code class="language-js">fs.open('myfile', 'wx', (err, fd) => {
  if (err) {
    if (err.code === 'EEXIST') {
      console.error('myfile already exists');
      return;
    }

    throw err;
  }

  writeMyData(fd);
});
</code></pre>
<p><strong>read (NOT RECOMMENDED)</strong></p>
<pre><code class="language-js">fs.access('myfile', (err) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.error('myfile does not exist');
      return;
    }

    throw err;
  }

  fs.open('myfile', 'r', (err, fd) => {
    if (err) throw err;
    readMyData(fd);
  });
});
</code></pre>
<p><strong>read (RECOMMENDED)</strong></p>
<pre><code class="language-js">fs.open('myfile', 'r', (err, fd) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.error('myfile does not exist');
      return;
    }

    throw err;
  }

  readMyData(fd);
});
</code></pre>
<p>The "not recommended" examples above check for accessibility and then use the
file; the "recommended" examples are better because they use the file directly
and handle the error, if any.</p>
<p>In general, check for the accessibility of a file only if the file will not be
used directly, for example when its accessibility is a signal from another
process.</p>
<p>On Windows, access-control policies (ACLs) on a directory may limit access to
a file or directory. The <code>fs.access()</code> function, however, does not check the
ACL and therefore may report that a path is accessible even if the ACL restricts
the user from reading or writing to it.</p>
<h2><code>fs.accessSync(path[, mode])</code><span><a class="mark" href="#fs_fs_accesssync_path_mode" id="fs_fs_accesssync_path_mode">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>fs.constants.F_OK</code></li>
</ul>
<p>Synchronously tests a user's permissions for the file or directory specified
by <code>path</code>. The <code>mode</code> argument is an optional integer that specifies the
accessibility checks to be performed. Check <a href="#fs_file_access_constants">File access constants</a> for
possible values of <code>mode</code>. It is possible to create a mask consisting of
the bitwise OR of two or more values
(e.g. <code>fs.constants.W_OK | fs.constants.R_OK</code>).</p>
<p>If any of the accessibility checks fail, an <code>Error</code> will be thrown. Otherwise,
the method will return <code>undefined</code>.</p>
<pre><code class="language-js">try {
  fs.accessSync('etc/passwd', fs.constants.R_OK | fs.constants.W_OK);
  console.log('can read/write');
} catch (err) {
  console.error('no access!');
}
</code></pre>
<h2><code>fs.appendFile(path, data[, options], callback)</code><span><a class="mark" href="#fs_fs_appendfile_path_data_options_callback" id="fs_fs_appendfile_path_data_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The passed <code>options</code> object will never be modified.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.6.7</td>
<td><p><span>Added in: v0.6.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;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">&#x3C;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">&#x3C;string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronously append data to a file, creating the file if it does not yet
exist. <code>data</code> can be a string or a <a href="#buffer_buffer"><code>Buffer</code></a>.</p>
<pre><code class="language-js">fs.appendFile('message.txt', 'data to append', (err) => {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
});
</code></pre>
<p>If <code>options</code> is a string, then it specifies the encoding:</p>
<pre><code class="language-js">fs.appendFile('message.txt', 'data to append', 'utf8', callback);
</code></pre>
<p>The <code>path</code> may be specified as a numeric file descriptor that has been opened
for appending (using <code>fs.open()</code> or <code>fs.openSync()</code>). The file descriptor will
not be closed automatically.</p>
<pre><code class="language-js">fs.open('message.txt', 'a', (err, fd) => {
  if (err) throw err;
  fs.appendFile(fd, 'data to append', 'utf8', (err) => {
    fs.close(fd, (err) => {
      if (err) throw err;
    });
    if (err) throw err;
  });
});
</code></pre>
<h2><code>fs.appendFileSync(path, data[, options])</code><span><a class="mark" href="#fs_fs_appendfilesync_path_data_options" id="fs_fs_appendfilesync_path_data_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>The passed <code>options</code> object will never be modified.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.6.7</td>
<td><p><span>Added in: v0.6.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;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">&#x3C;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">&#x3C;string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li>
</ul>
</li>
</ul>
<p>Synchronously append data to a file, creating the file if it does not yet
exist. <code>data</code> can be a string or a <a href="#buffer_buffer"><code>Buffer</code></a>.</p>
<pre><code class="language-js">try {
  fs.appendFileSync('message.txt', 'data to append');
  console.log('The "data to append" was appended to file!');
} catch (err) {
  /* Handle the error */
}
</code></pre>
<p>If <code>options</code> is a string, then it specifies the encoding:</p>
<pre><code class="language-js">fs.appendFileSync('message.txt', 'data to append', 'utf8');
</code></pre>
<p>The <code>path</code> may be specified as a numeric file descriptor that has been opened
for appending (using <code>fs.open()</code> or <code>fs.openSync()</code>). The file descriptor will
not be closed automatically.</p>
<pre><code class="language-js">let fd;

try {
  fd = fs.openSync('message.txt', 'a');
  fs.appendFileSync(fd, 'data to append', 'utf8');
} catch (err) {
  /* Handle the error */
} finally {
  if (fd !== undefined)
    fs.closeSync(fd);
}
</code></pre>
<h2><code>fs.chmod(path, mode, callback)</code><span><a class="mark" href="#fs_fs_chmod_path_mode_callback" id="fs_fs_chmod_path_mode_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.30</td>
<td><p><span>Added in: v0.1.30</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronously changes the permissions of a file. No arguments other than a
possible exception are given to the completion callback.</p>
<p>See also: <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a>.</p>
<pre><code class="language-js">fs.chmod('my_file.txt', 0o775, (err) => {
  if (err) throw err;
  console.log('The permissions for file "my_file.txt" have been changed!');
});
</code></pre>
<h3>File modes<span><a class="mark" href="#fs_file_modes" id="fs_file_modes">#</a></span></h3>
<p>The <code>mode</code> argument used in both the <code>fs.chmod()</code> and <code>fs.chmodSync()</code>
methods is a numeric bitmask created using a logical OR of the following
constants:</p>























































<table><thead><tr><th>Constant</th><th>Octal</th><th>Description</th></tr></thead><tbody><tr><td><code>fs.constants.S_IRUSR</code></td><td><code>0o400</code></td><td>read by owner</td></tr><tr><td><code>fs.constants.S_IWUSR</code></td><td><code>0o200</code></td><td>write by owner</td></tr><tr><td><code>fs.constants.S_IXUSR</code></td><td><code>0o100</code></td><td>execute/search by owner</td></tr><tr><td><code>fs.constants.S_IRGRP</code></td><td><code>0o40</code></td><td>read by group</td></tr><tr><td><code>fs.constants.S_IWGRP</code></td><td><code>0o20</code></td><td>write by group</td></tr><tr><td><code>fs.constants.S_IXGRP</code></td><td><code>0o10</code></td><td>execute/search by group</td></tr><tr><td><code>fs.constants.S_IROTH</code></td><td><code>0o4</code></td><td>read by others</td></tr><tr><td><code>fs.constants.S_IWOTH</code></td><td><code>0o2</code></td><td>write by others</td></tr><tr><td><code>fs.constants.S_IXOTH</code></td><td><code>0o1</code></td><td>execute/search by others</td></tr></tbody></table>
<p>An easier method of constructing the <code>mode</code> is to use a sequence of three
octal digits (e.g. <code>765</code>). The left-most digit (<code>7</code> in the example), specifies
the permissions for the file owner. The middle digit (<code>6</code> in the example),
specifies permissions for the group. The right-most digit (<code>5</code> in the example),
specifies the permissions for others.</p>









































<table><thead><tr><th>Number</th><th>Description</th></tr></thead><tbody><tr><td><code>7</code></td><td>read, write, and execute</td></tr><tr><td><code>6</code></td><td>read and write</td></tr><tr><td><code>5</code></td><td>read and execute</td></tr><tr><td><code>4</code></td><td>read only</td></tr><tr><td><code>3</code></td><td>write and execute</td></tr><tr><td><code>2</code></td><td>write only</td></tr><tr><td><code>1</code></td><td>execute only</td></tr><tr><td><code>0</code></td><td>no permission</td></tr></tbody></table>
<p>For example, the octal value <code>0o765</code> means:</p>
<ul>
<li>The owner may read, write and execute the file.</li>
<li>The group may read and write the file.</li>
<li>Others may read and execute the file.</li>
</ul>
<p>When using raw numbers where file modes are expected, any value larger than
<code>0o777</code> may result in platform-specific behaviors that are not supported to work
consistently. Therefore constants like <code>S_ISVTX</code>, <code>S_ISGID</code> or <code>S_ISUID</code> are not
exposed in <code>fs.constants</code>.</p>
<p>Caveats: on Windows only the write permission can be changed, and the
distinction among the permissions of group, owner or others is not
implemented.</p>
<h2><code>fs.chmodSync(path, mode)</code><span><a class="mark" href="#fs_fs_chmodsync_path_mode" id="fs_fs_chmodsync_path_mode">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.6.7</td>
<td><p><span>Added in: v0.6.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_chmod_path_mode_callback"><code>fs.chmod()</code></a>.</p>
<p>See also: <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a>.</p>
<h2><code>fs.chown(path, uid, gid, callback)</code><span><a class="mark" href="#fs_fs_chown_path_uid_gid_callback" id="fs_fs_chown_path_uid_gid_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.97</td>
<td><p><span>Added in: v0.1.97</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronously changes owner and group of a file. No arguments other than a
possible exception are given to the completion callback.</p>
<p>See also: <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a>.</p>
<h2><code>fs.chownSync(path, uid, gid)</code><span><a class="mark" href="#fs_fs_chownsync_path_uid_gid" id="fs_fs_chownsync_path_uid_gid">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.97</td>
<td><p><span>Added in: v0.1.97</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Synchronously changes owner and group of a file. Returns <code>undefined</code>.
This is the synchronous version of <a href="#fs_fs_chown_path_uid_gid_callback"><code>fs.chown()</code></a>.</p>
<p>See also: <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a>.</p>
<h2><code>fs.close(fd, callback)</code><span><a class="mark" href="#fs_fs_close_fd_callback" id="fs_fs_close_fd_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/close.2.html"><code>close(2)</code></a>. No arguments other than a possible exception are given
to the completion callback.</p>
<p>Calling <code>fs.close()</code> on any file descriptor (<code>fd</code>) that is currently in use
through any other <code>fs</code> operation may lead to undefined behavior.</p>
<h2><code>fs.closeSync(fd)</code><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">&#x3C;integer></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/close.2.html"><code>close(2)</code></a>. Returns <code>undefined</code>.</p>
<p>Calling <code>fs.closeSync()</code> on any file descriptor (<code>fd</code>) that is currently in use
through any other <code>fs</code> operation may lead to undefined behavior.</p>
<h2><code>fs.constants</code><span><a class="mark" href="#fs_fs_constants" id="fs_fs_constants">#</a></span></h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns an object containing commonly used constants for file system
operations. The specific constants currently defined are described in
<a href="#fs_fs_constants_1">FS constants</a>.</p>
<h2><code>fs.copyFile(src, dest[, flags], callback)</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;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">&#x3C;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">&#x3C;Function></a></li>
</ul>
<p>Asynchronously copies <code>src</code> to <code>dest</code>. By default, <code>dest</code> is overwritten if it
already exists. No arguments other than a possible exception are given to the
callback function. Node.js makes no guarantees about the atomicity of the copy
operation. If an error occurs after the destination file has been opened for
writing, Node.js will attempt to remove the destination.</p>
<p><code>flags</code> is an optional integer that specifies the behavior
of the copy operation. It is possible to create a mask consisting of the bitwise
OR of two or more values (e.g.
<code>fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE</code>).</p>
<ul>
<li><code>fs.constants.COPYFILE_EXCL</code>: The copy operation will fail if <code>dest</code> already
exists.</li>
<li><code>fs.constants.COPYFILE_FICLONE</code>: The copy operation will attempt to create a
copy-on-write reflink. If the platform does not support copy-on-write, then a
fallback copy mechanism is used.</li>
<li><code>fs.constants.COPYFILE_FICLONE_FORCE</code>: The copy operation will attempt to
create a copy-on-write reflink. If the platform does not support copy-on-write,
then the operation will fail.</li>
</ul>
<pre><code class="language-js">const fs = require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFile('source.txt', 'destination.txt', (err) => {
  if (err) throw err;
  console.log('source.txt was copied to destination.txt');
});
</code></pre>
<p>If the third argument is a number, then it specifies <code>flags</code>:</p>
<pre><code class="language-js">const fs = require('fs');
const { COPYFILE_EXCL } = fs.constants;

// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
fs.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL, callback);
</code></pre>
<h2><code>fs.copyFileSync(src, dest[, flags])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;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">&#x3C;number></a> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.</li>
</ul>
<p>Synchronously copies <code>src</code> to <code>dest</code>. By default, <code>dest</code> is overwritten if it
already exists. Returns <code>undefined</code>. Node.js makes no guarantees about the
atomicity of the copy operation. If an error occurs after the destination file
has been opened for writing, Node.js will attempt to remove the destination.</p>
<p><code>flags</code> is an optional integer that specifies the behavior
of the copy operation. It is possible to create a mask consisting of the bitwise
OR of two or more values (e.g.
<code>fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE</code>).</p>
<ul>
<li><code>fs.constants.COPYFILE_EXCL</code>: The copy operation will fail if <code>dest</code> already
exists.</li>
<li><code>fs.constants.COPYFILE_FICLONE</code>: The copy operation will attempt to create a
copy-on-write reflink. If the platform does not support copy-on-write, then a
fallback copy mechanism is used.</li>
<li><code>fs.constants.COPYFILE_FICLONE_FORCE</code>: The copy operation will attempt to
create a copy-on-write reflink. If the platform does not support copy-on-write,
then the operation will fail.</li>
</ul>
<pre><code class="language-js">const fs = require('fs');

// destination.txt will be created or overwritten by default.
fs.copyFileSync('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
</code></pre>
<p>If the third argument is a number, then it specifies <code>flags</code>:</p>
<pre><code class="language-js">const fs = require('fs');
const { COPYFILE_EXCL } = fs.constants;

// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
fs.copyFileSync('source.txt', 'destination.txt', COPYFILE_EXCL);
</code></pre>
<h2><code>fs.createReadStream(path[, options])</code><span><a class="mark" href="#fs_fs_createreadstream_path_options" id="fs_fs_createreadstream_path_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>The <code>fs</code> options allow overriding the used <code>fs</code> implementation.</p></td></tr>
<tr><td>v12.10.0</td>
<td><p>Enable <code>emitClose</code> option.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Impose new restrictions on <code>start</code> and <code>end</code>, throwing more appropriate errors in cases when we cannot reasonably handle the input values.</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 passed <code>options</code> object will never be modified.</p></td></tr>
<tr><td>v2.3.0</td>
<td><p>The passed <code>options</code> object can be a string now.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong>
<code>'r'</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>null</code></li>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>null</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>0o666</code></li>
<li><code>autoClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>true</code></li>
<li><code>emitClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>Infinity</code></li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>64 * 1024</code></li>
<li><code>fs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> <strong>Default:</strong> <code>null</code></li>
</ul>
</li>
<li>Returns: <a href="#fs_class_fs_readstream" class="type">&#x3C;fs.ReadStream></a> See <a href="#stream_class_stream_readable">Readable Stream</a>.</li>
</ul>
<p>Unlike the 16 kb default <code>highWaterMark</code> for a readable stream, the stream
returned by this method has a default <code>highWaterMark</code> of 64 kb.</p>
<p><code>options</code> can include <code>start</code> and <code>end</code> values to read a range of bytes from
the file instead of the entire file. Both <code>start</code> and <code>end</code> are inclusive and
start counting at 0, allowed values are in the
[0, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER"><code>Number.MAX_SAFE_INTEGER</code></a>] range. If <code>fd</code> is specified and <code>start</code> is
omitted or <code>undefined</code>, <code>fs.createReadStream()</code> reads sequentially from the
current file position. The <code>encoding</code> can be any one of those accepted by
<a href="#buffer_buffer"><code>Buffer</code></a>.</p>
<p>If <code>fd</code> is specified, <code>ReadStream</code> will ignore the <code>path</code> argument and will use
the specified file descriptor. This means that no <code>'open'</code> event will be
emitted. <code>fd</code> should be blocking; non-blocking <code>fd</code>s should be passed to
<a href="#net_class_net_socket"><code>net.Socket</code></a>.</p>
<p>If <code>fd</code> points to a character device that only supports blocking reads
(such as keyboard or sound card), read operations do not finish until data is
available. This can prevent the process from exiting and the stream from
closing naturally.</p>
<p>By default, the stream will not emit a <code>'close'</code> event after it has been
destroyed. This is the opposite of the default for other <code>Readable</code> streams.
Set the <code>emitClose</code> option to <code>true</code> to change this behavior.</p>
<p>By providing the <code>fs</code> option, it is possible to override the corresponding <code>fs</code>
implementations for <code>open</code>, <code>read</code>, and <code>close</code>. When providing the <code>fs</code> option,
overrides for <code>open</code>, <code>read</code>, and <code>close</code> are required.</p>
<pre><code class="language-js">const fs = require('fs');
// Create a stream from some character device.
const stream = fs.createReadStream('/dev/input/event0');
setTimeout(() => {
  stream.close(); // This may not close the stream.
  // Artificially marking end-of-stream, as if the underlying resource had
  // indicated end-of-file by itself, allows the stream to close.
  // This does not cancel pending read operations, and if there is such an
  // operation, the process may still not be able to exit successfully
  // until it finishes.
  stream.push(null);
  stream.read(0);
}, 100);
</code></pre>
<p>If <code>autoClose</code> is false, then the file descriptor won't be closed, even if
there's an error. It is the application's responsibility to close it and make
sure there's no file descriptor leak. If <code>autoClose</code> is set to true (default
behavior), on <code>'error'</code> or <code>'end'</code> the file descriptor will be closed
automatically.</p>
<p><code>mode</code> sets the file mode (permission and sticky bits), but only if the
file was created.</p>
<p>An example to read the last 10 bytes of a file which is 100 bytes long:</p>
<pre><code class="language-js">fs.createReadStream('sample.txt', { start: 90, end: 99 });
</code></pre>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<h2><code>fs.createWriteStream(path[, options])</code><span><a class="mark" href="#fs_fs_createwritestream_path_options" id="fs_fs_createwritestream_path_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>The <code>fs</code> options allow overriding the used <code>fs</code> implementation.</p></td></tr>
<tr><td>v12.10.0</td>
<td><p>Enable <code>emitClose</code> option.</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 passed <code>options</code> object will never be modified.</p></td></tr>
<tr><td>v5.5.0</td>
<td><p>The <code>autoClose</code> option is supported now.</p></td></tr>
<tr><td>v2.3.0</td>
<td><p>The passed <code>options</code> object can be a string now.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong>
<code>'w'</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>null</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>0o666</code></li>
<li><code>autoClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>true</code></li>
<li><code>emitClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>fs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> <strong>Default:</strong> <code>null</code></li>
</ul>
</li>
<li>Returns: <a href="#fs_class_fs_writestream" class="type">&#x3C;fs.WriteStream></a> See <a href="#stream_class_stream_writable">Writable Stream</a>.</li>
</ul>
<p><code>options</code> may also include a <code>start</code> option to allow writing data at
some position past the beginning of the file, allowed values are in the
[0, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER"><code>Number.MAX_SAFE_INTEGER</code></a>] range. Modifying a file rather
than replacing it may require a <code>flags</code> mode of <code>r+</code> rather than the
default mode <code>w</code>. The <code>encoding</code> can be any one of those accepted by
<a href="#buffer_buffer"><code>Buffer</code></a>.</p>
<p>If <code>autoClose</code> is set to true (default behavior) on <code>'error'</code> or <code>'finish'</code>
the file descriptor will be closed automatically. If <code>autoClose</code> is false,
then the file descriptor won't be closed, even if there's an error.
It is the application's responsibility to close it and make sure there's no
file descriptor leak.</p>
<p>By default, the stream will not emit a <code>'close'</code> event after it has been
destroyed. This is the opposite of the default for other <code>Writable</code> streams.
Set the <code>emitClose</code> option to <code>true</code> to change this behavior.</p>
<p>By providing the <code>fs</code> option it is possible to override the corresponding <code>fs</code>
implementations for <code>open</code>, <code>write</code>, <code>writev</code> and <code>close</code>. Overriding <code>write()</code>
without <code>writev()</code> can reduce performance as some optimizations (<code>_writev()</code>)
will be disabled. When providing the <code>fs</code> option,  overrides for <code>open</code>,
<code>close</code>, and at least one of <code>write</code> and <code>writev</code> are required.</p>
<p>Like <a href="#fs_class_fs_readstream"><code>ReadStream</code></a>, if <code>fd</code> is specified, <a href="#fs_class_fs_writestream"><code>WriteStream</code></a> will ignore the
<code>path</code> argument and will use the specified file descriptor. This means that no
<code>'open'</code> event will be emitted. <code>fd</code> should be blocking; non-blocking <code>fd</code>s
should be passed to <a href="#net_class_net_socket"><code>net.Socket</code></a>.</p>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<h2><code>fs.exists(path, callback)</code><span><a class="mark" href="#fs_fs_exists_path_callback" id="fs_fs_exists_path_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p><span>Deprecated since: v1.0.0</span></p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#fs_fs_stat_path_options_callback"><code>fs.stat()</code></a> or <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a> instead.</div><p></p>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>exists</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
</li>
</ul>
<p>Test whether or not the given path exists by checking with the file system.
Then call the <code>callback</code> argument with either true or false:</p>
<pre><code class="language-js">fs.exists('/etc/passwd', (exists) => {
  console.log(exists ? 'it\'s there' : 'no passwd!');
});
</code></pre>
<p><strong>The parameters for this callback are not consistent with other Node.js
callbacks.</strong> Normally, the first parameter to a Node.js callback is an <code>err</code>
parameter, optionally followed by other parameters. The <code>fs.exists()</code> callback
has only one boolean parameter. This is one reason <code>fs.access()</code> is recommended
instead of <code>fs.exists()</code>.</p>
<p>Using <code>fs.exists()</code> to check for the existence of a file before calling
<code>fs.open()</code>, <code>fs.readFile()</code> or <code>fs.writeFile()</code> is not recommended. Doing
so introduces a race condition, since other processes may change the file's
state between the two calls. Instead, user code should open/read/write the
file directly and handle the error raised if the file does not exist.</p>
<p><strong>write (NOT RECOMMENDED)</strong></p>
<pre><code class="language-js">fs.exists('myfile', (exists) => {
  if (exists) {
    console.error('myfile already exists');
  } else {
    fs.open('myfile', 'wx', (err, fd) => {
      if (err) throw err;
      writeMyData(fd);
    });
  }
});
</code></pre>
<p><strong>write (RECOMMENDED)</strong></p>
<pre><code class="language-js">fs.open('myfile', 'wx', (err, fd) => {
  if (err) {
    if (err.code === 'EEXIST') {
      console.error('myfile already exists');
      return;
    }

    throw err;
  }

  writeMyData(fd);
});
</code></pre>
<p><strong>read (NOT RECOMMENDED)</strong></p>
<pre><code class="language-js">fs.exists('myfile', (exists) => {
  if (exists) {
    fs.open('myfile', 'r', (err, fd) => {
      if (err) throw err;
      readMyData(fd);
    });
  } else {
    console.error('myfile does not exist');
  }
});
</code></pre>
<p><strong>read (RECOMMENDED)</strong></p>
<pre><code class="language-js">fs.open('myfile', 'r', (err, fd) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.error('myfile does not exist');
      return;
    }

    throw err;
  }

  readMyData(fd);
});
</code></pre>
<p>The "not recommended" examples above check for existence and then use the
file; the "recommended" examples are better because they use the file directly
and handle the error, if any.</p>
<p>In general, check for the existence of a file only if the file won’t be
used directly, for example when its existence is a signal from another
process.</p>
<h2><code>fs.existsSync(path)</code><span><a class="mark" href="#fs_fs_existssync_path" id="fs_fs_existssync_path">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the path exists, <code>false</code> otherwise.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_exists_path_callback"><code>fs.exists()</code></a>.</p>
<p><code>fs.exists()</code> is deprecated, but <code>fs.existsSync()</code> is not. The <code>callback</code>
parameter to <code>fs.exists()</code> accepts parameters that are inconsistent with other
Node.js callbacks. <code>fs.existsSync()</code> does not use a callback.</p>
<pre><code class="language-js">if (fs.existsSync('/etc/passwd')) {
  console.log('The path exists.');
}
</code></pre>
<h2><code>fs.fchmod(fd, mode, callback)</code><span><a class="mark" href="#fs_fs_fchmod_fd_mode_callback" id="fs_fs_fchmod_fd_mode_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p><span>Added in: v0.4.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fchmod.2.html"><code>fchmod(2)</code></a>. No arguments other than a possible exception
are given to the completion callback.</p>
<h2><code>fs.fchmodSync(fd, mode)</code><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">&#x3C;integer></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fchmod.2.html"><code>fchmod(2)</code></a>. Returns <code>undefined</code>.</p>
<h2><code>fs.fchown(fd, uid, gid, callback)</code><span><a class="mark" href="#fs_fs_fchown_fd_uid_gid_callback" id="fs_fs_fchown_fd_uid_gid_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p><span>Added in: v0.4.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fchown.2.html"><code>fchown(2)</code></a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2><code>fs.fchownSync(fd, uid, gid)</code><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">&#x3C;integer></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fchown.2.html"><code>fchown(2)</code></a>. Returns <code>undefined</code>.</p>
<h2><code>fs.fdatasync(fd, callback)</code><span><a class="mark" href="#fs_fs_fdatasync_fd_callback" id="fs_fs_fdatasync_fd_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.96</td>
<td><p><span>Added in: v0.1.96</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a>. No arguments other than a possible exception are
given to the completion callback.</p>
<h2><code>fs.fdatasyncSync(fd)</code><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">&#x3C;integer></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a>. Returns <code>undefined</code>.</p>
<h2><code>fs.fstat(fd[, options], callback)</code><span><a class="mark" href="#fs_fs_fstat_fd_options_callback" id="fs_fs_fstat_fd_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.95</td>
<td><p><span>Added in: v0.1.95</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether the numeric values in the returned
<a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>stats</code> <a href="#fs_class_fs_stats" class="type">&#x3C;fs.Stats></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fstat.2.html"><code>fstat(2)</code></a>. The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is an <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object. <code>fstat()</code> is identical to <a href="#fs_fs_stat_path_options_callback"><code>stat()</code></a>,
except that the file to be stat-ed is specified by the file descriptor <code>fd</code>.</p>
<h2><code>fs.fstatSync(fd[, options])</code><span><a class="mark" href="#fs_fs_fstatsync_fd_options" id="fs_fs_fstatsync_fd_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v0.1.95</td>
<td><p><span>Added in: v0.1.95</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether the numeric values in the returned
<a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#fs_class_fs_stats" class="type">&#x3C;fs.Stats></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fstat.2.html"><code>fstat(2)</code></a>.</p>
<h2><code>fs.fsync(fd, callback)</code><span><a class="mark" href="#fs_fs_fsync_fd_callback" id="fs_fs_fsync_fd_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.96</td>
<td><p><span>Added in: v0.1.96</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2><code>fs.fsyncSync(fd)</code><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">&#x3C;integer></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a>. Returns <code>undefined</code>.</p>
<h2><code>fs.ftruncate(fd[, len], callback)</code><span><a class="mark" href="#fs_fs_ftruncate_fd_len_callback" id="fs_fs_ftruncate_fd_len_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.8.6</td>
<td><p><span>Added in: v0.8.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>0</code></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/ftruncate.2.html"><code>ftruncate(2)</code></a>. No arguments other than a possible exception are
given to the completion callback.</p>
<p>If the file referred to by the file descriptor was larger than <code>len</code> bytes, only
the first <code>len</code> bytes will be retained in the file.</p>
<p>For example, the following program retains only the first four bytes of the
file:</p>
<pre><code class="language-js">console.log(fs.readFileSync('temp.txt', 'utf8'));
// Prints: Node.js

// get the file descriptor of the file to be truncated
const fd = fs.openSync('temp.txt', 'r+');

// Truncate the file to first four bytes
fs.ftruncate(fd, 4, (err) => {
  assert.ifError(err);
  console.log(fs.readFileSync('temp.txt', 'utf8'));
});
// Prints: Node
</code></pre>
<p>If the file previously was shorter than <code>len</code> bytes, it is extended, and the
extended part is filled with null bytes (<code>'\0'</code>):</p>
<pre><code class="language-js">console.log(fs.readFileSync('temp.txt', 'utf8'));
// Prints: Node.js

// get the file descriptor of the file to be truncated
const fd = fs.openSync('temp.txt', 'r+');

// Truncate the file to 10 bytes, whereas the actual size is 7 bytes
fs.ftruncate(fd, 10, (err) => {
  assert.ifError(err);
  console.log(fs.readFileSync('temp.txt'));
});
// Prints: &#x3C;Buffer 4e 6f 64 65 2e 6a 73 00 00 00>
// ('Node.js\0\0\0' in UTF8)
</code></pre>
<p>The last three bytes are null bytes (<code>'\0'</code>), to compensate the over-truncation.</p>
<h2><code>fs.ftruncateSync(fd[, len])</code><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">&#x3C;integer></a></li>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>0</code></li>
</ul>
<p>Returns <code>undefined</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_ftruncate_fd_len_callback"><code>fs.ftruncate()</code></a>.</p>
<h2><code>fs.futimes(fd, atime, mtime, callback)</code><span><a class="mark" href="#fs_fs_futimes_fd_atime_mtime_callback" id="fs_fs_futimes_fd_atime_mtime_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v4.1.0</td>
<td><p>Numeric strings, <code>NaN</code> and <code>Infinity</code> are now allowed time specifiers.</p></td></tr>
<tr><td>v0.4.2</td>
<td><p><span>Added in: v0.4.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;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><code>fs.futimesSync(fd, atime, mtime)</code><span><a class="mark" href="#fs_fs_futimessync_fd_atime_mtime" id="fs_fs_futimessync_fd_atime_mtime">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.1.0</td>
<td><p>Numeric strings, <code>NaN</code> and <code>Infinity</code> are now allowed time specifiers.</p></td></tr>
<tr><td>v0.4.2</td>
<td><p><span>Added in: v0.4.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></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><code>fs.lchmod(path, mode, callback)</code><span><a class="mark" href="#fs_fs_lchmod_path_mode_callback" id="fs_fs_lchmod_path_mode_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.4.7</td>
<td><p><span>Deprecated since: v0.4.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="https://www.freebsd.org/cgi/man.cgi?query=lchmod&#x26;sektion=2"><code>lchmod(2)</code></a>. No arguments other than a possible exception
are given to the completion callback.</p>
<p>Only available on macOS.</p>
<h2><code>fs.lchmodSync(path, mode)</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Synchronous <a href="https://www.freebsd.org/cgi/man.cgi?query=lchmod&#x26;sektion=2"><code>lchmod(2)</code></a>. Returns <code>undefined</code>.</p>
<h2><code>fs.lchown(path, uid, gid, callback)</code><span><a class="mark" href="#fs_fs_lchown_path_uid_gid_callback" id="fs_fs_lchown_path_uid_gid_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.6.0</td>
<td><p>This API is no longer deprecated.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/lchown.2.html"><code>lchown(2)</code></a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2><code>fs.lchownSync(path, uid, gid)</code><span><a class="mark" href="#fs_fs_lchownsync_path_uid_gid" id="fs_fs_lchownsync_path_uid_gid">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.6.0</td>
<td><p>This API is no longer deprecated.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/lchown.2.html"><code>lchown(2)</code></a>. Returns <code>undefined</code>.</p>
<h2><code>fs.link(existingPath, newPath, callback)</code><span><a class="mark" href="#fs_fs_link_existingpath_newpath_callback" id="fs_fs_link_existingpath_newpath_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>existingPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>existingPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a>. No arguments other than a possible exception are given to
the completion callback.</p>
<h2><code>fs.linkSync(existingPath, newPath)</code><span><a class="mark" href="#fs_fs_linksync_existingpath_newpath" id="fs_fs_linksync_existingpath_newpath">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>existingPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>existingPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a>. Returns <code>undefined</code>.</p>
<h2><code>fs.lstat(path[, options], callback)</code><span><a class="mark" href="#fs_fs_lstat_path_options_callback" id="fs_fs_lstat_path_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.30</td>
<td><p><span>Added in: v0.1.30</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether the numeric values in the returned
<a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>stats</code> <a href="#fs_class_fs_stats" class="type">&#x3C;fs.Stats></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a>. The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is a <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object. <code>lstat()</code> is identical to <code>stat()</code>,
except that if <code>path</code> is a symbolic link, then the link itself is stat-ed,
not the file that it refers to.</p>
<h2><code>fs.lstatSync(path[, options])</code><span><a class="mark" href="#fs_fs_lstatsync_path_options" id="fs_fs_lstatsync_path_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.30</td>
<td><p><span>Added in: v0.1.30</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether the numeric values in the returned
<a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#fs_class_fs_stats" class="type">&#x3C;fs.Stats></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a>.</p>
<h2><code>fs.mkdir(path[, options], callback)</code><span><a class="mark" href="#fs_fs_mkdir_path_options_callback" id="fs_fs_mkdir_path_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>In <code>recursive</code> mode, the callback now receives the first created path as an argument.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p>The second argument can now be an <code>options</code> object with <code>recursive</code> and <code>mode</code> properties.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.8</td>
<td><p><span>Added in: v0.1.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></p>
<ul>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Not supported on Windows. <strong>Default:</strong> <code>0o777</code>.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronously creates a directory.</p>
<p>The callback is given a possible exception and, if <code>recursive</code> is <code>true</code>, the
first directory path created, <code>(err, [path])</code>.</p>
<p>The optional <code>options</code> argument can be an integer specifying mode (permission
and sticky bits), or an object with a <code>mode</code> property and a <code>recursive</code>
property indicating whether parent directories should be created. Calling
<code>fs.mkdir()</code> when <code>path</code> is a directory that exists results in an error only
when <code>recursive</code> is false.</p>
<pre><code class="language-js">// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
  if (err) throw err;
});
</code></pre>
<p>On Windows, using <code>fs.mkdir()</code> on the root directory even with recursion will
result in an error:</p>
<pre><code class="language-js">fs.mkdir('/', { recursive: true }, (err) => {
  // => [Error: EPERM: operation not permitted, mkdir 'C:\']
});
</code></pre>
<p>See also: <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html"><code>mkdir(2)</code></a>.</p>
<h2><code>fs.mkdirSync(path[, options])</code><span><a class="mark" href="#fs_fs_mkdirsync_path_options" id="fs_fs_mkdirsync_path_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>In <code>recursive</code> mode, the first created path is returned now.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p>The second argument can now be an <code>options</code> object with <code>recursive</code> and <code>mode</code> properties.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></p>
<ul>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Not supported on Windows. <strong>Default:</strong> <code>0o777</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>Synchronously creates a directory. Returns <code>undefined</code>, or if <code>recursive</code> is
<code>true</code>, the first directory path created.
This is the synchronous version of <a href="#fs_fs_mkdir_path_options_callback"><code>fs.mkdir()</code></a>.</p>
<p>See also: <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html"><code>mkdir(2)</code></a>.</p>
<h2><code>fs.mkdtemp(prefix[, options], callback)</code><span><a class="mark" href="#fs_fs_mkdtemp_prefix_options_callback" id="fs_fs_mkdtemp_prefix_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v6.2.1</td>
<td><p>The <code>callback</code> parameter is optional now.</p></td></tr>
<tr><td>v5.10.0</td>
<td><p><span>Added in: v5.10.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>prefix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>directory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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. Due to platform
inconsistencies, avoid trailing <code>X</code> characters in <code>prefix</code>. Some platforms,
notably the BSDs, can return more than six random characters, and replace
trailing <code>X</code> characters in <code>prefix</code> with random characters.</p>
<p>The created directory path is passed as a string to the callback's second
parameter.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use.</p>
<pre><code class="language-js">fs.mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
});
</code></pre>
<p>The <code>fs.mkdtemp()</code> method will append the six randomly selected characters
directly to the <code>prefix</code> string. For instance, given a directory <code>/tmp</code>, if the
intention is to create a temporary directory <em>within</em> <code>/tmp</code>, the <code>prefix</code>
must end with a trailing platform-specific path separator
(<code>require('path').sep</code>).</p>
<pre><code class="language-js">// The parent directory for the new temporary directory
const tmpDir = os.tmpdir();

// This method is *INCORRECT*:
fs.mkdtemp(tmpDir, (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // Will print something similar to `/tmpabc123`.
  // A new temporary directory is created at the file system root
  // rather than *within* the /tmp directory.
});

// This method is *CORRECT*:
const { sep } = require('path');
fs.mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
  if (err) throw err;
  console.log(directory);
  // Will print something similar to `/tmp/abc123`.
  // A new temporary directory is created within
  // the /tmp directory.
});
</code></pre>
<h2><code>fs.mkdtempSync(prefix[, options])</code><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">&#x3C;string></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a></li>
</ul>
<p>Returns the created directory path.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_mkdtemp_prefix_options_callback"><code>fs.mkdtemp()</code></a>.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use.</p>
<h2><code>fs.open(path[, flags[, mode]], callback)</code><span><a class="mark" href="#fs_fs_open_path_flags_mode_callback" id="fs_fs_open_path_flags_mode_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.1.0</td>
<td><p>The <code>flags</code> argument is now optional and defaults to <code>'r'</code>.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>as</code> and <code>as+</code> modes are supported now.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>.
<strong>Default:</strong> <code>'r'</code>.</li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>0o666</code> (readable and writable)</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
</li>
</ul>
<p>Asynchronous file open. See <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a>.</p>
<p><code>mode</code> sets the file mode (permission and sticky bits), but only if the file was
created. On Windows, only the write permission can be manipulated; see
<a href="#fs_fs_chmod_path_mode_callback"><code>fs.chmod()</code></a>.</p>
<p>The callback gets two arguments <code>(err, fd)</code>.</p>
<p>Some characters (<code>&#x3C; > : " / \ | ? *</code>) are reserved under Windows as documented
by <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file">Naming Files, Paths, and Namespaces</a>. Under NTFS, if the filename contains
a colon, Node.js will open a file system stream, as described by
<a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams">this MSDN page</a>.</p>
<p>Functions based on <code>fs.open()</code> exhibit this behavior as well:
<code>fs.writeFile()</code>, <code>fs.readFile()</code>, etc.</p>
<h2><code>fs.opendir(path[, options], callback)</code><span><a class="mark" href="#fs_fs_opendir_path_options_callback" id="fs_fs_opendir_path_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>bufferSize</code> option was introduced.</p></td></tr>
<tr><td>v12.12.0</td>
<td><p><span>Added in: v12.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>bufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Number of directory entries that are buffered
internally when reading from the directory. Higher values lead to better
performance but higher memory usage. <strong>Default:</strong> <code>32</code></li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>dir</code> <a href="#fs_class_fs_dir" class="type">&#x3C;fs.Dir></a></li>
</ul>
</li>
</ul>
<p>Asynchronously open a directory. See <a href="http://man7.org/linux/man-pages/man3/opendir.3.html"><code>opendir(3)</code></a>.</p>
<p>Creates an <a href="#fs_class_fs_dir"><code>fs.Dir</code></a>, which contains all further functions for reading from
and cleaning up the directory.</p>
<p>The <code>encoding</code> option sets the encoding for the <code>path</code> while opening the
directory and subsequent read operations.</p>
<h2><code>fs.opendirSync(path[, options])</code><span><a class="mark" href="#fs_fs_opendirsync_path_options" id="fs_fs_opendirsync_path_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>bufferSize</code> option was introduced.</p></td></tr>
<tr><td>v12.12.0</td>
<td><p><span>Added in: v12.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>bufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Number of directory entries that are buffered
internally when reading from the directory. Higher values lead to better
performance but higher memory usage. <strong>Default:</strong> <code>32</code></li>
</ul>
</li>
<li>Returns: <a href="#fs_class_fs_dir" class="type">&#x3C;fs.Dir></a></li>
</ul>
<p>Synchronously open a directory. See <a href="http://man7.org/linux/man-pages/man3/opendir.3.html"><code>opendir(3)</code></a>.</p>
<p>Creates an <a href="#fs_class_fs_dir"><code>fs.Dir</code></a>, which contains all further functions for reading from
and cleaning up the directory.</p>
<p>The <code>encoding</code> option sets the encoding for the <code>path</code> while opening the
directory and subsequent read operations.</p>
<h2><code>fs.openSync(path[, flags, mode])</code><span><a class="mark" href="#fs_fs_opensync_path_flags_mode" id="fs_fs_opensync_path_flags_mode">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.1.0</td>
<td><p>The <code>flags</code> argument is now optional and defaults to <code>'r'</code>.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>as</code> and <code>as+</code> modes are supported now.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <strong>Default:</strong> <code>'r'</code>.
See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>.</li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;number></a></li>
</ul>
<p>Returns an integer representing the file descriptor.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_open_path_flags_mode_callback"><code>fs.open()</code></a>.</p>
<h2><code>fs.read(fd, buffer, offset, length, position, callback)</code><span><a class="mark" href="#fs_fs_read_fd_buffer_offset_length_position_callback" id="fs_fs_read_fd_buffer_offset_length_position_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code>, or a <code>DataView</code>.</p></td></tr>
<tr><td>v7.4.0</td>
<td><p>The <code>buffer</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>length</code> parameter can now be <code>0</code>.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;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 (read from the fd) will be written to.</p>
<p><code>offset</code> is the offset in the buffer to start writing at.</p>
<p><code>length</code> is an integer specifying the number of bytes to read.</p>
<p><code>position</code> is an argument specifying where to begin reading from in the file.
If <code>position</code> is <code>null</code>, data will be read from the current file position,
and the file position will be updated.
If <code>position</code> is an integer, the file position will remain unchanged.</p>
<p>The callback is given the three arguments, <code>(err, bytesRead, buffer)</code>.</p>
<p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns
a <code>Promise</code> for an <code>Object</code> with <code>bytesRead</code> and <code>buffer</code> properties.</p>
<h2><code>fs.read(fd, [options,] callback)</code><span><a class="mark" href="#fs_fs_read_fd_options_callback" id="fs_fs_read_fd_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>Options object can be passed in to make Buffer, offset, length and position optional</p></td></tr>
<tr><td>v12.17.0</td>
<td><p><span>Added in: v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> <strong>Default:</strong> <code>Buffer.alloc(16384)</code></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <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">&#x3C;integer></a> <strong>Default:</strong> <code>buffer.length</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>null</code></li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
</ul>
<p>Similar to the above <code>fs.read</code> function, this version takes an optional <code>options</code> object.
If no <code>options</code> object is specified, it will default with the above values.</p>
<h2><code>fs.readdir(path[, options], callback)</code><span><a class="mark" href="#fs_fs_readdir_path_options_callback" id="fs_fs_readdir_path_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>New option <code>withFileTypes</code> was added.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>options</code> parameter was added.</p></td></tr>
<tr><td>v0.1.8</td>
<td><p><span>Added in: v0.1.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>withFileTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>files</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer[]></a> | <a href="#fs_class_fs_dirent" class="type">&#x3C;fs.Dirent[]></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a>. Reads the contents of a directory.
The callback gets two arguments <code>(err, files)</code> where <code>files</code> is an array of
the names of the files in the directory excluding <code>'.'</code> and <code>'..'</code>.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the filenames passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>,
the filenames returned will be passed as <code>Buffer</code> objects.</p>
<p>If <code>options.withFileTypes</code> is set to <code>true</code>, the <code>files</code> array will contain
<a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a> objects.</p>
<h2><code>fs.readdirSync(path[, options])</code><span><a class="mark" href="#fs_fs_readdirsync_path_options" id="fs_fs_readdirsync_path_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>New option <code>withFileTypes</code> was added.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>withFileTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer[]></a> | <a href="#fs_class_fs_dirent" class="type">&#x3C;fs.Dirent[]></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a>.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the filenames returned. If the <code>encoding</code> is set to <code>'buffer'</code>,
the filenames returned will be passed as <code>Buffer</code> objects.</p>
<p>If <code>options.withFileTypes</code> is set to <code>true</code>, the result will contain
<a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a> objects.</p>
<h2><code>fs.readFile(path[, options], callback)</code><span><a class="mark" href="#fs_fs_readfile_path_options_callback" id="fs_fs_readfile_path_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v5.1.0</td>
<td><p>The <code>callback</code> will always be called with <code>null</code> as the <code>error</code> parameter in case of success.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>path</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.1.29</td>
<td><p><span>Added in: v0.1.29</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> filename or file descriptor</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;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">&#x3C;string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
</ul>
<p>Asynchronously reads the entire contents of a file.</p>
<pre><code class="language-js">fs.readFile('/etc/passwd', (err, data) => {
  if (err) throw err;
  console.log(data);
});
</code></pre>
<p>The callback is passed two arguments <code>(err, data)</code>, where <code>data</code> is the
contents of the file.</p>
<p>If no encoding is specified, then the raw buffer is returned.</p>
<p>If <code>options</code> is a string, then it specifies the encoding:</p>
<pre><code class="language-js">fs.readFile('/etc/passwd', 'utf8', callback);
</code></pre>
<p>When the path is a directory, the behavior of <code>fs.readFile()</code> and
<a href="#fs_fs_readfilesync_path_options"><code>fs.readFileSync()</code></a> is platform-specific. On macOS, Linux, and Windows, an
error will be returned. On FreeBSD, a representation of the directory's contents
will be returned.</p>
<pre><code class="language-js">// macOS, Linux, and Windows
fs.readFile('&#x3C;directory>', (err, data) => {
  // => [Error: EISDIR: illegal operation on a directory, read &#x3C;directory>]
});

//  FreeBSD
fs.readFile('&#x3C;directory>', (err, data) => {
  // => null, &#x3C;data>
});
</code></pre>
<p>The <code>fs.readFile()</code> function buffers the entire file. To minimize memory costs,
when possible prefer streaming via <code>fs.createReadStream()</code>.</p>
<h3>File descriptors<span><a class="mark" href="#fs_file_descriptors_1" id="fs_file_descriptors_1">#</a></span></h3>
<ol>
<li>Any specified file descriptor has to support reading.</li>
<li>If a file descriptor is specified as the <code>path</code>, it will not be closed
automatically.</li>
<li>The reading will begin at the current position. For example, if the file
already had <code>'Hello World</code>' and six bytes are read with the file descriptor,
the call to <code>fs.readFile()</code> with the same file descriptor, would give
<code>'World'</code>, rather than <code>'Hello World'</code>.</li>
</ol>
<h2><code>fs.readFileSync(path[, options])</code><span><a class="mark" href="#fs_fs_readfilesync_path_options" id="fs_fs_readfilesync_path_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>path</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.1.8</td>
<td><p><span>Added in: v0.1.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> filename or file descriptor</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;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">&#x3C;string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Returns the contents of the <code>path</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_readfile_path_options_callback"><code>fs.readFile()</code></a>.</p>
<p>If the <code>encoding</code> option is specified then this function returns a
string. Otherwise it returns a buffer.</p>
<p>Similar to <a href="#fs_fs_readfile_path_options_callback"><code>fs.readFile()</code></a>, when the path is a directory, the behavior of
<code>fs.readFileSync()</code> is platform-specific.</p>
<pre><code class="language-js">// macOS, Linux, and Windows
fs.readFileSync('&#x3C;directory>');
// => [Error: EISDIR: illegal operation on a directory, read &#x3C;directory>]

//  FreeBSD
fs.readFileSync('&#x3C;directory>'); // => &#x3C;data>
</code></pre>
<h2><code>fs.readlink(path[, options], callback)</code><span><a class="mark" href="#fs_fs_readlink_path_options_callback" id="fs_fs_readlink_path_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>linkString</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a>. The callback gets two arguments <code>(err, linkString)</code>.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the link path passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>,
the link path returned will be passed as a <code>Buffer</code> object.</p>
<h2><code>fs.readlinkSync(path[, options])</code><span><a class="mark" href="#fs_fs_readlinksync_path_options" id="fs_fs_readlinksync_path_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a>. Returns the symbolic link's string value.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the link path returned. If the <code>encoding</code> is set to <code>'buffer'</code>,
the link path returned will be passed as a <code>Buffer</code> object.</p>
<h2><code>fs.readSync(fd, buffer, offset, length, position)</code><span><a class="mark" href="#fs_fs_readsync_fd_buffer_offset_length_position" id="fs_fs_readsync_fd_buffer_offset_length_position">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>length</code> parameter can now be <code>0</code>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Returns the number of <code>bytesRead</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_read_fd_buffer_offset_length_position_callback"><code>fs.read()</code></a>.</p>
<h2><code>fs.readSync(fd, buffer, [options])</code><span><a class="mark" href="#fs_fs_readsync_fd_buffer_options" id="fs_fs_readsync_fd_buffer_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>Options object can be passed in to make offset, length and position optional</p></td></tr>
<tr><td>v12.17.0</td>
<td><p><span>Added in: v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <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">&#x3C;integer></a> <strong>Default:</strong> <code>buffer.length</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>null</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Returns the number of <code>bytesRead</code>.</p>
<p>Similar to the above <code>fs.readSync</code> function, this version takes an optional <code>options</code> object.
If no <code>options</code> object is specified, it will default with the above values.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_read_fd_buffer_offset_length_position_callback"><code>fs.read()</code></a>.</p>
<h2><code>fs.readv(fd, buffers[, position], callback)</code><span><a class="mark" href="#fs_fs_readv_fd_buffers_position_callback" id="fs_fs_readv_fd_buffers_position_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.17.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">&#x3C;integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type">&#x3C;ArrayBufferView[]></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type">&#x3C;ArrayBufferView[]></a></li>
</ul>
</li>
</ul>
<p>Read from a file specified by <code>fd</code> and write to an array of <code>ArrayBufferView</code>s
using <code>readv()</code>.</p>
<p><code>position</code> is the offset from the beginning of the file from where data
should be read. If <code>typeof position !== 'number'</code>, the data will be read
from the current position.</p>
<p>The callback will be given three arguments: <code>err</code>, <code>bytesRead</code>, and
<code>buffers</code>. <code>bytesRead</code> is how many bytes were read from the file.</p>
<p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns
a <code>Promise</code> for an <code>Object</code> with <code>bytesRead</code> and <code>buffers</code> properties.</p>
<h2><code>fs.readvSync(fd, buffers[, position])</code><span><a class="mark" href="#fs_fs_readvsync_fd_buffers_position" id="fs_fs_readvsync_fd_buffers_position">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.17.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">&#x3C;integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type">&#x3C;ArrayBufferView[]></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of bytes read.</li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_readv_fd_buffers_position_callback"><code>fs.readv()</code></a>.</p>
<h2><code>fs.realpath(path[, options], callback)</code><span><a class="mark" href="#fs_fs_realpath_path_options_callback" id="fs_fs_realpath_path_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>Pipe/Socket resolve support was added.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v6.4.0</td>
<td><p>Calling <code>realpath</code> now works again for various edge cases on Windows.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>cache</code> parameter was removed.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>resolvedPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
</ul>
<p>Asynchronously computes the canonical pathname by resolving <code>.</code>, <code>..</code> and
symbolic links.</p>
<p>A canonical pathname is not necessarily unique. Hard links and bind mounts can
expose a file system entity through many pathnames.</p>
<p>This function behaves like <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a>, with some exceptions:</p>
<ol>
<li>
<p>No case conversion is performed on case-insensitive file systems.</p>
</li>
<li>
<p>The maximum number of symbolic links is platform-independent and generally
(much) higher than what the native <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a> implementation supports.</p>
</li>
</ol>
<p>The <code>callback</code> gets two arguments <code>(err, resolvedPath)</code>. May use <code>process.cwd</code>
to resolve relative paths.</p>
<p>Only paths that can be converted to UTF8 strings are supported.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the path passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>,
the path returned will be passed as a <code>Buffer</code> object.</p>
<p>If <code>path</code> resolves to a socket or a pipe, the function will return a system
dependent name for that object.</p>
<h2><code>fs.realpath.native(path[, options], callback)</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>resolvedPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a>.</p>
<p>The <code>callback</code> gets two arguments <code>(err, resolvedPath)</code>.</p>
<p>Only paths that can be converted to UTF8 strings are supported.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the path passed to the callback. If the <code>encoding</code> is set to <code>'buffer'</code>,
the path returned will be passed as a <code>Buffer</code> object.</p>
<p>On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on <code>/proc</code> in order for this function to work. Glibc does not have
this restriction.</p>
<h2><code>fs.realpathSync(path[, options])</code><span><a class="mark" href="#fs_fs_realpathsync_path_options" id="fs_fs_realpathsync_path_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Pipe/Socket resolve support was added.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v6.4.0</td>
<td><p>Calling <code>realpathSync</code> now works again for various edge cases on Windows.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>cache</code> parameter was removed.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Returns the resolved pathname.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_realpath_path_options_callback"><code>fs.realpath()</code></a>.</p>
<h2><code>fs.realpathSync.native(path[, options])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man3/realpath.3.html"><code>realpath(3)</code></a>.</p>
<p>Only paths that can be converted to UTF8 strings are supported.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the path returned. If the <code>encoding</code> is set to <code>'buffer'</code>,
the path returned will be passed as a <code>Buffer</code> object.</p>
<p>On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on <code>/proc</code> in order for this function to work. Glibc does not have
this restriction.</p>
<h2><code>fs.rename(oldPath, newPath, callback)</code><span><a class="mark" href="#fs_fs_rename_oldpath_newpath_callback" id="fs_fs_rename_oldpath_newpath_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>oldPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>oldPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;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. If there is a directory at <code>newPath</code>, an error will
be raised instead. No arguments other than a possible exception are
given to the completion callback.</p>
<p>See also: <a href="http://man7.org/linux/man-pages/man2/rename.2.html"><code>rename(2)</code></a>.</p>
<pre><code class="language-js">fs.rename('oldFile.txt', 'newFile.txt', (err) => {
  if (err) throw err;
  console.log('Rename complete!');
});
</code></pre>
<h2><code>fs.renameSync(oldPath, newPath)</code><span><a class="mark" href="#fs_fs_renamesync_oldpath_newpath" id="fs_fs_renamesync_oldpath_newpath">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>oldPath</code> and <code>newPath</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>oldPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/rename.2.html"><code>rename(2)</code></a>. Returns <code>undefined</code>.</p>
<h2><code>fs.rmdir(path[, options], callback)</code><span><a class="mark" href="#fs_fs_rmdir_path_options_callback" id="fs_fs_rmdir_path_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>maxBusyTries</code> option is renamed to <code>maxRetries</code>, and its default is 0. The <code>emfileWait</code> option has been removed, and <code>EMFILE</code> errors use the same retry logic as other errors. The <code>retryDelay</code> option is now supported. <code>ENFILE</code> errors are now retried.</p></td></tr>
<tr><td>v12.10.0</td>
<td><p>The <code>recursive</code>, <code>maxBusyTries</code>, and <code>emfileWait</code> options are now supported.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameters can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Recursive removal is experimental.</div><p></p>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>maxRetries</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> If an <code>EBUSY</code>, <code>EMFILE</code>, <code>ENFILE</code>, <code>ENOTEMPTY</code>, or
<code>EPERM</code> error is encountered, Node.js will retry the operation with a linear
backoff wait of <code>retryDelay</code> ms longer on each try. This option represents the
number of retries. This option is ignored if the <code>recursive</code> option is not
<code>true</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, perform a recursive directory removal. In
recursive mode, errors are not reported if <code>path</code> does not exist, and
operations are retried on failure. <strong>Default:</strong> <code>false</code>.</li>
<li><code>retryDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The amount of time in milliseconds to wait between
retries. This option is ignored if the <code>recursive</code> option is not <code>true</code>.
<strong>Default:</strong> <code>100</code>.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/rmdir.2.html"><code>rmdir(2)</code></a>. No arguments other than a possible exception are given
to the completion callback.</p>
<p>Using <code>fs.rmdir()</code> on a file (not a directory) results in an <code>ENOENT</code> error on
Windows and an <code>ENOTDIR</code> error on POSIX.</p>
<h2><code>fs.rmdirSync(path[, options])</code><span><a class="mark" href="#fs_fs_rmdirsync_path_options" id="fs_fs_rmdirsync_path_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>maxBusyTries</code> option is renamed to <code>maxRetries</code>, and its default is 0. The <code>emfileWait</code> option has been removed, and <code>EMFILE</code> errors use the same retry logic as other errors. The <code>retryDelay</code> option is now supported. <code>ENFILE</code> errors are now retried.</p></td></tr>
<tr><td>v12.10.0</td>
<td><p>The <code>recursive</code>, <code>maxBusyTries</code>, and <code>emfileWait</code> options are now supported.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameters can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Recursive removal is experimental.</div><p></p>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>maxRetries</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> If an <code>EBUSY</code>, <code>EMFILE</code>, <code>ENFILE</code>, <code>ENOTEMPTY</code>, or
<code>EPERM</code> error is encountered, Node.js will retry the operation with a linear
backoff wait of <code>retryDelay</code> ms longer on each try. This option represents the
number of retries. This option is ignored if the <code>recursive</code> option is not
<code>true</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, perform a recursive directory removal. In
recursive mode, errors are not reported if <code>path</code> does not exist, and
operations are retried on failure. <strong>Default:</strong> <code>false</code>.</li>
<li><code>retryDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The amount of time in milliseconds to wait between
retries. This option is ignored if the <code>recursive</code> option is not <code>true</code>.
<strong>Default:</strong> <code>100</code>.</li>
</ul>
</li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/rmdir.2.html"><code>rmdir(2)</code></a>. Returns <code>undefined</code>.</p>
<p>Using <code>fs.rmdirSync()</code> on a file (not a directory) results in an <code>ENOENT</code> error
on Windows and an <code>ENOTDIR</code> error on POSIX.</p>
<h2><code>fs.stat(path[, options], callback)</code><span><a class="mark" href="#fs_fs_stat_path_options_callback" id="fs_fs_stat_path_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether the numeric values in the returned
<a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>stats</code> <a href="#fs_class_fs_stats" class="type">&#x3C;fs.Stats></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/stat.2.html"><code>stat(2)</code></a>. The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is an <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object.</p>
<p>In case of an error, the <code>err.code</code> will be one of <a href="#errors_common_system_errors">Common System Errors</a>.</p>
<p>Using <code>fs.stat()</code> to check for the existence of a file before calling
<code>fs.open()</code>, <code>fs.readFile()</code> or <code>fs.writeFile()</code> is not recommended.
Instead, user code should open/read/write the file directly and handle the
error raised if the file is not available.</p>
<p>To check if a file exists without manipulating it afterwards, <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a>
is recommended.</p>
<p>For example, given the following directory structure:</p>
<pre><code class="language-text">- txtDir
-- file.txt
- app.js
</code></pre>
<p>The next program will check for the stats of the given paths:</p>
<pre><code class="language-js">const fs = require('fs');

const pathsToCheck = ['./txtDir', './txtDir/file.txt'];

for (let i = 0; i &#x3C; pathsToCheck.length; i++) {
  fs.stat(pathsToCheck[i], function(err, stats) {
    console.log(stats.isDirectory());
    console.log(stats);
  });
}
</code></pre>
<p>The resulting output will resemble:</p>
<pre><code class="language-console">true
Stats {
  dev: 16777220,
  mode: 16877,
  nlink: 3,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 14214262,
  size: 96,
  blocks: 0,
  atimeMs: 1561174653071.963,
  mtimeMs: 1561174614583.3518,
  ctimeMs: 1561174626623.5366,
  birthtimeMs: 1561174126937.2893,
  atime: 2019-06-22T03:37:33.072Z,
  mtime: 2019-06-22T03:36:54.583Z,
  ctime: 2019-06-22T03:37:06.624Z,
  birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
  dev: 16777220,
  mode: 33188,
  nlink: 1,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 14214074,
  size: 8,
  blocks: 8,
  atimeMs: 1561174616618.8555,
  mtimeMs: 1561174614584,
  ctimeMs: 1561174614583.8145,
  birthtimeMs: 1561174007710.7478,
  atime: 2019-06-22T03:36:56.619Z,
  mtime: 2019-06-22T03:36:54.584Z,
  ctime: 2019-06-22T03:36:54.584Z,
  birthtime: 2019-06-22T03:26:47.711Z
}
</code></pre>
<h2><code>fs.statSync(path[, options])</code><span><a class="mark" href="#fs_fs_statsync_path_options" id="fs_fs_statsync_path_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether the numeric values in the returned
<a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#fs_class_fs_stats" class="type">&#x3C;fs.Stats></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/stat.2.html"><code>stat(2)</code></a>.</p>
<h2><code>fs.symlink(target, path[, type], callback)</code><span><a class="mark" href="#fs_fs_symlink_target_path_type_callback" id="fs_fs_symlink_target_path_type_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>If the <code>type</code> argument is left undefined, Node will autodetect <code>target</code> type and automatically select <code>dir</code> or <code>file</code></p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>target</code> and <code>path</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/symlink.2.html"><code>symlink(2)</code></a> which creates the link called <code>path</code> pointing to
<code>target</code>. No arguments other than a possible exception are given to the
completion callback.</p>
<p>The <code>type</code> argument is only available on Windows and ignored on other platforms.
It can be set to <code>'dir'</code>, <code>'file'</code>, or <code>'junction'</code>. If the <code>type</code> argument is
not set, Node.js will autodetect <code>target</code> type and use <code>'file'</code> or <code>'dir'</code>. If
the <code>target</code> does not exist, <code>'file'</code> will be used. 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>Relative targets are relative to the link’s parent directory.</p>
<pre><code class="language-js">fs.symlink('./mew', './example/mewtwo', callback);
</code></pre>
<p>The above example creates a symbolic link <code>mewtwo</code> in the <code>example</code> which points
to <code>mew</code> in the same directory:</p>
<pre><code class="language-bash">$ tree example/
example/
├── mew
└── mewtwo -> ./mew
</code></pre>
<h2><code>fs.symlinkSync(target, path[, type])</code><span><a class="mark" href="#fs_fs_symlinksync_target_path_type" id="fs_fs_symlinksync_target_path_type">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>If the <code>type</code> argument is left undefined, Node will autodetect <code>target</code> type and automatically select <code>dir</code> or <code>file</code></p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>target</code> and <code>path</code> parameters can be WHATWG <code>URL</code> objects using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns <code>undefined</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_symlink_target_path_type_callback"><code>fs.symlink()</code></a>.</p>
<h2><code>fs.truncate(path[, len], callback)</code><span><a class="mark" href="#fs_fs_truncate_path_len_callback" id="fs_fs_truncate_path_len_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.8.6</td>
<td><p><span>Added in: v0.8.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>0</code></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/truncate.2.html"><code>truncate(2)</code></a>. No arguments other than a possible exception are
given to the completion callback. A file descriptor can also be passed as the
first argument. In this case, <code>fs.ftruncate()</code> is called.</p>
<p>Passing a file descriptor is deprecated and may result in an error being thrown
in the future.</p>
<h2><code>fs.truncateSync(path[, len])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>0</code></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/truncate.2.html"><code>truncate(2)</code></a>. Returns <code>undefined</code>. A file descriptor can also be
passed as the first argument. In this case, <code>fs.ftruncateSync()</code> is called.</p>
<p>Passing a file descriptor is deprecated and may result in an error being thrown
in the future.</p>
<h2><code>fs.unlink(path, callback)</code><span><a class="mark" href="#fs_fs_unlink_path_callback" id="fs_fs_unlink_path_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>Asynchronously removes a file or symbolic link. No arguments other than a
possible exception are given to the completion callback.</p>
<pre><code class="language-js">// Assuming that 'path/file.txt' is a regular file.
fs.unlink('path/file.txt', (err) => {
  if (err) throw err;
  console.log('path/file.txt was deleted');
});
</code></pre>
<p><code>fs.unlink()</code> will not work on a directory, empty or otherwise. To remove a
directory, use <a href="#fs_fs_rmdir_path_options_callback"><code>fs.rmdir()</code></a>.</p>
<p>See also: <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>.</p>
<h2><code>fs.unlinkSync(path)</code><span><a class="mark" href="#fs_fs_unlinksync_path" id="fs_fs_unlinksync_path">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>. Returns <code>undefined</code>.</p>
<h2><code>fs.unwatchFile(filename[, listener])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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><code>fs.utimes(path, atime, mtime, callback)</code><span><a class="mark" href="#fs_fs_utimes_path_atime_mtime_callback" id="fs_fs_utimes_path_atime_mtime_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><code>NaN</code>, <code>Infinity</code>, and <code>-Infinity</code> are no longer valid time specifiers.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v4.1.0</td>
<td><p>Numeric strings, <code>NaN</code> and <code>Infinity</code> are now allowed time specifiers.</p></td></tr>
<tr><td>v0.4.2</td>
<td><p><span>Added in: v0.4.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;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 in seconds,
<code>Date</code>s, or a numeric string like <code>'123456789.0'</code>.</li>
<li>If the value can not be converted to a number, or is <code>NaN</code>, <code>Infinity</code> or
<code>-Infinity</code>, an <code>Error</code> will be thrown.</li>
</ul>
<h2><code>fs.utimesSync(path, atime, mtime)</code><span><a class="mark" href="#fs_fs_utimessync_path_atime_mtime" id="fs_fs_utimessync_path_atime_mtime">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p><code>NaN</code>, <code>Infinity</code>, and <code>-Infinity</code> are no longer valid time specifiers.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v4.1.0</td>
<td><p>Numeric strings, <code>NaN</code> and <code>Infinity</code> are now allowed time specifiers.</p></td></tr>
<tr><td>v0.4.2</td>
<td><p><span>Added in: v0.4.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
</ul>
<p>Returns <code>undefined</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_utimes_path_atime_mtime_callback"><code>fs.utimes()</code></a>.</p>
<h2><code>fs.watch(filename[, options][, listener])</code><span><a class="mark" href="#fs_fs_watch_filename_options_listener" id="fs_fs_watch_filename_options_listener">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The passed <code>options</code> object will never be modified.</p></td></tr>
<tr><td>v0.5.10</td>
<td><p><span>Added in: v0.5.10</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>persistent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;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">&#x3C;string></a> Specifies the character encoding to be used for the
 filename passed to the listener. <strong>Default:</strong> <code>'utf8'</code>.</li>
</ul>
</li>
<li>
<p><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> <strong>Default:</strong> <code>undefined</code></p>
<ul>
<li><code>eventType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#fs_class_fs_fswatcher" class="type">&#x3C;fs.FSWatcher></a></li>
</ul>
<p>Watch for changes on <code>filename</code>, where <code>filename</code> is either a file or a
directory.</p>
<p>The second argument is optional. If <code>options</code> is provided as a string, it
specifies the <code>encoding</code>. Otherwise <code>options</code> should be passed as an object.</p>
<p>The listener callback gets two arguments <code>(eventType, filename)</code>. <code>eventType</code>
is either <code>'rename'</code> or <code>'change'</code>, and <code>filename</code> is the name of the file
which triggered the event.</p>
<p>On most platforms, <code>'rename'</code> is emitted whenever a filename appears or
disappears in the directory.</p>
<p>The listener callback is attached to the <code>'change'</code> event fired by
<a href="#fs_class_fs_fswatcher"><code>fs.FSWatcher</code></a>, but it is not the same thing as the <code>'change'</code> value of
<code>eventType</code>.</p>
<h3>Caveats<span><a class="mark" href="#fs_caveats" id="fs_caveats">#</a></span></h3>

<p>The <code>fs.watch</code> API is not 100% consistent across platforms, and is
unavailable in some situations.</p>
<p>The recursive option is only supported on macOS and Windows.</p>
<p>On Windows, no events will be emitted if the watched directory is moved or
renamed. An <code>EPERM</code> error is reported when the watched directory is deleted.</p>
<h4>Availability<span><a class="mark" href="#fs_availability" id="fs_availability">#</a></span></h4>

<p>This feature depends on the underlying operating system providing a way
to be notified of filesystem changes.</p>
<ul>
<li>On Linux systems, this uses <a href="http://man7.org/linux/man-pages/man7/inotify.7.html"><code>inotify(7)</code></a>.</li>
<li>On BSD systems, this uses <a href="https://www.freebsd.org/cgi/man.cgi?query=kqueue&#x26;sektion=2"><code>kqueue(2)</code></a>.</li>
<li>On macOS, this uses <a href="https://www.freebsd.org/cgi/man.cgi?query=kqueue&#x26;sektion=2"><code>kqueue(2)</code></a> for files and <a href="https://developer.apple.com/documentation/coreservices/file_system_events"><code>FSEvents</code></a> for
directories.</li>
<li>On SunOS systems (including Solaris and SmartOS), this uses <a href="https://illumos.org/man/port_create"><code>event ports</code></a>.</li>
<li>On Windows systems, this feature depends on <a href="https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-readdirectorychangesw"><code>ReadDirectoryChangesW</code></a>.</li>
<li>On Aix systems, this feature depends on <a href="https://www.ibm.com/developerworks/aix/library/au-aix_event_infrastructure/"><code>AHAFS</code></a>, which must be enabled.</li>
</ul>
<p>If the underlying functionality is not available for some reason, then
<code>fs.watch()</code> will not be able to function and may thrown an exception.
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 or Docker.</p>
<p>It is still possible to use <code>fs.watchFile()</code>, which uses stat polling, but
this method is slower and less reliable.</p>
<h4>Inodes<span><a class="mark" href="#fs_inodes" id="fs_inodes">#</a></span></h4>

<p>On Linux and macOS systems, <code>fs.watch()</code> resolves the path to an <a href="https://en.wikipedia.org/wiki/Inode">inode</a> and
watches the inode. If the watched path is deleted and recreated, it is assigned
a new inode. The watch will emit an event for the delete but will continue
watching the <em>original</em> inode. Events for the new inode will not be emitted.
This is expected behavior.</p>
<p>AIX files retain the same inode for the lifetime of a file. Saving and closing a
watched file on AIX will result in two notifications (one for adding new
content, and one for truncation).</p>
<h4>Filename argument<span><a class="mark" href="#fs_filename_argument" id="fs_filename_argument">#</a></span></h4>

<p>Providing <code>filename</code> argument in the callback is only supported on Linux,
macOS, Windows, and AIX. Even on supported platforms, <code>filename</code> is not always
guaranteed to be provided. Therefore, don't assume that <code>filename</code> argument is
always provided in the callback, and have some fallback logic if it is <code>null</code>.</p>
<pre><code class="language-js">fs.watch('somedir', (eventType, filename) => {
  console.log(`event type is: ${eventType}`);
  if (filename) {
    console.log(`filename provided: ${filename}`);
  } else {
    console.log('filename not provided');
  }
});
</code></pre>
<h2><code>fs.watchFile(filename[, options], listener)</code><span><a class="mark" href="#fs_fs_watchfile_filename_options_listener" id="fs_fs_watchfile_filename_options_listener">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.5.0</td>
<td><p>The <code>bigint</code> option is now supported.</p></td></tr>
<tr><td>v7.6.0</td>
<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol. Support is currently still <em>experimental</em>.</p></td></tr>
<tr><td>v0.1.31</td>
<td><p><span>Added in: v0.1.31</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>persistent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;integer></a> <strong>Default:</strong> <code>5007</code></li>
</ul>
</li>
<li>
<p><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>current</code> <a href="#fs_class_fs_stats" class="type">&#x3C;fs.Stats></a></li>
<li><code>previous</code> <a href="#fs_class_fs_stats" class="type">&#x3C;fs.Stats></a></li>
</ul>
</li>
</ul>
<p>Watch for changes on <code>filename</code>. The callback <code>listener</code> will be called each
time the file is accessed.</p>
<p>The <code>options</code> argument may be omitted. If provided, it should be an object. The
<code>options</code> object may contain a boolean named <code>persistent</code> that indicates
whether the process should continue to run as long as files are being watched.
The <code>options</code> object may specify an <code>interval</code> property indicating how often the
target should be polled in milliseconds.</p>
<p>The <code>listener</code> gets two arguments the current stat object and the previous
stat object:</p>
<pre><code class="language-js">fs.watchFile('message.text', (curr, prev) => {
  console.log(`the current mtime is: ${curr.mtime}`);
  console.log(`the previous mtime was: ${prev.mtime}`);
});
</code></pre>
<p>These stat objects are instances of <code>fs.Stat</code>. If the <code>bigint</code> option is <code>true</code>,
the numeric values in these objects are specified as <code>BigInt</code>s.</p>
<p>To be notified when the file was modified, not just accessed, it is necessary
to compare <code>curr.mtime</code> and <code>prev.mtime</code>.</p>
<p>When an <code>fs.watchFile</code> operation results in an <code>ENOENT</code> error, it
will invoke the listener once, with all the fields zeroed (or, for dates, the
Unix Epoch). 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 and then renamed a second time back to its original name</li>
</ul>
<h2><code>fs.write(fd, buffer[, offset[, length[, position]]], callback)</code><span><a class="mark" href="#fs_fs_write_fd_buffer_offset_length_position_callback" id="fs_fs_write_fd_buffer_offset_length_position_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code></p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.4.0</td>
<td><p>The <code>buffer</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>The <code>offset</code> and <code>length</code> parameters are optional now.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.0.2</td>
<td><p><span>Added in: v0.0.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
</ul>
</li>
</ul>
<p>Write <code>buffer</code> to the file specified by <code>fd</code>.</p>
<p><code>offset</code> determines the part of the buffer to be written, and <code>length</code> is
an integer specifying the number of bytes to write.</p>
<p><code>position</code> refers to the offset from the beginning of the file where this data
should be written. If <code>typeof position !== 'number'</code>, the data will be written
at the current position. See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>.</p>
<p>The callback will be given three arguments <code>(err, bytesWritten, buffer)</code> where
<code>bytesWritten</code> specifies how many <em>bytes</em> were written from <code>buffer</code>.</p>
<p>If this method is invoked as its <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed version, it returns
a <code>Promise</code> for an <code>Object</code> with <code>bytesWritten</code> and <code>buffer</code> properties.</p>
<p>It is unsafe to use <code>fs.write()</code> multiple times on the same file without waiting
for the callback. For this scenario, <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a> is
recommended.</p>
<p>On Linux, positional writes don't work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
<h2><code>fs.write(fd, string[, position[, encoding]], callback)</code><span><a class="mark" href="#fs_fs_write_fd_string_position_encoding_callback" id="fs_fs_write_fd_string_position_encoding_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>The <code>position</code> parameter is optional now.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v0.11.5</td>
<td><p><span>Added in: v0.11.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>written</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
</li>
</ul>
<p>Write <code>string</code> to the file specified by <code>fd</code>. If <code>string</code> is not a string, then
the value will be coerced to one.</p>
<p><code>position</code> refers to the offset from the beginning of the file where this data
should be written. If <code>typeof position !== 'number'</code> the data will be written at
the current position. See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>.</p>
<p><code>encoding</code> is the expected string encoding.</p>
<p>The callback will receive the arguments <code>(err, written, string)</code> where <code>written</code>
specifies how many <em>bytes</em> the passed string required to be written. Bytes
written is not necessarily the same as string characters written. See
<a href="#buffer_class_method_buffer_bytelength_string_encoding"><code>Buffer.byteLength</code></a>.</p>
<p>It is unsafe to use <code>fs.write()</code> multiple times on the same file without waiting
for the callback. For this scenario, <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a> is
recommended.</p>
<p>On Linux, positional writes don't work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
<p>On Windows, if the file descriptor is connected to the console (e.g. <code>fd == 1</code>
or <code>stdout</code>) a string containing non-ASCII characters will not be rendered
properly by default, regardless of the encoding used.
It is possible to configure the console to render UTF-8 properly by changing the
active codepage with the <code>chcp 65001</code> command. See the <a href="https://ss64.com/nt/chcp.html">chcp</a> docs for more
details.</p>
<h2><code>fs.writeFile(file, data[, options], callback)</code><span><a class="mark" href="#fs_fs_writefile_file_data_options_callback" id="fs_fs_writefile_file_data_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>data</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will throw a <code>TypeError</code> at runtime.</p></td></tr>
<tr><td>v7.4.0</td>
<td><p>The <code>data</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>The <code>callback</code> parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.1.29</td>
<td><p><span>Added in: v0.1.29</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;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">&#x3C;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">&#x3C;string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>When <code>file</code> is a filename, asynchronously writes data to the file, replacing the
file if it already exists.  <code>data</code> can be a string or a buffer.</p>
<p>When <code>file</code> is a file descriptor, the behavior is similar to calling
<code>fs.write()</code> directly (which is recommended). See the notes below on using
a file descriptor.</p>
<p>The <code>encoding</code> option is ignored if <code>data</code> is a buffer.</p>
<pre><code class="language-js">const data = new Uint8Array(Buffer.from('Hello Node.js'));
fs.writeFile('message.txt', data, (err) => {
  if (err) throw err;
  console.log('The file has been saved!');
});
</code></pre>
<p>If <code>options</code> is a string, then it specifies the encoding:</p>
<pre><code class="language-js">fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
</code></pre>
<p>It is unsafe to use <code>fs.writeFile()</code> multiple times on the same file without
waiting for the callback. For this scenario, <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a> is
recommended.</p>
<h3>Using <code>fs.writeFile()</code> with file descriptors<span><a class="mark" href="#fs_using_fs_writefile_with_file_descriptors" id="fs_using_fs_writefile_with_file_descriptors">#</a></span></h3>
<p>When <code>file</code> is a file descriptor, the behavior is almost identical to directly
calling <code>fs.write()</code> like:</p>
<pre><code class="language-js">fs.write(fd, Buffer.from(data, options.encoding), callback);
</code></pre>
<p>The difference from directly calling <code>fs.write()</code> is that under some unusual
conditions, <code>fs.write()</code> may write only part of the buffer and will need to be
retried to write the remaining data, whereas <code>fs.writeFile()</code> will retry until
the data is entirely written (or an error occurs).</p>
<p>The implications of this are a common source of confusion. In
the file descriptor case, the file is not replaced! The data is not necessarily
written to the beginning of the file, and the file's original data may remain
before and/or after the newly written data.</p>
<p>For example, if <code>fs.writeFile()</code> is called twice in a row, first to write the
string <code>'Hello'</code>, then to write the string <code>', World'</code>, the file would contain
<code>'Hello, World'</code>, and might contain some of the file's original data (depending
on the size of the original file, and the position of the file descriptor). If
a file name had been used instead of a descriptor, the file would be guaranteed
to contain only <code>', World'</code>.</p>
<h2><code>fs.writeFileSync(file, data[, options])</code><span><a class="mark" href="#fs_fs_writefilesync_file_data_options" id="fs_fs_writefilesync_file_data_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>data</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v7.4.0</td>
<td><p>The <code>data</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>file</code> parameter can be a file descriptor now.</p></td></tr>
<tr><td>v0.1.29</td>
<td><p><span>Added in: v0.1.29</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;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">&#x3C;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">&#x3C;string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li>
</ul>
</li>
</ul>
<p>Returns <code>undefined</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_writefile_file_data_options_callback"><code>fs.writeFile()</code></a>.</p>
<h2><code>fs.writeSync(fd, buffer[, offset[, length[, position]]])</code><span><a class="mark" href="#fs_fs_writesync_fd_buffer_offset_length_position" id="fs_fs_writesync_fd_buffer_offset_length_position">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>The <code>buffer</code> parameter can now be any <code>TypedArray</code> or a <code>DataView</code>.</p></td></tr>
<tr><td>v7.4.0</td>
<td><p>The <code>buffer</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>The <code>offset</code> and <code>length</code> parameters are optional now.</p></td></tr>
<tr><td>v0.1.21</td>
<td><p><span>Added in: v0.1.21</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of bytes written.</li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_write_fd_buffer_offset_length_position_callback"><code>fs.write(fd, buffer...)</code></a>.</p>
<h2><code>fs.writeSync(fd, string[, position[, encoding]])</code><span><a class="mark" href="#fs_fs_writesync_fd_string_position_encoding" id="fs_fs_writesync_fd_string_position_encoding">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.2.0</td>
<td><p>The <code>position</code> parameter is optional now.</p></td></tr>
<tr><td>v0.11.5</td>
<td><p><span>Added in: v0.11.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of bytes written.</li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_write_fd_string_position_encoding_callback"><code>fs.write(fd, string...)</code></a>.</p>
<h2><code>fs.writev(fd, buffers[, position], callback)</code><span><a class="mark" href="#fs_fs_writev_fd_buffers_position_callback" id="fs_fs_writev_fd_buffers_position_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.9.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">&#x3C;integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type">&#x3C;ArrayBufferView[]></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type">&#x3C;ArrayBufferView[]></a></li>
</ul>
</li>
</ul>
<p>Write an array of <code>ArrayBufferView</code>s to the file specified by <code>fd</code> using
<code>writev()</code>.</p>
<p><code>position</code> is 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.</p>
<p>The callback will be given three arguments: <code>err</code>, <code>bytesWritten</code>, and
<code>buffers</code>. <code>bytesWritten</code> is how many bytes were written from <code>buffers</code>.</p>
<p>If this method is <a href="#util_util_promisify_original"><code>util.promisify()</code></a>ed, it returns a <code>Promise</code> for an
<code>Object</code> with <code>bytesWritten</code> and <code>buffers</code> properties.</p>
<p>It is unsafe to use <code>fs.writev()</code> multiple times on the same file without
waiting for the callback. For this scenario, use <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a>.</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><code>fs.writevSync(fd, buffers[, position])</code><span><a class="mark" href="#fs_fs_writevsync_fd_buffers_position" id="fs_fs_writevsync_fd_buffers_position">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.9.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">&#x3C;integer></a></li>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type">&#x3C;ArrayBufferView[]></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of bytes written.</li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#fs_fs_writev_fd_buffers_position_callback"><code>fs.writev()</code></a>.</p>
<h2><code>fs</code> Promises API<span><a class="mark" href="#fs_fs_promises_api" id="fs_fs_promises_api">#</a></span></h2>
<p>The <code>fs.promises</code> API provides an alternative set of asynchronous file system
methods that return <code>Promise</code> objects rather than using callbacks. The
API is accessible via <code>require('fs').promises</code>.</p>
<h3>Class: <code>FileHandle</code><span><a class="mark" href="#fs_class_filehandle" id="fs_class_filehandle">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>A <code>FileHandle</code> object is a wrapper for a numeric file descriptor.
Instances of <code>FileHandle</code> are distinct from numeric file descriptors
in that they provide an object oriented API for working with files.</p>
<p>If a <code>FileHandle</code> is not closed using the
<code>filehandle.close()</code> method, it might automatically close the file descriptor
and will emit a process warning, thereby helping to prevent memory leaks.
Please do not rely on this behavior because it is unreliable and
the file may not be closed. Instead, always explicitly close <code>FileHandle</code>s.
Node.js may change this behavior in the future.</p>
<p>Instances of the <code>FileHandle</code> object are created internally by the
<code>fsPromises.open()</code> method.</p>
<p>Unlike the callback-based API (<code>fs.fstat()</code>, <code>fs.fchown()</code>, <code>fs.fchmod()</code>, and
so on), a numeric file descriptor is not used by the promise-based API. Instead,
the promise-based API uses the <code>FileHandle</code> class in order to help avoid
accidental leaking of unclosed file descriptors after a <code>Promise</code> is resolved or
rejected.</p>
<h4><code>filehandle.appendFile(data, options)</code><span><a class="mark" href="#fs_filehandle_appendfile_data_options" id="fs_filehandle_appendfile_data_options">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Alias of <a href="#fs_filehandle_writefile_data_options"><code>filehandle.writeFile()</code></a>.</p>
<p>When operating on file handles, the mode cannot be changed from what it was set
to with <a href="#fs_fspromises_open_path_flags_mode"><code>fsPromises.open()</code></a>. Therefore, this is equivalent to
<a href="#fs_filehandle_writefile_data_options"><code>filehandle.writeFile()</code></a>.</p>
<h4><code>filehandle.chmod(mode)</code><span><a class="mark" href="#fs_filehandle_chmod_mode" id="fs_filehandle_chmod_mode">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Modifies the permissions on the file. The <code>Promise</code> is resolved with no
arguments upon success.</p>
<h4><code>filehandle.chown(uid, gid)</code><span><a class="mark" href="#fs_filehandle_chown_uid_gid" id="fs_filehandle_chown_uid_gid">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Changes the ownership of the file then resolves the <code>Promise</code> with no arguments
upon success.</p>
<h4><code>filehandle.close()</code><span><a class="mark" href="#fs_filehandle_close" id="fs_filehandle_close">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> A <code>Promise</code> that will be resolved once the underlying
file descriptor is closed, or will be rejected if an error occurs while
closing.</li>
</ul>
<p>Closes the file descriptor.</p>
<pre><code class="language-js">const fsPromises = require('fs').promises;
async function openAndClose() {
  let filehandle;
  try {
    filehandle = await fsPromises.open('thefile.txt', 'r');
  } finally {
    if (filehandle !== undefined)
      await filehandle.close();
  }
}
</code></pre>
<h4><code>filehandle.datasync()</code><span><a class="mark" href="#fs_filehandle_datasync" id="fs_filehandle_datasync">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a>. The <code>Promise</code> is resolved with no arguments upon
success.</p>
<h4><code>filehandle.fd</code><span><a class="mark" href="#fs_filehandle_fd" id="fs_filehandle_fd">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The numeric file descriptor managed by the <code>FileHandle</code> object.</li>
</ul>
<h4><code>filehandle.read(buffer, offset, length, position)</code><span><a class="mark" href="#fs_filehandle_read_buffer_offset_length_position" id="fs_filehandle_read_buffer_offset_length_position">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Read data from the file.</p>
<p><code>buffer</code> is the buffer that the data will be written to.</p>
<p><code>offset</code> is the offset in the buffer to start writing at.</p>
<p><code>length</code> is an integer specifying the number of bytes to read.</p>
<p><code>position</code> is an argument specifying where to begin reading from in the file.
If <code>position</code> is <code>null</code>, data will be read from the current file position,
and the file position will be updated.
If <code>position</code> is an integer, the file position will remain unchanged.</p>
<p>Following successful read, the <code>Promise</code> is resolved with an object with a
<code>bytesRead</code> property specifying the number of bytes read, and a <code>buffer</code>
property that is a reference to the passed in <code>buffer</code> argument.</p>
<h4><code>filehandle.read(options)</code><span><a class="mark" href="#fs_filehandle_read_options" id="fs_filehandle_read_options">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> <strong>Default:</strong> <code>Buffer.alloc(16384)</code></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <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">&#x3C;integer></a> <strong>Default:</strong> <code>buffer.length</code></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>null</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<h4><code>filehandle.readFile(options)</code><span><a class="mark" href="#fs_filehandle_readfile_options" id="fs_filehandle_readfile_options">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> <strong>Default:</strong> <code>null</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronously reads the entire contents of a file.</p>
<p>The <code>Promise</code> is resolved with the contents of the file. If no encoding is
specified (using <code>options.encoding</code>), the data is returned as a <code>Buffer</code>
object. Otherwise, the data will be a string.</p>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<p>The <code>FileHandle</code> has to support reading.</p>
<p>If one or more <code>filehandle.read()</code> calls are made on a file handle and then a
<code>filehandle.readFile()</code> call is made, the data will be read from the current
position till the end of the file. It doesn't always read from the beginning
of the file.</p>
<h4><code>filehandle.readv(buffers[, position])</code><span><a class="mark" href="#fs_filehandle_readv_buffers_position" id="fs_filehandle_readv_buffers_position">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type">&#x3C;ArrayBufferView[]></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Read from a file and write to an array of <code>ArrayBufferView</code>s</p>
<p>The <code>Promise</code> is resolved with an object containing a <code>bytesRead</code> property
identifying the number of bytes read, and a <code>buffers</code> property containing
a reference to the <code>buffers</code> input.</p>
<p><code>position</code> is the offset from the beginning of the file where this data
should be read from. If <code>typeof position !== 'number'</code>, the data will be read
from the current position.</p>
<h4><code>filehandle.stat([options])</code><span><a class="mark" href="#fs_filehandle_stat_options" id="fs_filehandle_stat_options">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Added in: v10.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether the numeric values in the returned
<a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Retrieves the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> for the file.</p>
<h4><code>filehandle.sync()</code><span><a class="mark" href="#fs_filehandle_sync" id="fs_filehandle_sync">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a>. The <code>Promise</code> is resolved with no arguments upon
success.</p>
<h4><code>filehandle.truncate(len)</code><span><a class="mark" href="#fs_filehandle_truncate_len" id="fs_filehandle_truncate_len">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>0</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Truncates the file then resolves the <code>Promise</code> with no arguments upon success.</p>
<p>If the file was larger than <code>len</code> bytes, only the first <code>len</code> bytes will be
retained in the file.</p>
<p>For example, the following program retains only the first four bytes of the
file:</p>
<pre><code class="language-js">const fs = require('fs');
const fsPromises = fs.promises;

console.log(fs.readFileSync('temp.txt', 'utf8'));
// Prints: Node.js

async function doTruncate() {
  let filehandle = null;
  try {
    filehandle = await fsPromises.open('temp.txt', 'r+');
    await filehandle.truncate(4);
  } finally {
    if (filehandle) {
      // Close the file if it is opened.
      await filehandle.close();
    }
  }
  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints: Node
}

doTruncate().catch(console.error);
</code></pre>
<p>If the file previously was shorter than <code>len</code> bytes, it is extended, and the
extended part is filled with null bytes (<code>'\0'</code>):</p>
<pre><code class="language-js">const fs = require('fs');
const fsPromises = fs.promises;

console.log(fs.readFileSync('temp.txt', 'utf8'));
// Prints: Node.js

async function doTruncate() {
  let filehandle = null;
  try {
    filehandle = await fsPromises.open('temp.txt', 'r+');
    await filehandle.truncate(10);
  } finally {
    if (filehandle) {
      // Close the file if it is opened.
      await filehandle.close();
    }
  }
  console.log(fs.readFileSync('temp.txt', 'utf8'));  // Prints Node.js\0\0\0
}

doTruncate().catch(console.error);
</code></pre>
<p>The last three bytes are null bytes (<code>'\0'</code>), to compensate the over-truncation.</p>
<h4><code>filehandle.utimes(atime, mtime)</code><span><a class="mark" href="#fs_filehandle_utimes_atime_mtime" id="fs_filehandle_utimes_atime_mtime">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Change the file system timestamps of the object referenced by the <code>FileHandle</code>
then resolves the <code>Promise</code> with no arguments upon success.</p>
<p>This function does not work on AIX versions before 7.1, it will resolve the
<code>Promise</code> with an error using code <code>UV_ENOSYS</code>.</p>
<h4><code>filehandle.write(buffer[, offset[, length[, position]]])</code><span><a class="mark" href="#fs_filehandle_write_buffer_offset_length_position" id="fs_filehandle_write_buffer_offset_length_position">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Write <code>buffer</code> to the file.</p>
<p>The <code>Promise</code> is resolved with an object containing a <code>bytesWritten</code> property
identifying the number of bytes written, and a <code>buffer</code> property containing
a reference to the <code>buffer</code> written.</p>
<p><code>offset</code> determines the part of the buffer to be written, and <code>length</code> is
an integer specifying the number of bytes to write.</p>
<p><code>position</code> refers to the offset from the beginning of the file where this data
should be written. If <code>typeof position !== 'number'</code>, the data will be written
at the current position. See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>.</p>
<p>It is unsafe to use <code>filehandle.write()</code> multiple times on the same file
without waiting for the <code>Promise</code> to be resolved (or rejected). For this
scenario, use <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a>.</p>
<p>On Linux, positional writes do not work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
<h4><code>filehandle.write(string[, position[, encoding]])</code><span><a class="mark" href="#fs_filehandle_write_string_position_encoding" id="fs_filehandle_write_string_position_encoding">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Write <code>string</code> to the file. If <code>string</code> is not a string, then
the value will be coerced to one.</p>
<p>The <code>Promise</code> is resolved with an object containing a <code>bytesWritten</code> property
identifying the number of bytes written, and a <code>buffer</code> property containing
a reference to the <code>string</code> written.</p>
<p><code>position</code> refers to the offset from the beginning of the file where this data
should be written. If the type of <code>position</code> is not a <code>number</code> the data
will be written at the current position. See <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>.</p>
<p><code>encoding</code> is the expected string encoding.</p>
<p>It is unsafe to use <code>filehandle.write()</code> multiple times on the same file
without waiting for the <code>Promise</code> to be resolved (or rejected). For this
scenario, use <a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a>.</p>
<p>On Linux, positional writes do not work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
<h4><code>filehandle.writeFile(data, options)</code><span><a class="mark" href="#fs_filehandle_writefile_data_options" id="fs_filehandle_writefile_data_options">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronously writes data to a file, replacing the file if it already exists.
<code>data</code> can be a string or a buffer. The <code>Promise</code> will be resolved with no
arguments upon success.</p>
<p>The <code>encoding</code> option is ignored if <code>data</code> is a buffer.</p>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<p>The <code>FileHandle</code> has to support writing.</p>
<p>It is unsafe to use <code>filehandle.writeFile()</code> multiple times on the same file
without waiting for the <code>Promise</code> to be resolved (or rejected).</p>
<p>If one or more <code>filehandle.write()</code> calls are made on a file handle and then a
<code>filehandle.writeFile()</code> call is made, the data will be written from the
current position till the end of the file. It doesn't always write from the
beginning of the file.</p>
<h4><code>filehandle.writev(buffers[, position])</code><span><a class="mark" href="#fs_filehandle_writev_buffers_position" id="fs_filehandle_writev_buffers_position">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<ul>
<li><code>buffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type">&#x3C;ArrayBufferView[]></a></li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Write an array of <code>ArrayBufferView</code>s to the file.</p>
<p>The <code>Promise</code> is resolved with an object containing a <code>bytesWritten</code> property
identifying the number of bytes written, and a <code>buffers</code> property containing
a reference to the <code>buffers</code> input.</p>
<p><code>position</code> is 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.</p>
<p>It is unsafe to call <code>writev()</code> multiple times on the same file without waiting
for the previous operation to complete.</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>
<h3><code>fsPromises.access(path[, mode])</code><span><a class="mark" href="#fs_fspromises_access_path_mode" id="fs_fspromises_access_path_mode">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>fs.constants.F_OK</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Tests a user's permissions for the file or directory specified by <code>path</code>.
The <code>mode</code> argument is an optional integer that specifies the accessibility
checks to be performed. Check <a href="#fs_file_access_constants">File access constants</a> for possible values
of <code>mode</code>. It is possible to create a mask consisting of the bitwise OR of
two or more values (e.g. <code>fs.constants.W_OK | fs.constants.R_OK</code>).</p>
<p>If the accessibility check is successful, the <code>Promise</code> is resolved with no
value. If any of the accessibility checks fail, the <code>Promise</code> is rejected
with an <code>Error</code> object. The following example checks if the file
<code>/etc/passwd</code> can be read and written by the current process.</p>
<pre><code class="language-js">const fs = require('fs');
const fsPromises = fs.promises;

fsPromises.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK)
  .then(() => console.log('can access'))
  .catch(() => console.error('cannot access'));
</code></pre>
<p>Using <code>fsPromises.access()</code> to check for the accessibility of a file before
calling <code>fsPromises.open()</code> is not recommended. Doing so introduces a race
condition, since other processes may change the file's state between the two
calls. Instead, user code should open/read/write the file directly and handle
the error raised if the file is not accessible.</p>
<h3><code>fsPromises.appendFile(path, data[, options])</code><span><a class="mark" href="#fs_fspromises_appendfile_path_data_options" id="fs_fspromises_appendfile_path_data_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="#fs_class_filehandle" class="type">&#x3C;FileHandle></a> filename or <code>FileHandle</code></li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;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">&#x3C;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">&#x3C;string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronously append data to a file, creating the file if it does not yet
exist. <code>data</code> can be a string or a <a href="#buffer_buffer"><code>Buffer</code></a>. The <code>Promise</code> will be
resolved with no arguments upon success.</p>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<p>The <code>path</code> may be specified as a <code>FileHandle</code> that has been opened
for appending (using <code>fsPromises.open()</code>).</p>
<h3><code>fsPromises.chmod(path, mode)</code><span><a class="mark" href="#fs_fspromises_chmod_path_mode" id="fs_fspromises_chmod_path_mode">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Changes the permissions of a file then resolves the <code>Promise</code> with no
arguments upon succces.</p>
<h3><code>fsPromises.chown(path, uid, gid)</code><span><a class="mark" href="#fs_fspromises_chown_path_uid_gid" id="fs_fspromises_chown_path_uid_gid">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Changes the ownership of a file then resolves the <code>Promise</code> with no arguments
upon success.</p>
<h3><code>fsPromises.copyFile(src, dest[, flags])</code><span><a class="mark" href="#fs_fspromises_copyfile_src_dest_flags" id="fs_fspromises_copyfile_src_dest_flags">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;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">&#x3C;number></a> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronously copies <code>src</code> to <code>dest</code>. By default, <code>dest</code> is overwritten if it
already exists. The <code>Promise</code> will be resolved with no arguments upon success.</p>
<p>Node.js makes no guarantees about the atomicity of the copy operation. If an
error occurs after the destination file has been opened for writing, Node.js
will attempt to remove the destination.</p>
<p><code>flags</code> is an optional integer that specifies the behavior
of the copy operation. It is possible to create a mask consisting of the bitwise
OR of two or more values (e.g.
<code>fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE</code>).</p>
<ul>
<li><code>fs.constants.COPYFILE_EXCL</code>: The copy operation will fail if <code>dest</code> already
exists.</li>
<li><code>fs.constants.COPYFILE_FICLONE</code>: The copy operation will attempt to create a
copy-on-write reflink. If the platform does not support copy-on-write, then a
fallback copy mechanism is used.</li>
<li><code>fs.constants.COPYFILE_FICLONE_FORCE</code>: The copy operation will attempt to
create a copy-on-write reflink. If the platform does not support copy-on-write,
then the operation will fail.</li>
</ul>
<pre><code class="language-js">const fsPromises = require('fs').promises;

// destination.txt will be created or overwritten by default.
fsPromises.copyFile('source.txt', 'destination.txt')
  .then(() => console.log('source.txt was copied to destination.txt'))
  .catch(() => console.log('The file could not be copied'));
</code></pre>
<p>If the third argument is a number, then it specifies <code>flags</code>:</p>
<pre><code class="language-js">const fs = require('fs');
const fsPromises = fs.promises;
const { COPYFILE_EXCL } = fs.constants;

// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
fsPromises.copyFile('source.txt', 'destination.txt', COPYFILE_EXCL)
  .then(() => console.log('source.txt was copied to destination.txt'))
  .catch(() => console.log('The file could not be copied'));
</code></pre>
<h3><code>fsPromises.lchmod(path, mode)</code><span><a class="mark" href="#fs_fspromises_lchmod_path_mode" id="fs_fspromises_lchmod_path_mode">#</a></span></h3>
<div class="api_metadata">
<span>Deprecated since: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Changes the permissions on a symbolic link then resolves the <code>Promise</code> with
no arguments upon success. This method is only implemented on macOS.</p>
<h3><code>fsPromises.lchown(path, uid, gid)</code><span><a class="mark" href="#fs_fspromises_lchown_path_uid_gid" id="fs_fspromises_lchown_path_uid_gid">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.6.0</td>
<td><p>This API is no longer deprecated.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Added in: v10.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>uid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>gid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Changes the ownership on a symbolic link then resolves the <code>Promise</code> with
no arguments upon success.</p>
<h3><code>fsPromises.link(existingPath, newPath)</code><span><a class="mark" href="#fs_fspromises_link_existingpath_newpath" id="fs_fspromises_link_existingpath_newpath">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>existingPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a>. The <code>Promise</code> is resolved with no arguments upon success.</p>
<h3><code>fsPromises.lstat(path[, options])</code><span><a class="mark" href="#fs_fspromises_lstat_path_options" id="fs_fspromises_lstat_path_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Added in: v10.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether the numeric values in the returned
<a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a>. The <code>Promise</code> is resolved with the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object
for the given symbolic link <code>path</code>.</p>
<h3><code>fsPromises.mkdir(path[, options])</code><span><a class="mark" href="#fs_fspromises_mkdir_path_options" id="fs_fspromises_mkdir_path_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></p>
<ul>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Not supported on Windows. <strong>Default:</strong> <code>0o777</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronously creates a directory then resolves the <code>Promise</code> with either no
arguments, or the first directory path created if <code>recursive</code> is <code>true</code>.</p>
<p>The optional <code>options</code> argument can be an integer specifying mode (permission
and sticky bits), or an object with a <code>mode</code> property and a <code>recursive</code>
property indicating whether parent directories should be created. Calling
<code>fsPromises.mkdir()</code> when <code>path</code> is a directory that exists results in a
rejection only when <code>recursive</code> is false.</p>
<h3><code>fsPromises.mkdtemp(prefix[, options])</code><span><a class="mark" href="#fs_fspromises_mkdtemp_prefix_options" id="fs_fspromises_mkdtemp_prefix_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>prefix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Creates a unique temporary directory and resolves the <code>Promise</code> with the created
directory path. A unique directory name is generated by appending six random
characters to the end of the provided <code>prefix</code>. Due to platform
inconsistencies, avoid trailing <code>X</code> characters in <code>prefix</code>. Some platforms,
notably the BSDs, can return more than six random characters, and replace
trailing <code>X</code> characters in <code>prefix</code> with random characters.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use.</p>
<pre><code class="language-js">fsPromises.mkdtemp(path.join(os.tmpdir(), 'foo-'))
  .catch(console.error);
</code></pre>
<p>The <code>fsPromises.mkdtemp()</code> method will append the six randomly selected
characters directly to the <code>prefix</code> string. For instance, given a directory
<code>/tmp</code>, if the intention is to create a temporary directory <em>within</em> <code>/tmp</code>, the
<code>prefix</code> must end with a trailing platform-specific path separator
(<code>require('path').sep</code>).</p>
<h3><code>fsPromises.open(path, flags[, mode])</code><span><a class="mark" href="#fs_fspromises_open_path_flags_mode" id="fs_fspromises_open_path_flags_mode">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.1.0</td>
<td><p>The <code>flags</code> argument is now optional and defaults to <code>'r'</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Added in: v10.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>.
<strong>Default:</strong> <code>'r'</code>.</li>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>0o666</code> (readable and writable)</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronous file open that returns a <code>Promise</code> that, when resolved, yields a
<code>FileHandle</code> object. See <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a>.</p>
<p><code>mode</code> sets the file mode (permission and sticky bits), but only if the file was
created.</p>
<p>Some characters (<code>&#x3C; > : " / \ | ? *</code>) are reserved under Windows as documented
by <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file">Naming Files, Paths, and Namespaces</a>. Under NTFS, if the filename contains
a colon, Node.js will open a file system stream, as described by
<a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams">this MSDN page</a>.</p>
<h3><code>fsPromises.opendir(path[, options])</code><span><a class="mark" href="#fs_fspromises_opendir_path_options" id="fs_fspromises_opendir_path_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>bufferSize</code> option was introduced.</p></td></tr>
<tr><td>v12.12.0</td>
<td><p><span>Added in: v12.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>bufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Number of directory entries that are buffered
internally when reading from the directory. Higher values lead to better
performance but higher memory usage. <strong>Default:</strong> <code>32</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> containing <a href="#fs_class_fs_dir" class="type">&#x3C;fs.Dir></a></li>
</ul>
<p>Asynchronously open a directory. See <a href="http://man7.org/linux/man-pages/man3/opendir.3.html"><code>opendir(3)</code></a>.</p>
<p>Creates an <a href="#fs_class_fs_dir"><code>fs.Dir</code></a>, which contains all further functions for reading from
and cleaning up the directory.</p>
<p>The <code>encoding</code> option sets the encoding for the <code>path</code> while opening the
directory and subsequent read operations.</p>
<p>Example using async iteration:</p>
<pre><code class="language-js">const fs = require('fs');

async function print(path) {
  const dir = await fs.promises.opendir(path);
  for await (const dirent of dir) {
    console.log(dirent.name);
  }
}
print('./').catch(console.error);
</code></pre>
<h3><code>fsPromises.readdir(path[, options])</code><span><a class="mark" href="#fs_fspromises_readdir_path_options" id="fs_fspromises_readdir_path_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.11.0</td>
<td><p>New option <code>withFileTypes</code> was added.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Added in: v10.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>withFileTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Reads the contents of a directory then resolves the <code>Promise</code> with an array
of the names of the files in the directory excluding <code>'.'</code> and <code>'..'</code>.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the filenames. If the <code>encoding</code> is set to <code>'buffer'</code>, the filenames returned
will be passed as <code>Buffer</code> objects.</p>
<p>If <code>options.withFileTypes</code> is set to <code>true</code>, the resolved array will contain
<a href="#fs_class_fs_dirent"><code>fs.Dirent</code></a> objects.</p>
<pre><code class="language-js">const fs = require('fs');

async function print(path) {
  const files = await fs.promises.readdir(path);
  for (const file of files) {
    console.log(file);
  }
}
print('./').catch(console.error);
</code></pre>
<h3><code>fsPromises.readFile(path[, options])</code><span><a class="mark" href="#fs_fspromises_readfile_path_options" id="fs_fspromises_readfile_path_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="#fs_class_filehandle" class="type">&#x3C;FileHandle></a> filename or <code>FileHandle</code></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;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">&#x3C;string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronously reads the entire contents of a file.</p>
<p>The <code>Promise</code> is resolved with the contents of the file. If no encoding is
specified (using <code>options.encoding</code>), the data is returned as a <code>Buffer</code>
object. Otherwise, the data will be a string.</p>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<p>When the <code>path</code> is a directory, the behavior of <code>fsPromises.readFile()</code> is
platform-specific. On macOS, Linux, and Windows, the promise will be rejected
with an error. On FreeBSD, a representation of the directory's contents will be
returned.</p>
<p>Any specified <code>FileHandle</code> has to support reading.</p>
<h3><code>fsPromises.readlink(path[, options])</code><span><a class="mark" href="#fs_fspromises_readlink_path_options" id="fs_fspromises_readlink_path_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a>. The <code>Promise</code> is resolved with the <code>linkString</code> upon
success.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the link path returned. If the <code>encoding</code> is set to <code>'buffer'</code>, the link path
returned will be passed as a <code>Buffer</code> object.</p>
<h3><code>fsPromises.realpath(path[, options])</code><span><a class="mark" href="#fs_fspromises_realpath_path_options" id="fs_fspromises_realpath_path_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Determines the actual location of <code>path</code> using the same semantics as the
<code>fs.realpath.native()</code> function then resolves the <code>Promise</code> with the resolved
path.</p>
<p>Only paths that can be converted to UTF8 strings are supported.</p>
<p>The optional <code>options</code> argument can be a string specifying an encoding, or an
object with an <code>encoding</code> property specifying the character encoding to use for
the path. If the <code>encoding</code> is set to <code>'buffer'</code>, the path returned will be
passed as a <code>Buffer</code> object.</p>
<p>On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on <code>/proc</code> in order for this function to work. Glibc does not have
this restriction.</p>
<h3><code>fsPromises.rename(oldPath, newPath)</code><span><a class="mark" href="#fs_fspromises_rename_oldpath_newpath" id="fs_fspromises_rename_oldpath_newpath">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>oldPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>newPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Renames <code>oldPath</code> to <code>newPath</code> and resolves the <code>Promise</code> with no arguments
upon success.</p>
<h3><code>fsPromises.rmdir(path[, options])</code><span><a class="mark" href="#fs_fspromises_rmdir_path_options" id="fs_fspromises_rmdir_path_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>maxBusyTries</code> option is renamed to <code>maxRetries</code>, and its default is 0. The <code>emfileWait</code> option has been removed, and <code>EMFILE</code> errors use the same retry logic as other errors. The <code>retryDelay</code> option is now supported. <code>ENFILE</code> errors are now retried.</p></td></tr>
<tr><td>v12.10.0</td>
<td><p>The <code>recursive</code>, <code>maxBusyTries</code>, and <code>emfileWait</code> options are now supported.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Added in: v10.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Recursive removal is experimental.</div><p></p>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>maxRetries</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> If an <code>EBUSY</code>, <code>EMFILE</code>, <code>ENFILE</code>, <code>ENOTEMPTY</code>, or
<code>EPERM</code> error is encountered, Node.js will retry the operation with a linear
backoff wait of <code>retryDelay</code> ms longer on each try. This option represents the
number of retries. This option is ignored if the <code>recursive</code> option is not
<code>true</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, perform a recursive directory removal. In
recursive mode, errors are not reported if <code>path</code> does not exist, and
operations are retried on failure. <strong>Default:</strong> <code>false</code>.</li>
<li><code>retryDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The amount of time in milliseconds to wait between
retries. This option is ignored if the <code>recursive</code> option is not <code>true</code>.
<strong>Default:</strong> <code>100</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Removes the directory identified by <code>path</code> then resolves the <code>Promise</code> with
no arguments upon success.</p>
<p>Using <code>fsPromises.rmdir()</code> on a file (not a directory) results in the
<code>Promise</code> being rejected with an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code>
error on POSIX.</p>
<h3><code>fsPromises.stat(path[, options])</code><span><a class="mark" href="#fs_fspromises_stat_path_options" id="fs_fspromises_stat_path_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.5.0</td>
<td><p>Accepts an additional <code>options</code> object to specify whether the numeric values returned should be bigint.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Added in: v10.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>bigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether the numeric values in the returned
<a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>The <code>Promise</code> is resolved with the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object for the given <code>path</code>.</p>
<h3><code>fsPromises.symlink(target, path[, type])</code><span><a class="mark" href="#fs_fspromises_symlink_target_path_type" id="fs_fspromises_symlink_target_path_type">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'file'</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Creates a symbolic link then resolves the <code>Promise</code> with no arguments upon
success.</p>
<p>The <code>type</code> argument is only used on Windows platforms and can be one of <code>'dir'</code>,
<code>'file'</code>, or <code>'junction'</code>. Windows junction points require the destination path
to be absolute. When using <code>'junction'</code>, the <code>target</code> argument will
automatically be normalized to absolute path.</p>
<h3><code>fsPromises.truncate(path[, len])</code><span><a class="mark" href="#fs_fspromises_truncate_path_len" id="fs_fspromises_truncate_path_len">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>len</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>0</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Truncates the <code>path</code> then resolves the <code>Promise</code> with no arguments upon
success. The <code>path</code> <em>must</em> be a string or <code>Buffer</code>.</p>
<h3><code>fsPromises.unlink(path)</code><span><a class="mark" href="#fs_fspromises_unlink_path" id="fs_fspromises_unlink_path">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>. The <code>Promise</code> is resolved with no arguments upon
success.</p>
<h3><code>fsPromises.utimes(path, atime, mtime)</code><span><a class="mark" href="#fs_fspromises_utimes_path_atime_mtime" id="fs_fspromises_utimes_path_atime_mtime">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>atime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
<li><code>mtime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" class="type">&#x3C;Date></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Change the file system timestamps of the object referenced by <code>path</code> then
resolves the <code>Promise</code> with no arguments upon success.</p>
<p>The <code>atime</code> and <code>mtime</code> arguments follow these rules:</p>
<ul>
<li>Values can be either numbers representing Unix epoch time, <code>Date</code>s, or a
numeric string like <code>'123456789.0'</code>.</li>
<li>If the value can not be converted to a number, or is <code>NaN</code>, <code>Infinity</code> or
<code>-Infinity</code>, an <code>Error</code> will be thrown.</li>
</ul>
<h3><code>fsPromises.writeFile(file, data[, options])</code><span><a class="mark" href="#fs_fspromises_writefile_file_data_options" id="fs_fspromises_writefile_file_data_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="#fs_class_filehandle" class="type">&#x3C;FileHandle></a> filename or <code>FileHandle</code></li>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;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">&#x3C;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">&#x3C;string></a> See <a href="#fs_file_system_flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Asynchronously writes data to a file, replacing the file if it already exists.
<code>data</code> can be a string or a buffer. The <code>Promise</code> will be resolved with no
arguments upon success.</p>
<p>The <code>encoding</code> option is ignored if <code>data</code> is a buffer.</p>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<p>Any specified <code>FileHandle</code> has to support writing.</p>
<p>It is unsafe to use <code>fsPromises.writeFile()</code> multiple times on the same file
without waiting for the <code>Promise</code> to be resolved (or rejected).</p>
<h2>FS constants<span><a class="mark" href="#fs_fs_constants_1" id="fs_fs_constants_1">#</a></span></h2>
<p>The following constants are exported by <code>fs.constants</code>.</p>
<p>Not every constant will be available on every operating system.</p>
<p>To use more than one constant, use the bitwise OR <code>|</code> operator.</p>
<p>Example:</p>
<pre><code class="language-js">const fs = require('fs');

const {
  O_RDWR,
  O_CREAT,
  O_EXCL
} = fs.constants;

fs.open('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {
  // ...
});
</code></pre>
<h3>File access constants<span><a class="mark" href="#fs_file_access_constants" id="fs_file_access_constants">#</a></span></h3>
<p>The following constants are meant for use with <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a>.</p>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>F_OK</code></td>
    <td>Flag indicating that the file is visible to the calling process.
     This is useful for determining if a file exists, but says nothing
     about <code>rwx</code> permissions. Default if no mode is specified.</td>
  </tr>
  <tr>
    <td><code>R_OK</code></td>
    <td>Flag indicating that the file can be read by the calling process.</td>
  </tr>
  <tr>
    <td><code>W_OK</code></td>
    <td>Flag indicating that the file can be written by the calling
    process.</td>
  </tr>
  <tr>
    <td><code>X_OK</code></td>
    <td>Flag indicating that the file can be executed by the calling
    process. This has no effect on Windows
    (will behave like <code>fs.constants.F_OK</code>).</td>
  </tr>
</tbody></table>
<h3>File copy constants<span><a class="mark" href="#fs_file_copy_constants" id="fs_file_copy_constants">#</a></span></h3>
<p>The following constants are meant for use with <a href="#fs_fs_copyfile_src_dest_flags_callback"><code>fs.copyFile()</code></a>.</p>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>COPYFILE_EXCL</code></td>
    <td>If present, the copy operation will fail with an error if the
    destination path already exists.</td>
  </tr>
  <tr>
    <td><code>COPYFILE_FICLONE</code></td>
    <td>If present, the copy operation will attempt to create a
    copy-on-write reflink. If the underlying platform does not support
    copy-on-write, then a fallback copy mechanism is used.</td>
  </tr>
  <tr>
    <td><code>COPYFILE_FICLONE_FORCE</code></td>
    <td>If present, the copy operation will attempt to create a
    copy-on-write reflink. If the underlying platform does not support
    copy-on-write, then the operation will fail with an error.</td>
  </tr>
</tbody></table>
<h3>File open constants<span><a class="mark" href="#fs_file_open_constants" id="fs_file_open_constants">#</a></span></h3>
<p>The following constants are meant for use with <code>fs.open()</code>.</p>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>O_RDONLY</code></td>
    <td>Flag indicating to open a file for read-only access.</td>
  </tr>
  <tr>
    <td><code>O_WRONLY</code></td>
    <td>Flag indicating to open a file for write-only access.</td>
  </tr>
  <tr>
    <td><code>O_RDWR</code></td>
    <td>Flag indicating to open a file for read-write access.</td>
  </tr>
  <tr>
    <td><code>O_CREAT</code></td>
    <td>Flag indicating to create the file if it does not already exist.</td>
  </tr>
  <tr>
    <td><code>O_EXCL</code></td>
    <td>Flag indicating that opening a file should fail if the
    <code>O_CREAT</code> flag is set and the file already exists.</td>
  </tr>
  <tr>
    <td><code>O_NOCTTY</code></td>
    <td>Flag indicating that if path identifies a terminal device, opening the
    path shall not cause that terminal to become the controlling terminal for
    the process (if the process does not already have one).</td>
  </tr>
  <tr>
    <td><code>O_TRUNC</code></td>
    <td>Flag indicating that if the file exists and is a regular file, and the
    file is opened successfully for write access, its length shall be truncated
    to zero.</td>
  </tr>
  <tr>
    <td><code>O_APPEND</code></td>
    <td>Flag indicating that data will be appended to the end of the file.</td>
  </tr>
  <tr>
    <td><code>O_DIRECTORY</code></td>
    <td>Flag indicating that the open should fail if the path is not a
    directory.</td>
  </tr>
  <tr>
  <td><code>O_NOATIME</code></td>
    <td>Flag indicating reading accesses to the file system will no longer
    result in an update to the <code>atime</code> information associated with
    the file. This flag is available on Linux operating systems only.</td>
  </tr>
  <tr>
    <td><code>O_NOFOLLOW</code></td>
    <td>Flag indicating that the open should fail if the path is a symbolic
    link.</td>
  </tr>
  <tr>
    <td><code>O_SYNC</code></td>
    <td>Flag indicating that the file is opened for synchronized I/O with write
    operations waiting for file integrity.</td>
  </tr>
  <tr>
    <td><code>O_DSYNC</code></td>
    <td>Flag indicating that the file is opened for synchronized I/O with write
    operations waiting for data integrity.</td>
  </tr>
  <tr>
    <td><code>O_SYMLINK</code></td>
    <td>Flag indicating to open the symbolic link itself rather than the
    resource it is pointing to.</td>
  </tr>
  <tr>
    <td><code>O_DIRECT</code></td>
    <td>When set, an attempt will be made to minimize caching effects of file
    I/O.</td>
  </tr>
  <tr>
    <td><code>O_NONBLOCK</code></td>
    <td>Flag indicating to open the file in nonblocking mode when possible.</td>
  </tr>
  <tr>
    <td><code>UV_FS_O_FILEMAP</code></td>
    <td>When set, a memory file mapping is used to access the file. This flag
    is available on Windows operating systems only. On other operating systems,
    this flag is ignored.</td>
  </tr>
</tbody></table>
<h3>File type constants<span><a class="mark" href="#fs_file_type_constants" id="fs_file_type_constants">#</a></span></h3>
<p>The following constants are meant for use with the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object's
<code>mode</code> property for determining a file's type.</p>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>S_IFMT</code></td>
    <td>Bit mask used to extract the file type code.</td>
  </tr>
  <tr>
    <td><code>S_IFREG</code></td>
    <td>File type constant for a regular file.</td>
  </tr>
  <tr>
    <td><code>S_IFDIR</code></td>
    <td>File type constant for a directory.</td>
  </tr>
  <tr>
    <td><code>S_IFCHR</code></td>
    <td>File type constant for a character-oriented device file.</td>
  </tr>
  <tr>
    <td><code>S_IFBLK</code></td>
    <td>File type constant for a block-oriented device file.</td>
  </tr>
  <tr>
    <td><code>S_IFIFO</code></td>
    <td>File type constant for a FIFO/pipe.</td>
  </tr>
  <tr>
    <td><code>S_IFLNK</code></td>
    <td>File type constant for a symbolic link.</td>
  </tr>
  <tr>
    <td><code>S_IFSOCK</code></td>
    <td>File type constant for a socket.</td>
  </tr>
</tbody></table>
<h3>File mode constants<span><a class="mark" href="#fs_file_mode_constants" id="fs_file_mode_constants">#</a></span></h3>
<p>The following constants are meant for use with the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object's
<code>mode</code> property for determining the access permissions for a file.</p>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>S_IRWXU</code></td>
    <td>File mode indicating readable, writable, and executable by owner.</td>
  </tr>
  <tr>
    <td><code>S_IRUSR</code></td>
    <td>File mode indicating readable by owner.</td>
  </tr>
  <tr>
    <td><code>S_IWUSR</code></td>
    <td>File mode indicating writable by owner.</td>
  </tr>
  <tr>
    <td><code>S_IXUSR</code></td>
    <td>File mode indicating executable by owner.</td>
  </tr>
  <tr>
    <td><code>S_IRWXG</code></td>
    <td>File mode indicating readable, writable, and executable by group.</td>
  </tr>
  <tr>
    <td><code>S_IRGRP</code></td>
    <td>File mode indicating readable by group.</td>
  </tr>
  <tr>
    <td><code>S_IWGRP</code></td>
    <td>File mode indicating writable by group.</td>
  </tr>
  <tr>
    <td><code>S_IXGRP</code></td>
    <td>File mode indicating executable by group.</td>
  </tr>
  <tr>
    <td><code>S_IRWXO</code></td>
    <td>File mode indicating readable, writable, and executable by others.</td>
  </tr>
  <tr>
    <td><code>S_IROTH</code></td>
    <td>File mode indicating readable by others.</td>
  </tr>
  <tr>
    <td><code>S_IWOTH</code></td>
    <td>File mode indicating writable by others.</td>
  </tr>
  <tr>
    <td><code>S_IXOTH</code></td>
    <td>File mode indicating executable by others.</td>
  </tr>
</tbody></table>
<h2>File system flags<span><a class="mark" href="#fs_file_system_flags" id="fs_file_system_flags">#</a></span></h2>
<p>The following flags are available wherever the <code>flag</code> option takes a
string.</p>
<ul>
<li>
<p><code>'a'</code>: Open file for appending.
The file is created if it does not exist.</p>
</li>
<li>
<p><code>'ax'</code>: Like <code>'a'</code> but fails if the path exists.</p>
</li>
<li>
<p><code>'a+'</code>: Open file for reading and appending.
The file is created if it does not exist.</p>
</li>
<li>
<p><code>'ax+'</code>: Like <code>'a+'</code> but fails if the path exists.</p>
</li>
<li>
<p><code>'as'</code>: Open file for appending in synchronous mode.
The file is created if it does not exist.</p>
</li>
<li>
<p><code>'as+'</code>: Open file for reading and appending in synchronous mode.
The file is created if it does not exist.</p>
</li>
<li>
<p><code>'r'</code>: Open file for reading.
An exception occurs if the file does not exist.</p>
</li>
<li>
<p><code>'r+'</code>: Open file for reading and writing.
An exception occurs if the file does not exist.</p>
</li>
<li>
<p><code>'rs+'</code>: Open file for reading and writing in synchronous mode. Instructs
the operating system to bypass the local file system cache.</p>
<p>This is primarily useful for opening files on NFS mounts as it allows
skipping the potentially stale local cache. It has a very real impact on
I/O performance so using this flag is not recommended unless it is needed.</p>
<p>This doesn't turn <code>fs.open()</code> or <code>fsPromises.open()</code> into a synchronous
blocking call. If synchronous operation is desired, something like
<code>fs.openSync()</code> should be used.</p>
</li>
<li>
<p><code>'w'</code>: Open file for writing.
The file is created (if it does not exist) or truncated (if it exists).</p>
</li>
<li>
<p><code>'wx'</code>: Like <code>'w'</code> but fails if the path exists.</p>
</li>
<li>
<p><code>'w+'</code>: Open file for reading and writing.
The file is created (if it does not exist) or truncated (if it exists).</p>
</li>
<li>
<p><code>'wx+'</code>: Like <code>'w+'</code> but fails if the path exists.</p>
</li>
</ul>
<p><code>flag</code> can also be a number as documented by <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a>; commonly used constants
are available from <code>fs.constants</code>. On Windows, flags are translated to
their equivalent ones where applicable, e.g. <code>O_WRONLY</code> to <code>FILE_GENERIC_WRITE</code>,
or <code>O_EXCL|O_CREAT</code> to <code>CREATE_NEW</code>, as accepted by <code>CreateFileW</code>.</p>
<p>The exclusive flag <code>'x'</code> (<code>O_EXCL</code> flag in <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a>) ensures that path is newly
created. On POSIX systems, path is considered to exist even if it is a symlink
to a non-existent file. The exclusive flag may or may not work with network
file systems.</p>
<p>On Linux, positional writes don't work when the file is opened in append mode.
The kernel ignores the position argument and always appends the data to
the end of the file.</p>
<p>Modifying a file rather than replacing it may require a flags mode of <code>'r+'</code>
rather than the default mode <code>'w'</code>.</p>
<p>The behavior of some flags are platform-specific. As such, opening a directory
on macOS and Linux with the <code>'a+'</code> flag, as in the example below, will return an
error. In contrast, on Windows and FreeBSD, a file descriptor or a <code>FileHandle</code>
will be returned.</p>
<pre><code class="language-js">// macOS and Linux
fs.open('&#x3C;directory>', 'a+', (err, fd) => {
  // => [Error: EISDIR: illegal operation on a directory, open &#x3C;directory>]
});

// Windows and FreeBSD
fs.open('&#x3C;directory>', 'a+', (err, fd) => {
  // => null, &#x3C;fd>
});
</code></pre>
<p>On Windows, opening an existing hidden file using the <code>'w'</code> flag (either
through <code>fs.open()</code> or <code>fs.writeFile()</code> or <code>fsPromises.open()</code>) will fail with
<code>EPERM</code>. Existing hidden files can be opened for writing with the <code>'r+'</code> flag.</p>
<p>A call to <code>fs.ftruncate()</code> or <code>filehandle.truncate()</code> can be used to reset
the file contents.</p>
<h1>Global objects<span><a class="mark" href="#globals_global_objects" id="globals_global_objects">#</a></span></h1>


<p>These objects are available in all modules. The following variables may appear
to be global but are not. They exist only in the scope of modules, see the
<a href="modules.html">module system documentation</a>:</p>
<ul>
<li><a href="#modules_dirname"><code>__dirname</code></a></li>
<li><a href="#modules_filename"><code>__filename</code></a></li>
<li><a href="#modules_exports"><code>exports</code></a></li>
<li><a href="#modules_module"><code>module</code></a></li>
<li><a href="#modules_require_id"><code>require()</code></a></li>
</ul>
<p>The objects listed here are specific to Node.js. There are <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: <code>Buffer</code><span><a class="mark" href="#globals_class_buffer" id="globals_class_buffer">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.103</span>
</div>

<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Used to handle binary data. See the <a href="buffer.html">buffer section</a>.</p>
<h2><code>__dirname</code><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><code>__filename</code><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><code>clearImmediate(immediateObject)</code><span><a class="mark" href="#globals_clearimmediate_immediateobject" id="globals_clearimmediate_immediateobject">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>

<p><a href="#timers_clearimmediate_immediate"><code>clearImmediate</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<h2><code>clearInterval(intervalObject)</code><span><a class="mark" href="#globals_clearinterval_intervalobject" id="globals_clearinterval_intervalobject">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>

<p><a href="#timers_clearinterval_timeout"><code>clearInterval</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<h2><code>clearTimeout(timeoutObject)</code><span><a class="mark" href="#globals_cleartimeout_timeoutobject" id="globals_cleartimeout_timeoutobject">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>

<p><a href="#timers_cleartimeout_timeout"><code>clearTimeout</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<h2><code>console</code><span><a class="mark" href="#globals_console" id="globals_console">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div>

<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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><code>exports</code><span><a class="mark" href="#globals_exports" id="globals_exports">#</a></span></h2>
<p>This variable may appear to be global but is not. See <a href="#modules_exports"><code>exports</code></a>.</p>
<h2><code>global</code><span><a class="mark" href="#globals_global" id="globals_global">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div>

<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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><code>module</code><span><a class="mark" href="#globals_module" id="globals_module">#</a></span></h2>
<p>This variable may appear to be global but is not. See <a href="#modules_module"><code>module</code></a>.</p>
<h2><code>process</code><span><a class="mark" href="#globals_process" id="globals_process">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.7</span>
</div>

<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>The process object. See the <a href="#process_process"><code>process</code> object</a> section.</p>
<h2><code>queueMicrotask(callback)</code><span><a class="mark" href="#globals_queuemicrotask_callback" id="globals_queuemicrotask_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.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">&#x3C;Function></a> Function to be queued.</li>
</ul>
<p>The <code>queueMicrotask()</code> method queues a microtask to invoke <code>callback</code>. If
<code>callback</code> throws an exception, the <a href="#process_process"><code>process</code> object</a> <code>'uncaughtException'</code>
event will be emitted.</p>
<p>The microtask queue is managed by V8 and may be used in a similar manner to
the <a href="#process_process_nexttick_callback_args"><code>process.nextTick()</code></a> queue, which is managed by Node.js. The
<code>process.nextTick()</code> queue is always processed before the microtask queue
within each turn of the Node.js event loop.</p>
<pre><code class="language-js">// Here, `queueMicrotask()` is used to ensure the 'load' event is always
// emitted asynchronously, and therefore consistently. Using
// `process.nextTick()` here would result in the 'load' event always emitting
// before any other promise jobs.

DataHandler.prototype.load = async function load(key) {
  const hit = this._cache.get(url);
  if (hit !== undefined) {
    queueMicrotask(() => {
      this.emit('load', hit);
    });
    return;
  }

  const data = await fetchData(key);
  this._cache.set(url, data);
  this.emit('load', data);
};
</code></pre>
<h2><code>require()</code><span><a class="mark" href="#globals_require" id="globals_require">#</a></span></h2>
<p>This variable may appear to be global but is not. See <a href="#modules_require_id"><code>require()</code></a>.</p>
<h2><code>setImmediate(callback[, ...args])</code><span><a class="mark" href="#globals_setimmediate_callback_args" id="globals_setimmediate_callback_args">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>

<p><a href="#timers_setimmediate_callback_args"><code>setImmediate</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<h2><code>setInterval(callback, delay[, ...args])</code><span><a class="mark" href="#globals_setinterval_callback_delay_args" id="globals_setinterval_callback_delay_args">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>

<p><a href="#timers_setinterval_callback_delay_args"><code>setInterval</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<h2><code>setTimeout(callback, delay[, ...args])</code><span><a class="mark" href="#globals_settimeout_callback_delay_args" id="globals_settimeout_callback_delay_args">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>

<p><a href="#timers_settimeout_callback_delay_args"><code>setTimeout</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<h2><code>TextDecoder</code><span><a class="mark" href="#globals_textdecoder" id="globals_textdecoder">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.0.0</span>
</div>

<p>The WHATWG <code>TextDecoder</code> class. See the <a href="#util_class_util_textdecoder"><code>TextDecoder</code></a> section.</p>
<h2><code>TextEncoder</code><span><a class="mark" href="#globals_textencoder" id="globals_textencoder">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.0.0</span>
</div>

<p>The WHATWG <code>TextEncoder</code> class. See the <a href="#util_class_util_textencoder"><code>TextEncoder</code></a> section.</p>
<h2><code>URL</code><span><a class="mark" href="#globals_url" id="globals_url">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>

<p>The WHATWG <code>URL</code> class. See the <a href="#url_class_url"><code>URL</code></a> section.</p>
<h2><code>URLSearchParams</code><span><a class="mark" href="#globals_urlsearchparams" id="globals_urlsearchparams">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>

<p>The WHATWG <code>URLSearchParams</code> class. See the <a href="#url_class_urlsearchparams"><code>URLSearchParams</code></a> section.</p>
<h2><code>WebAssembly</code><span><a class="mark" href="#globals_webassembly" id="globals_webassembly">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>

<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>The object that acts as the namespace for all W3C
<a href="https://webassembly.org">WebAssembly</a> related functionality. See the
<a href="https://developer.mozilla.org/en-US/docs/WebAssembly">Mozilla Developer Network</a> for usage and compatibility.</p>
<h1>HTTP<span><a class="mark" href="#http_http" id="http_http">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>To use the HTTP server and client one must <code>require('http')</code>.</p>
<p>The HTTP interfaces in Node.js are designed to support many features
of the protocol which have been traditionally difficult to use.
In particular, large, possibly chunk-encoded, messages. The interface is
careful to never buffer entire requests or responses, so the
user is able to stream data.</p>
<p>HTTP message headers are represented by an object like this:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{ 'content-length': '123',
  'content-type': 'text/plain',
  'connection': 'keep-alive',
  'host': 'mysite.com',
  'accept': '*/*' }
</code></pre>
<p>Keys are lowercased. Values are not modified.</p>
<p>In order to support the full spectrum of possible HTTP applications, the Node.js
HTTP API is very low-level. It deals with stream handling and message
parsing only. It parses a message into headers and body but it does not
parse the actual headers or the body.</p>
<p>See <a href="#http_message_headers"><code>message.headers</code></a> for details on how duplicate headers are handled.</p>
<p>The raw headers as they were received are retained in the <code>rawHeaders</code>
property, which is an array of <code>[key, value, key2, value2, ...]</code>. For
example, the previous message header object might have a <code>rawHeaders</code>
list like the following:</p>
<!-- eslint-disable semi -->
<pre><code class="language-js">[ 'ConTent-Length', '123456',
  'content-LENGTH', '123',
  'content-type', 'text/plain',
  'CONNECTION', 'keep-alive',
  'Host', 'mysite.com',
  'accepT', '*/*' ]
</code></pre>
<h2>Class: <code>http.Agent</code><span><a class="mark" href="#http_class_http_agent" id="http_class_http_agent">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<p>An <code>Agent</code> is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the
<code>keepAlive</code> <a href="#http_new_agent_options">option</a>.</p>
<p>Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The <code>Agent</code> will still make
the requests to that server, but each one will occur over a new connection.</p>
<p>When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the Node.js process running when there are no outstanding requests.
(see <a href="#net_socket_unref"><code>socket.unref()</code></a>).</p>
<p>It is good practice, to <a href="#http_agent_destroy"><code>destroy()</code></a> an <code>Agent</code> instance when it is no
longer in use, because unused sockets consume OS resources.</p>
<p>Sockets are removed from an agent when the socket emits either
a <code>'close'</code> event or an <code>'agentRemove'</code> event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:</p>
<pre><code class="language-js">http.get(options, (res) => {
  // Do stuff
}).on('socket', (socket) => {
  socket.emit('agentRemove');
});
</code></pre>
<p>An agent may also be used for an individual request. By providing
<code>{agent: false}</code> as an option to the <code>http.get()</code> or <code>http.request()</code>
functions, a one-time use <code>Agent</code> with default options will be used
for the client connection.</p>
<p><code>agent:false</code>:</p>
<pre><code class="language-js">http.get({
  hostname: 'localhost',
  port: 80,
  path: '/',
  agent: false  // Create a new agent just for this one request
}, (res) => {
  // Do stuff with response
});
</code></pre>
<h3><code>new Agent([options])</code><span><a class="mark" href="#http_new_agent_options" id="http_new_agent_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Set of configurable options to set on the agent.
Can have the following fields:</p>
<ul>
<li><code>keepAlive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Keep sockets around even when there are no
outstanding requests, so they can be used for future requests without
having to reestablish a TCP connection. Not to be confused with the
<code>keep-alive</code> value of the <code>Connection</code> header. The <code>Connection: keep-alive</code>
header is always sent when using an agent except when the <code>Connection</code>
header is explicitly specified or when the <code>keepAlive</code> and <code>maxSockets</code>
options are respectively set to <code>false</code> and <code>Infinity</code>, in which case
<code>Connection: close</code> will be used. <strong>Default:</strong> <code>false</code>.</li>
<li><code>keepAliveMsecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> When using the <code>keepAlive</code> option, specifies
the <a href="#net_socket_setkeepalive_enable_initialdelay">initial delay</a>
for TCP Keep-Alive packets. Ignored when the
<code>keepAlive</code> option is <code>false</code> or <code>undefined</code>. <strong>Default:</strong> <code>1000</code>.</li>
<li><code>maxSockets</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Maximum number of sockets to allow per
host. Each request will use a new socket until the maximum is reached.
<strong>Default:</strong> <code>Infinity</code>.</li>
<li><code>maxFreeSockets</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Maximum number of sockets to leave open
in a free state. Only relevant if <code>keepAlive</code> is set to <code>true</code>.
<strong>Default:</strong> <code>256</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Socket timeout in milliseconds.
This will set the timeout when the socket is created.</li>
</ul>
</li>
</ul>
<p><code>options</code> in <a href="#net_socket_connect_options_connectlistener"><code>socket.connect()</code></a> are also supported.</p>
<p>The default <a href="#http_http_globalagent"><code>http.globalAgent</code></a> that is used by <a href="#http_http_request_options_callback"><code>http.request()</code></a> has all
of these values set to their respective defaults.</p>
<p>To configure any of them, a custom <a href="#http_class_http_agent"><code>http.Agent</code></a> instance must be created.</p>
<pre><code class="language-js">const http = require('http');
const keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback);
</code></pre>
<h3><code>agent.createConnection(options[, callback])</code><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">&#x3C;Object></a> Options containing connection details. Check
<a href="#net_net_createconnection_options_connectlistener"><code>net.createConnection()</code></a> for the format of the options</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Callback function that receives the created socket</li>
<li>Returns: <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>Produces a socket/stream to be used for HTTP requests.</p>
<p>By default, this function is the same as <a href="#net_net_createconnection_options_connectlistener"><code>net.createConnection()</code></a>. However,
custom agents may override this method in case greater flexibility is desired.</p>
<p>A socket/stream can be supplied in one of two ways: by returning the
socket/stream from this function, or by passing the socket/stream to <code>callback</code>.</p>
<p>This method is guaranteed to return an instance of the <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>.</p>
<p><code>callback</code> has a signature of <code>(err, stream)</code>.</p>
<h3><code>agent.keepSocketAlive(socket)</code><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="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>Called when <code>socket</code> is detached from a request and could be persisted by the
<code>Agent</code>. Default behavior is to:</p>
<pre><code class="language-js">socket.setKeepAlive(true, this.keepAliveMsecs);
socket.unref();
return true;
</code></pre>
<p>This method can be overridden by a particular <code>Agent</code> subclass. If this
method returns a falsy value, the socket will be destroyed instead of persisting
it for use with the next request.</p>
<p>The <code>socket</code> argument can be an instance of <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>, a subclass of
<a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>.</p>
<h3><code>agent.reuseSocket(socket, request)</code><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="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
<li><code>request</code> <a href="#http_class_http_clientrequest" class="type">&#x3C;http.ClientRequest></a></li>
</ul>
<p>Called when <code>socket</code> is attached to <code>request</code> after being persisted because of
the keep-alive options. Default behavior is to:</p>
<pre><code class="language-js">socket.ref();
</code></pre>
<p>This method can be overridden by a particular <code>Agent</code> subclass.</p>
<p>The <code>socket</code> argument can be an instance of <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>, a subclass of
<a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>.</p>
<h3><code>agent.destroy()</code><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><code>agent.freeSockets</code><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">&#x3C;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>
<p>Sockets in the <code>freeSockets</code> list will be automatically destroyed and
removed from the array on <code>'timeout'</code>.</p>
<h3><code>agent.getName(options)</code><span><a class="mark" href="#http_agent_getname_options" id="http_agent_getname_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> A set of options providing information for name generation</p>
<ul>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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><code>agent.maxFreeSockets</code><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">&#x3C;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><code>agent.maxSockets</code><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">&#x3C;number></a></li>
</ul>
<p>By default set to <code>Infinity</code>. Determines how many concurrent sockets the agent
can have open per origin. Origin is the returned value of <a href="#http_agent_getname_options"><code>agent.getName()</code></a>.</p>
<h3><code>agent.requests</code><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">&#x3C;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><code>agent.sockets</code><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">&#x3C;Object></a></li>
</ul>
<p>An object which contains arrays of sockets currently in use by the
agent. Do not modify.</p>
<h2>Class: <code>http.ClientRequest</code><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>
<ul>
<li>Extends: <a href="#stream_stream" class="type">&#x3C;Stream></a></li>
</ul>
<p>This object is created internally and returned from <a href="#http_http_request_options_callback"><code>http.request()</code></a>. It
represents an <em>in-progress</em> request whose header has already been queued. The
header is still mutable using the <a href="#http_request_setheader_name_value"><code>setHeader(name, value)</code></a>,
<a href="#http_request_getheader_name"><code>getHeader(name)</code></a>, <a href="#http_request_removeheader_name"><code>removeHeader(name)</code></a> API. The actual header will
be sent along with the first data chunk or when calling <a href="#http_request_end_data_encoding_callback"><code>request.end()</code></a>.</p>
<p>To get the response, add a listener for <a href="#http_event_response"><code>'response'</code></a> to the request object.
<a href="#http_event_response"><code>'response'</code></a> will be emitted from the request object when the response
headers have been received. The <a href="#http_event_response"><code>'response'</code></a> event is executed with one
argument which is an instance of <a href="#http_class_http_incomingmessage"><code>http.IncomingMessage</code></a>.</p>
<p>During the <a href="#http_event_response"><code>'response'</code></a> event, one can add listeners to the
response object; particularly to listen for the <code>'data'</code> event.</p>
<p>If no <a href="#http_event_response"><code>'response'</code></a> handler is added, then the response will be
entirely discarded. However, if a <a href="#http_event_response"><code>'response'</code></a> event handler is added,
then the data from the response object <strong>must</strong> be consumed, either by
calling <code>response.read()</code> whenever there is a <code>'readable'</code> event, or
by adding a <code>'data'</code> handler, or by calling the <code>.resume()</code> method.
Until the data is consumed, the <code>'end'</code> event will not fire. Also, until
the data is read it will consume memory that can eventually lead to a
'process out of memory' error.</p>
<p>Unlike the <code>request</code> object, if the response closes prematurely, the
<code>response</code> object does not emit an <code>'error'</code> event but instead emits the
<code>'aborted'</code> event.</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>
<h3>Event: <code>'abort'</code><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: <code>'connect'</code><span><a class="mark" href="#http_event_connect" id="http_event_connect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>response</code> <a href="#http_class_http_incomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>socket</code> <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
<li><code>head</code> <a href="#buffer_class_buffer" class="type">&#x3C;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>This event is guaranteed to be passed an instance of the <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>.</p>
<p>A client and server pair demonstrating how to listen for the <code>'connect'</code> event:</p>
<pre><code class="language-js">const http = require('http');
const net = require('net');
const { URL } = require('url');

// Create an HTTP tunneling proxy
const proxy = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('okay');
});
proxy.on('connect', (req, clientSocket, head) => {
  // Connect to an origin server
  const { port, hostname } = new URL(`http://${req.url}`);
  const serverSocket = net.connect(port || 80, hostname, () => {
    clientSocket.write('HTTP/1.1 200 Connection Established\r\n' +
                    'Proxy-agent: Node.js-Proxy\r\n' +
                    '\r\n');
    serverSocket.write(head);
    serverSocket.pipe(clientSocket);
    clientSocket.pipe(serverSocket);
  });
});

// Now that proxy is running
proxy.listen(1337, '127.0.0.1', () => {

  // Make a request to a tunneling proxy
  const options = {
    port: 1337,
    host: '127.0.0.1',
    method: 'CONNECT',
    path: 'www.google.com:80'
  };

  const req = http.request(options);
  req.end();

  req.on('connect', (res, socket, head) => {
    console.log('got connected!');

    // Make a request over an HTTP tunnel
    socket.write('GET / HTTP/1.1\r\n' +
                 'Host: www.google.com:80\r\n' +
                 'Connection: close\r\n' +
                 '\r\n');
    socket.on('data', (chunk) => {
      console.log(chunk.toString());
    });
    socket.on('end', () => {
      proxy.close();
    });
  });
});
</code></pre>
<h3>Event: <code>'continue'</code><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: <code>'information'</code><span><a class="mark" href="#http_event_information" id="http_event_information">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>
<p><code>info</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>httpVersion</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>httpVersionMajor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>httpVersionMinor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>statusMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>rawHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
</li>
</ul>
<p>Emitted when the server sends a 1xx intermediate response (excluding 101
Upgrade). The listeners of this event will receive an object containing the
HTTP version, status code, status message, key-value headers object,
and array with the raw header names followed by their respective values.</p>
<pre><code class="language-js">const http = require('http');

const options = {
  host: '127.0.0.1',
  port: 8080,
  path: '/length_request'
};

// Make a request
const req = http.request(options);
req.end();

req.on('information', (info) => {
  console.log(`Got information prior to main response: ${info.statusCode}`);
});
</code></pre>
<p>101 Upgrade statuses do not fire this event due to their break from the
traditional HTTP request/response chain, such as web sockets, in-place TLS
upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the
<a href="#http_event_upgrade"><code>'upgrade'</code></a> event instead.</p>
<h3>Event: <code>'response'</code><span><a class="mark" href="#http_event_response" id="http_event_response">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.0</span>
</div>
<ul>
<li><code>response</code> <a href="#http_class_http_incomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
</ul>
<p>Emitted when a response is received to this request. This event is emitted only
once.</p>
<h3>Event: <code>'socket'</code><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="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>This event is guaranteed to be passed an instance of the <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>.</p>
<h3>Event: <code>'timeout'</code><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: <code>'upgrade'</code><span><a class="mark" href="#http_event_upgrade" id="http_event_upgrade">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div>
<ul>
<li><code>response</code> <a href="#http_class_http_incomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>socket</code> <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
<li><code>head</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Emitted each time a server responds to a request with an upgrade. If this
event is not being listened for and the response status code is 101 Switching
Protocols, clients receiving an upgrade header will have their connections
closed.</p>
<p>This event is guaranteed to be passed an instance of the <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>.</p>
<p>A client server pair demonstrating how to listen for the <code>'upgrade'</code> event.</p>
<pre><code class="language-js">const http = require('http');

// Create an HTTP server
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('okay');
});
server.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
server.listen(1337, '127.0.0.1', () => {

  // make a request
  const options = {
    port: 1337,
    host: '127.0.0.1',
    headers: {
      'Connection': 'Upgrade',
      'Upgrade': 'websocket'
    }
  };

  const req = http.request(options);
  req.end();

  req.on('upgrade', (res, socket, upgradeHead) => {
    console.log('got upgraded!');
    socket.end();
    process.exit(0);
  });
});
</code></pre>
<h3><code>request.abort()</code><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><code>request.aborted</code><span><a class="mark" href="#http_request_aborted" id="http_request_aborted">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>The <code>aborted</code> property is no longer a timestamp number.</p></td></tr>
<tr><td>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <code>request.aborted</code> property will be <code>true</code> if the request has
been aborted.</p>
<h3><code>request.connection</code><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="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>See <a href="#http_request_socket"><code>request.socket</code></a>.</p>
<h3><code>request.end([data[, encoding]][, callback])</code><span><a class="mark" href="#http_request_end_data_encoding_callback" id="http_request_end_data_encoding_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>This method now returns a reference to <code>ClientRequest</code>.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type">&#x3C;this></a></li>
</ul>
<p>Finishes sending the request. If any parts of the body are
unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating <code>'0\r\n\r\n'</code>.</p>
<p>If <code>data</code> is specified, it is equivalent to calling
<a href="#http_request_write_chunk_encoding_callback"><code>request.write(data, encoding)</code></a> followed by <code>request.end(callback)</code>.</p>
<p>If <code>callback</code> is specified, it will be called when the request stream
is finished.</p>
<h3><code>request.finished</code><span><a class="mark" href="#http_request_finished" id="http_request_finished">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span><span>Deprecated since: v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated. Use <a href="#http_request_writableended"><code>request.writableEnded</code></a>.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <code>request.finished</code> property will be <code>true</code> if <a href="#http_request_end_data_encoding_callback"><code>request.end()</code></a>
has been called. <code>request.end()</code> will automatically be called if the
request was initiated via <a href="#http_http_get_options_callback"><code>http.get()</code></a>.</p>
<h3><code>request.flushHeaders()</code><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>Flushes 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><code>request.getHeader(name)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Reads out a header on the request. The name is case-insensitive.
The type of the return value depends on the arguments provided to
<a href="#http_request_setheader_name_value"><code>request.setHeader()</code></a>.</p>
<pre><code class="language-js">request.setHeader('content-type', 'text/html');
request.setHeader('Content-Length', Buffer.byteLength(body));
request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
const contentType = request.getHeader('Content-Type');
// 'contentType' is 'text/html'
const contentLength = request.getHeader('Content-Length');
// 'contentLength' is of type number
const cookie = request.getHeader('Cookie');
// 'cookie' is of type string[]
</code></pre>
<h3><code>request.maxHeadersCount</code><span><a class="mark" href="#http_request_maxheaderscount" id="http_request_maxheaderscount">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <strong>Default:</strong> <code>2000</code></li>
</ul>
<p>Limits maximum response headers count. If set to 0, no limit will be applied.</p>
<h3><code>request.path</code><span><a class="mark" href="#http_request_path" id="http_request_path">#</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">&#x3C;string></a> The request path.</li>
</ul>
<h3><code>request.removeHeader(name)</code><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">&#x3C;string></a></li>
</ul>
<p>Removes a header that's already defined into headers object.</p>
<pre><code class="language-js">request.removeHeader('Content-Type');
</code></pre>
<h3><code>request.reusedSocket</code><span><a class="mark" href="#http_request_reusedsocket" id="http_request_reusedsocket">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether the request is send through a reused socket.</li>
</ul>
<p>When sending request through a keep-alive enabled agent, the underlying socket
might be reused. But if server closes connection at unfortunate time, client
may run into a 'ECONNRESET' error.</p>
<pre><code class="language-js">const http = require('http');

// Server has a 5 seconds keep-alive timeout by default
http
  .createServer((req, res) => {
    res.write('hello\n');
    res.end();
  })
  .listen(3000);

setInterval(() => {
  // Adapting a keep-alive agent
  http.get('http://localhost:3000', { agent }, (res) => {
    res.on('data', (data) => {
      // Do nothing
    });
  });
}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
</code></pre>
<p>By marking a request whether it reused socket or not, we can do
automatic error retry base on it.</p>
<pre><code class="language-js">const http = require('http');
const agent = new http.Agent({ keepAlive: true });

function retriableRequest() {
  const req = http
    .get('http://localhost:3000', { agent }, (res) => {
      // ...
    })
    .on('error', (err) => {
      // Check if retry is needed
      if (req.reusedSocket &#x26;&#x26; err.code === 'ECONNRESET') {
        retriableRequest();
      }
    });
}

retriableRequest();
</code></pre>
<h3><code>request.setHeader(name, value)</code><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">&#x3C;string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Sets a single header value for headers object. If this header already exists in
the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, <a href="#http_request_getheader_name"><code>request.getHeader()</code></a> may return
non-string values. However, the non-string values will be converted to strings
for network transmission.</p>
<pre><code class="language-js">request.setHeader('Content-Type', 'application/json');
</code></pre>
<p>or</p>
<pre><code class="language-js">request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
</code></pre>
<h3><code>request.setNoDelay([noDelay])</code><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">&#x3C;boolean></a></li>
</ul>
<p>Once a socket is assigned to this request and is connected
<a href="#net_socket_setnodelay_nodelay"><code>socket.setNoDelay()</code></a> will be called.</p>
<h3><code>request.setSocketKeepAlive([enable][, initialDelay])</code><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">&#x3C;boolean></a></li>
<li><code>initialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Once a socket is assigned to this request and is connected
<a href="#net_socket_setkeepalive_enable_initialdelay"><code>socket.setKeepAlive()</code></a> will be called.</p>
<h3><code>request.setTimeout(timeout[, callback])</code><span><a class="mark" href="#http_request_settimeout_timeout_callback" id="http_request_settimeout_timeout_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Consistently set socket timeout only when the socket connects.</p></td></tr>
<tr><td>v0.5.9</td>
<td><p><span>Added in: v0.5.9</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;Function></a> Optional function to be called when a timeout occurs.
Same as binding to the <code>'timeout'</code> event.</li>
<li>Returns: <a href="#http_class_http_clientrequest" class="type">&#x3C;http.ClientRequest></a></li>
</ul>
<p>Once a socket is assigned to this request and is connected
<a href="#net_socket_settimeout_timeout_callback"><code>socket.setTimeout()</code></a> will be called.</p>
<h3><code>request.socket</code><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="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit <code>'readable'</code> events
because of how the protocol parser attaches to the socket. The <code>socket</code>
may also be accessed via <code>request.connection</code>.</p>
<pre><code class="language-js">const http = require('http');
const options = {
  host: 'www.google.com',
};
const req = http.get(options);
req.end();
req.once('response', (res) => {
  const ip = req.socket.localAddress;
  const port = req.socket.localPort;
  console.log(`Your IP address is ${ip} and your source port is ${port}.`);
  // Consume response object
});
</code></pre>
<p>This property is guaranteed to be an instance of the <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>, unless the user specified a socket
type other than <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>.</p>
<h3><code>request.writableEnded</code><span><a class="mark" href="#http_request_writableended" id="http_request_writableended">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> after <a href="#http_request_end_data_encoding_callback"><code>request.end()</code></a> has been called. This property
does not indicate whether the data has been flushed, for this use
<a href="#http_request_writablefinished"><code>request.writableFinished</code></a> instead.</p>
<h3><code>request.writableFinished</code><span><a class="mark" href="#http_request_writablefinished" id="http_request_writablefinished">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.7.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> if all data has been flushed to the underlying system, immediately
before the <a href="#http_event_finish"><code>'finish'</code></a> event is emitted.</p>
<h3><code>request.write(chunk[, encoding][, callback])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Sends a chunk of the body. By calling this method
many times, a request body can be sent to a
server. In that case, it is suggested to use the
<code>['Transfer-Encoding', 'chunked']</code> header line when
creating the request.</p>
<p>The <code>encoding</code> argument is optional and only applies when <code>chunk</code> is a string.
Defaults to <code>'utf8'</code>.</p>
<p>The <code>callback</code> argument is optional and will be called when this chunk of data
is flushed, but only if the chunk is non-empty.</p>
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
buffer. Returns <code>false</code> if all or part of the data was queued in user memory.
<code>'drain'</code> will be emitted when the buffer is free again.</p>
<p>When <code>write</code> function is called with empty string or buffer, it does
nothing and waits for more input.</p>
<h2>Class: <code>http.Server</code><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>
<ul>
<li>Extends: <a href="#net_class_net_server" class="type">&#x3C;net.Server></a></li>
</ul>
<h3>Event: <code>'checkContinue'</code><span><a class="mark" href="#http_event_checkcontinue" id="http_event_checkcontinue">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>request</code> <a href="#http_class_http_incomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>response</code> <a href="#http_class_http_serverresponse" class="type">&#x3C;http.ServerResponse></a></li>
</ul>
<p>Emitted each time a request with an HTTP <code>Expect: 100-continue</code> is received.
If this event is not listened for, the server will automatically respond
with a <code>100 Continue</code> as appropriate.</p>
<p>Handling this event involves calling <a href="#http_response_writecontinue"><code>response.writeContinue()</code></a> if the
client should continue to send the request body, or generating an appropriate
HTTP response (e.g. 400 Bad Request) if the client should not continue to send
the request body.</p>
<p>When this event is emitted and handled, the <a href="#http_event_request"><code>'request'</code></a> event will
not be emitted.</p>
<h3>Event: <code>'checkExpectation'</code><span><a class="mark" href="#http_event_checkexpectation" id="http_event_checkexpectation">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v5.5.0</span>
</div>
<ul>
<li><code>request</code> <a href="#http_class_http_incomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>response</code> <a href="#http_class_http_serverresponse" class="type">&#x3C;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>When this event is emitted and handled, the <a href="#http_event_request"><code>'request'</code></a> event will
not be emitted.</p>
<h3>Event: <code>'clientError'</code><span><a class="mark" href="#http_event_clienterror" id="http_event_clienterror">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>The default behavior will return a 431 Request Header Fields Too Large if a HPE_HEADER_OVERFLOW error occurs.</p></td></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>rawPacket</code> is the current buffer that just parsed. Adding this buffer to the error object of <code>'clientError'</code> event is to make it possible that developers can log the broken packet.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The default action of calling <code>.destroy()</code> on the <code>socket</code> will no longer take place if there are listeners attached for <code>'clientError'</code>.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>exception</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>socket</code> <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></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>This event is guaranteed to be passed an instance of the <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>.</p>
<p>Default behavior is to try close the socket with a HTTP '400 Bad Request',
or a HTTP '431 Request Header Fields Too Large' in the case of a
<a href="#errors_hpe_header_overflow"><code>HPE_HEADER_OVERFLOW</code></a> error. If the socket is not writable it is
immediately destroyed.</p>
<p><code>socket</code> is the <a href="#net_class_net_socket"><code>net.Socket</code></a> object that the error originated from.</p>
<pre><code class="language-js">const http = require('http');

const server = http.createServer((req, res) => {
  res.end();
});
server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);
</code></pre>
<p>When the <code>'clientError'</code> event occurs, there is no <code>request</code> or <code>response</code>
object, so any HTTP response sent, including response headers and payload,
<em>must</em> be written directly to the <code>socket</code> object. Care must be taken to
ensure the response is a properly formatted HTTP response message.</p>
<p><code>err</code> is an instance of <code>Error</code> with two extra columns:</p>
<ul>
<li><code>bytesParsed</code>: the bytes count of request packet that Node.js may have parsed
correctly;</li>
<li><code>rawPacket</code>: the raw packet of current request.</li>
</ul>
<p>In some cases, the client has already received the response and/or the socket
has already been destroyed, like in case of <code>ECONNRESET</code> errors. Before
trying to send data to the socket, it is better to check that it is still
writable.</p>
<pre><code class="language-js">server.on('clientError', (err, socket) => {
  if (err.code === 'ECONNRESET' || !socket.writable) {
    return;
  }

  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
</code></pre>
<h3>Event: <code>'close'</code><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: <code>'connect'</code><span><a class="mark" href="#http_event_connect_1" id="http_event_connect_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>request</code> <a href="#http_class_http_incomingmessage" class="type">&#x3C;http.IncomingMessage></a> Arguments for the HTTP request, as it is in
the <a href="#http_event_request"><code>'request'</code></a> event</li>
<li><code>socket</code> <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a> Network socket between the server and client</li>
<li><code>head</code> <a href="#buffer_class_buffer" class="type">&#x3C;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>This event is guaranteed to be passed an instance of the <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>.</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: <code>'connection'</code><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="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>This event is emitted when a new TCP stream is established. <code>socket</code> is
typically an object of type <a href="#net_class_net_socket"><code>net.Socket</code></a>. Usually users will not want to
access this event. In particular, the socket will not emit <code>'readable'</code> events
because of how the protocol parser attaches to the socket. The <code>socket</code> can
also be accessed at <code>request.connection</code>.</p>
<p>This event can also be explicitly emitted by users to inject connections
into the HTTP server. In that case, any <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream can be passed.</p>
<p>If <code>socket.setTimeout()</code> is called here, the timeout will be replaced with
<code>server.keepAliveTimeout</code> when the socket has served a request (if
<code>server.keepAliveTimeout</code> is non-zero).</p>
<p>This event is guaranteed to be passed an instance of the <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>.</p>
<h3>Event: <code>'request'</code><span><a class="mark" href="#http_event_request" id="http_event_request">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.0</span>
</div>
<ul>
<li><code>request</code> <a href="#http_class_http_incomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>response</code> <a href="#http_class_http_serverresponse" class="type">&#x3C;http.ServerResponse></a></li>
</ul>
<p>Emitted each time there is a request. There may be multiple requests
per connection (in the case of HTTP Keep-Alive connections).</p>
<h3>Event: <code>'upgrade'</code><span><a class="mark" href="#http_event_upgrade_1" id="http_event_upgrade_1">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Not listening to this event no longer causes the socket to be destroyed if a client sends an Upgrade header.</p></td></tr>
<tr><td>v0.1.94</td>
<td><p><span>Added in: v0.1.94</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>request</code> <a href="#http_class_http_incomingmessage" class="type">&#x3C;http.IncomingMessage></a> Arguments for the HTTP request, as it is in
the <a href="#http_event_request"><code>'request'</code></a> event</li>
<li><code>socket</code> <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a> Network socket between the server and client</li>
<li><code>head</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The first packet of the upgraded stream (may be empty)</li>
</ul>
<p>Emitted each time a client requests an HTTP upgrade. Listening to this event
is optional and clients cannot insist on a protocol change.</p>
<p>After this event is emitted, the request's socket will not have a <code>'data'</code>
event listener, meaning it will need to be bound in order to handle data
sent to the server on that socket.</p>
<p>This event is guaranteed to be passed an instance of the <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>.</p>
<h3><code>server.close([callback])</code><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">&#x3C;Function></a></li>
</ul>
<p>Stops the server from accepting new connections. See <a href="#net_server_close_callback"><code>net.Server.close()</code></a>.</p>
<h3><code>server.headersTimeout</code><span><a class="mark" href="#http_server_headerstimeout" id="http_server_headerstimeout">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <strong>Default:</strong> <code>60000</code></li>
</ul>
<p>Limit the amount of time the parser will wait to receive the complete HTTP
headers.</p>
<p>In case of inactivity, the rules defined in <a href="#http_server_timeout"><code>server.timeout</code></a> apply. However,
that inactivity based timeout would still allow the connection to be kept open
if the headers are being sent very slowly (by default, up to a byte per 2
minutes). In order to prevent this, whenever header data arrives an additional
check is made that more than <code>server.headersTimeout</code> milliseconds has not
passed since the connection was established. If the check fails, a <code>'timeout'</code>
event is emitted on the server object, and (by default) the socket is destroyed.
See <a href="#http_server_timeout"><code>server.timeout</code></a> for more information on how timeout behavior can be
customized.</p>
<p>A value of <code>0</code> will disable the HTTP headers timeout check.</p>
<h3><code>server.listen()</code><span><a class="mark" href="#http_server_listen" id="http_server_listen">#</a></span></h3>
<p>Starts the HTTP server listening for connections.
This method is identical to <a href="#net_server_listen"><code>server.listen()</code></a> from <a href="#net_class_net_server"><code>net.Server</code></a>.</p>
<h3><code>server.listening</code><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">&#x3C;boolean></a> Indicates whether or not the server is listening for connections.</li>
</ul>
<h3><code>server.maxHeadersCount</code><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">&#x3C;number></a> <strong>Default:</strong> <code>2000</code></li>
</ul>
<p>Limits maximum incoming headers count. If set to 0, no limit will be applied.</p>
<h3><code>server.setTimeout([msecs][, callback])</code><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">&#x3C;number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#http_class_http_server" class="type">&#x3C;http.Server></a></li>
</ul>
<p>Sets the timeout value for sockets, and emits a <code>'timeout'</code> event on
the Server object, passing the socket as an argument, if a timeout
occurs.</p>
<p>If there is a <code>'timeout'</code> event listener on the Server object, then it
will be called with the timed-out socket as an argument.</p>
<p>By default, the Server's timeout value is 2 minutes, and sockets are
destroyed automatically if they time out. However, if a callback is assigned
to the Server's <code>'timeout'</code> event, timeouts must be handled explicitly.</p>
<p>To change the default timeout use the <a href="#cli_http_server_default_timeout_milliseconds"><code>--http-server-default-timeout</code></a>
flag.</p>
<h3><code>server.timeout</code><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">&#x3C;number></a> Timeout in milliseconds. <strong>Default:</strong> <code>120000</code> (2 minutes).</li>
</ul>
<p>The number of milliseconds of inactivity before a socket is presumed
to have timed out.</p>
<p>A value of <code>0</code> will disable the timeout behavior on incoming connections.</p>
<p>The socket timeout logic is set up on connection, so changing this
value only affects new connections to the server, not any existing connections.</p>
<p>To change the default timeout use the <a href="#cli_http_server_default_timeout_milliseconds"><code>--http-server-default-timeout</code></a>
flag.</p>
<h3><code>server.keepAliveTimeout</code><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">&#x3C;number></a> Timeout in milliseconds. <strong>Default:</strong> <code>5000</code> (5 seconds).</li>
</ul>
<p>The number of milliseconds of inactivity a server needs to wait for additional
incoming data, after it has finished writing the last response, before a socket
will be destroyed. If the server receives new data before the keep-alive
timeout has fired, it will reset the regular inactivity timeout, i.e.,
<a href="#http_server_timeout"><code>server.timeout</code></a>.</p>
<p>A value of <code>0</code> will disable the keep-alive timeout behavior on incoming
connections.
A value of <code>0</code> makes the http server behave similarly to Node.js versions prior
to 8.0.0, which did not have a keep-alive timeout.</p>
<p>The socket timeout logic is set up on connection, so changing this value only
affects new connections to the server, not any existing connections.</p>
<h2>Class: <code>http.ServerResponse</code><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>
<ul>
<li>Extends: <a href="#stream_stream" class="type">&#x3C;Stream></a></li>
</ul>
<p>This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the <a href="#http_event_request"><code>'request'</code></a> event.</p>
<h3>Event: <code>'close'</code><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.</p>
<h3>Event: <code>'finish'</code><span><a class="mark" href="#http_event_finish" id="http_event_finish">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div>
<p>Emitted when the response has been sent. More specifically, this event is
emitted when the last segment of the response headers and body have been
handed off to the operating system for transmission over the network. It
does not imply that the client has received anything yet.</p>
<h3><code>response.addTrailers(headers)</code><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">&#x3C;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>HTTP requires the <code>Trailer</code> header to be sent in order to
emit trailers, with a list of the header fields in its value. E.g.,</p>
<pre><code class="language-js">response.writeHead(200, { 'Content-Type': 'text/plain',
                          'Trailer': 'Content-MD5' });
response.write(fileData);
response.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
response.end();
</code></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p>
<h3><code>response.connection</code><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="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>See <a href="#http_response_socket"><code>response.socket</code></a>.</p>
<h3><code>response.cork()</code><span><a class="mark" href="#http_response_cork" id="http_response_cork">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p>See <a href="#stream_writable_cork"><code>writable.cork()</code></a>.</p>
<h3><code>response.end([data[, encoding]][, callback])</code><span><a class="mark" href="#http_response_end_data_encoding_callback" id="http_response_end_data_encoding_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>This method now returns a reference to <code>ServerResponse</code>.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type">&#x3C;this></a></li>
</ul>
<p>This method signals to the server that all of the response headers and body
have been sent; that server should consider this message complete.
The method, <code>response.end()</code>, MUST be called on each response.</p>
<p>If <code>data</code> is specified, it is similar in effect to calling
<a href="#http_response_write_chunk_encoding_callback"><code>response.write(data, encoding)</code></a> followed by <code>response.end(callback)</code>.</p>
<p>If <code>callback</code> is specified, it will be called when the response stream
is finished.</p>
<h3><code>response.finished</code><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><span>Deprecated since: v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated. Use <a href="#http_response_writableended"><code>response.writableEnded</code></a>.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <code>response.finished</code> property will be <code>true</code> if <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a>
has been called.</p>
<h3><code>response.flushHeaders()</code><span><a class="mark" href="#http_response_flushheaders" id="http_response_flushheaders">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div>
<p>Flushes the response headers. See also: <a href="#http_request_flushheaders"><code>request.flushHeaders()</code></a>.</p>
<h3><code>response.getHeader(name)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Reads out a header that's already been queued but not sent to the client.
The name is case-insensitive. The type of the return value depends
on the arguments provided to <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a>.</p>
<pre><code class="language-js">response.setHeader('Content-Type', 'text/html');
response.setHeader('Content-Length', Buffer.byteLength(body));
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
const contentType = response.getHeader('content-type');
// contentType is 'text/html'
const contentLength = response.getHeader('Content-Length');
// contentLength is of type number
const setCookie = response.getHeader('set-cookie');
// setCookie is of type string[]
</code></pre>
<h3><code>response.getHeaderNames()</code><span><a class="mark" href="#http_response_getheadernames" id="http_response_getheadernames">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>Returns an array containing the unique names of the current outgoing headers.
All header names are lowercase.</p>
<pre><code class="language-js">response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

const headerNames = response.getHeaderNames();
// headerNames === ['foo', 'set-cookie']
</code></pre>
<h3><code>response.getHeaders()</code><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">&#x3C;Object></a></li>
</ul>
<p>Returns a shallow copy of the current outgoing headers. Since a shallow copy
is used, array values may be mutated without additional calls to various
header-related http module methods. The keys of the returned object are the
header names and the values are the respective header values. All header names
are lowercase.</p>
<p>The object returned by the <code>response.getHeaders()</code> method <em>does not</em>
prototypically inherit from the JavaScript <code>Object</code>. This means that typical
<code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others
are not defined and <em>will not work</em>.</p>
<pre><code class="language-js">response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

const headers = response.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
</code></pre>
<h3><code>response.hasHeader(name)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the header identified by <code>name</code> is currently set in the
outgoing headers. The header name matching is case-insensitive.</p>
<pre><code class="language-js">const hasContentType = response.hasHeader('content-type');
</code></pre>
<h3><code>response.headersSent</code><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">&#x3C;boolean></a></li>
</ul>
<p>Boolean (read-only). True if headers were sent, false otherwise.</p>
<h3><code>response.removeHeader(name)</code><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">&#x3C;string></a></li>
</ul>
<p>Removes a header that's queued for implicit sending.</p>
<pre><code class="language-js">response.removeHeader('Content-Encoding');
</code></pre>
<h3><code>response.sendDate</code><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">&#x3C;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><code>response.setHeader(name, value)</code><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">&#x3C;string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Sets a single header value for implicit headers. If this header already exists
in the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, <a href="#http_response_getheader_name"><code>response.getHeader()</code></a> may return
non-string values. However, the non-string values will be converted to strings
for network transmission.</p>
<pre><code class="language-js">response.setHeader('Content-Type', 'text/html');
</code></pre>
<p>or</p>
<pre><code class="language-js">response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
</code></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p>
<p>When headers have been set with <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="language-js">// Returns content-type = text/plain
const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ok');
});
</code></pre>
<p>If <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> method is called and this method has not been
called, it will directly write the supplied header values onto the network
channel without caching internally, and the <a href="#http_response_getheader_name"><code>response.getHeader()</code></a> on the
header will not yield the expected result. If progressive population of headers
is desired with potential future retrieval and modification, use
<a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a> instead of <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>.</p>
<h3><code>response.setTimeout(msecs[, callback])</code><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">&#x3C;number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#http_class_http_serverresponse" class="type">&#x3C;http.ServerResponse></a></li>
</ul>
<p>Sets the Socket's timeout value to <code>msecs</code>. If a callback is
provided, then it is added as a listener on the <code>'timeout'</code> event on
the response object.</p>
<p>If no <code>'timeout'</code> listener is added to the request, the response, or
the server, then sockets are destroyed when they time out. If a handler is
assigned to the request, the response, or the server's <code>'timeout'</code> events,
timed out sockets must be handled explicitly.</p>
<h3><code>response.socket</code><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="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>Reference to the underlying socket. Usually users will not want to access
this property. In particular, the socket will not emit <code>'readable'</code> events
because of how the protocol parser attaches to the socket. After
<code>response.end()</code>, the property is nulled. The <code>socket</code> may also be accessed
via <code>response.connection</code>.</p>
<pre><code class="language-js">const http = require('http');
const server = http.createServer((req, res) => {
  const ip = res.socket.remoteAddress;
  const port = res.socket.remotePort;
  res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);
</code></pre>
<p>This property is guaranteed to be an instance of the <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>, unless the user specified a socket
type other than <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>.</p>
<h3><code>response.statusCode</code><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">&#x3C;number></a> <strong>Default:</strong> <code>200</code></li>
</ul>
<p>When using implicit headers (not calling <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> explicitly),
this property controls the status code that will be sent to the client when
the headers get flushed.</p>
<pre><code class="language-js">response.statusCode = 404;
</code></pre>
<p>After response header was sent to the client, this property indicates the
status code which was sent out.</p>
<h3><code>response.statusMessage</code><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">&#x3C;string></a></li>
</ul>
<p>When using implicit headers (not calling <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> explicitly),
this property controls the status message that will be sent to the client when
the headers get flushed. If this is left as <code>undefined</code> then the standard
message for the status code will be used.</p>
<pre><code class="language-js">response.statusMessage = 'Not found';
</code></pre>
<p>After response header was sent to the client, this property indicates the
status message which was sent out.</p>
<h3><code>response.uncork()</code><span><a class="mark" href="#http_response_uncork" id="http_response_uncork">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p>See <a href="#stream_writable_uncork"><code>writable.uncork()</code></a>.</p>
<h3><code>response.writableEnded</code><span><a class="mark" href="#http_response_writableended" id="http_response_writableended">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> after <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> has been called. This property
does not indicate whether the data has been flushed, for this use
<a href="#http_response_writablefinished"><code>response.writableFinished</code></a> instead.</p>
<h3><code>response.writableFinished</code><span><a class="mark" href="#http_response_writablefinished" id="http_response_writablefinished">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.7.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> if all data has been flushed to the underlying system, immediately
before the <a href="#http_event_finish"><code>'finish'</code></a> event is emitted.</p>
<h3><code>response.write(chunk[, encoding][, callback])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>If this method is called and <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> has not been called,
it will switch to implicit header mode and flush the implicit headers.</p>
<p>This sends a chunk of the response body. This method may
be called multiple times to provide successive parts of the body.</p>
<p>In the <code>http</code> module, the response body is omitted when the
request is a HEAD request. Similarly, the <code>204</code> and <code>304</code> responses
<em>must not</em> include a message body.</p>
<p><code>chunk</code> can be a string or a buffer. If <code>chunk</code> is a string,
the second parameter specifies how to encode it into a byte stream.
<code>callback</code> will be called when this chunk of data is flushed.</p>
<p>This is the raw HTTP body and has nothing to do with higher-level multi-part
body encodings that may be used.</p>
<p>The first time <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, it will send the buffered
header information and the first chunk of the body to the client. The second
time <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, Node.js assumes data will be streamed,
and sends the new data separately. That is, the response is buffered up to the
first chunk of the body.</p>
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
buffer. Returns <code>false</code> if all or part of the data was queued in user memory.
<code>'drain'</code> will be emitted when the buffer is free again.</p>
<h3><code>response.writeContinue()</code><span><a class="mark" href="#http_response_writecontinue" id="http_response_writecontinue">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<p>Sends a HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the <a href="#http_event_checkcontinue"><code>'checkContinue'</code></a> event on
<code>Server</code>.</p>
<h3><code>response.writeHead(statusCode[, statusMessage][, headers])</code><span><a class="mark" href="#http_response_writehead_statuscode_statusmessage_headers" id="http_response_writehead_statuscode_statusmessage_headers">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.10.0</td>
<td><p>Return <code>this</code> from <code>writeHead()</code> to allow chaining with <code>end()</code>.</p></td></tr>
<tr><td>v5.11.0, v4.4.5</td>
<td><p>A <code>RangeError</code> is thrown if <code>statusCode</code> is not a number in the range <code>[100, 999]</code>.</p></td></tr>
<tr><td>v0.1.30</td>
<td><p><span>Added in: v0.1.30</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>statusMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li>Returns: <a href="#http_class_http_serverresponse" class="type">&#x3C;http.ServerResponse></a></li>
</ul>
<p>Sends a response header to the request. The status code is a 3-digit HTTP
status code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers.
Optionally one can give a human-readable <code>statusMessage</code> as the second
argument.</p>
<p>Returns a reference to the <code>ServerResponse</code>, so that calls can be chained.</p>
<pre><code class="language-js">const body = 'hello world';
response
  .writeHead(200, {
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'text/plain'
  })
  .end(body);
</code></pre>
<p>This method must only be called once on a message and it must
be called before <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> is called.</p>
<p>If <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> or <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> are called before calling
this, the implicit/mutable headers will be calculated and call this function.</p>
<p>When headers have been set with <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p>
<p>If this method is called and <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a> has not been called,
it will directly write the supplied header values onto the network channel
without caching internally, and the <a href="#http_response_getheader_name"><code>response.getHeader()</code></a> on the header
will not yield the expected result. If progressive population of headers is
desired with potential future retrieval and modification, use
<a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a> instead.</p>
<pre><code class="language-js">// Returns content-type = text/plain
const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ok');
});
</code></pre>
<p><code>Content-Length</code> is given in bytes, not characters. Use
<a href="#buffer_class_method_buffer_bytelength_string_encoding"><code>Buffer.byteLength()</code></a> to determine the length of the body in bytes. Node.js
does not check whether <code>Content-Length</code> and the length of the body which has
been transmitted are equal or not.</p>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p>
<h3><code>response.writeProcessing()</code><span><a class="mark" href="#http_response_writeprocessing" id="http_response_writeprocessing">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>Sends a HTTP/1.1 102 Processing message to the client, indicating that
the request body should be sent.</p>
<h2>Class: <code>http.IncomingMessage</code><span><a class="mark" href="#http_class_http_incomingmessage" id="http_class_http_incomingmessage">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>readableHighWaterMark</code> value mirrors that of the socket.</p></td></tr>
<tr><td>v0.1.17</td>
<td><p><span>Added in: v0.1.17</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Extends: <a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>An <code>IncomingMessage</code> object is created by <a href="#http_class_http_server"><code>http.Server</code></a> or
<a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> and passed as the first argument to the <a href="#http_event_request"><code>'request'</code></a>
and <a href="#http_event_response"><code>'response'</code></a> event respectively. It may be used to access response
status, headers and data.</p>
<h3>Event: <code>'aborted'</code><span><a class="mark" href="#http_event_aborted" id="http_event_aborted">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.8</span>
</div>
<p>Emitted when the request has been aborted.</p>
<h3>Event: <code>'close'</code><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.</p>
<h3><code>message.aborted</code><span><a class="mark" href="#http_message_aborted" id="http_message_aborted">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.1.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <code>message.aborted</code> property will be <code>true</code> if the request has
been aborted.</p>
<h3><code>message.complete</code><span><a class="mark" href="#http_message_complete" id="http_message_complete">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <code>message.complete</code> property will be <code>true</code> if a complete HTTP message has
been received and successfully parsed.</p>
<p>This property is particularly useful as a means of determining if a client or
server fully transmitted a message before a connection was terminated:</p>
<pre><code class="language-js">const req = http.request({
  host: '127.0.0.1',
  port: 8080,
  method: 'POST'
}, (res) => {
  res.resume();
  res.on('end', () => {
    if (!res.complete)
      console.error(
        'The connection was terminated while the message was still being sent');
  });
});
</code></pre>
<h3><code>message.destroy([error])</code><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">&#x3C;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 on the socket and <code>error</code> is passed
as an argument to any listeners on the event.</p>
<h3><code>message.headers</code><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">&#x3C;Object></a></li>
</ul>
<p>The request/response headers object.</p>
<p>Key-value pairs of header names and values. Header names are lower-cased.</p>
<pre><code class="language-js">// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
//   host: '127.0.0.1:8000',
//   accept: '*/*' }
console.log(request.headers);
</code></pre>
<p>Duplicates in raw headers are handled in the following ways, depending on the
header name:</p>
<ul>
<li>Duplicates of <code>age</code>, <code>authorization</code>, <code>content-length</code>, <code>content-type</code>,
<code>etag</code>, <code>expires</code>, <code>from</code>, <code>host</code>, <code>if-modified-since</code>, <code>if-unmodified-since</code>,
<code>last-modified</code>, <code>location</code>, <code>max-forwards</code>, <code>proxy-authorization</code>, <code>referer</code>,
<code>retry-after</code>, <code>server</code>, or <code>user-agent</code> are discarded.</li>
<li><code>set-cookie</code> is always an array. Duplicates are added to the array.</li>
<li>For duplicate <code>cookie</code> headers, the values are joined together with '; '.</li>
<li>For all other headers, the values are joined together with ', '.</li>
</ul>
<h3><code>message.httpVersion</code><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">&#x3C;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><code>message.method</code><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">&#x3C;string></a></li>
</ul>
<p><strong>Only valid for request obtained from <a href="#http_class_http_server"><code>http.Server</code></a>.</strong></p>
<p>The request method as a string. Read only. Examples: <code>'GET'</code>, <code>'DELETE'</code>.</p>
<h3><code>message.rawHeaders</code><span><a class="mark" href="#http_message_rawheaders" id="http_message_rawheaders">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.6</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>The raw request/response headers list exactly as they were received.</p>
<p>The keys and values are in the same list. It is <em>not</em> a
list of tuples. So, the even-numbered offsets are key values, and the
odd-numbered offsets are the associated values.</p>
<p>Header names are not lowercased, and duplicates are not merged.</p>
<pre><code class="language-js">// Prints something like:
//
// [ 'user-agent',
//   'this is invalid because there can be only one',
//   'User-Agent',
//   'curl/7.22.0',
//   'Host',
//   '127.0.0.1:8000',
//   'ACCEPT',
//   '*/*' ]
console.log(request.rawHeaders);
</code></pre>
<h3><code>message.rawTrailers</code><span><a class="mark" href="#http_message_rawtrailers" id="http_message_rawtrailers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.6</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>The raw request/response trailer keys and values exactly as they were
received. Only populated at the <code>'end'</code> event.</p>
<h3><code>message.setTimeout(msecs[, callback])</code><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">&#x3C;number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#http_class_http_incomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
</ul>
<p>Calls <code>message.connection.setTimeout(msecs, callback)</code>.</p>
<h3><code>message.socket</code><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="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>The <a href="#net_class_net_socket"><code>net.Socket</code></a> object associated with the connection.</p>
<p>With HTTPS support, use <a href="#tls_tlssocket_getpeercertificate_detailed"><code>request.socket.getPeerCertificate()</code></a> to obtain the
client's authentication details.</p>
<p>This property is guaranteed to be an instance of the <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>, unless the user specified a socket
type other than <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a>.</p>
<h3><code>message.statusCode</code><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">&#x3C;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><code>message.statusMessage</code><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">&#x3C;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><code>message.trailers</code><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">&#x3C;Object></a></li>
</ul>
<p>The request/response trailers object. Only populated at the <code>'end'</code> event.</p>
<h3><code>message.url</code><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">&#x3C;string></a></li>
</ul>
<p><strong>Only valid for request obtained from <a href="#http_class_http_server"><code>http.Server</code></a>.</strong></p>
<p>Request URL string. This contains only the URL that is
present in the actual HTTP request. If the request is:</p>
<pre><code class="language-http">GET /status?name=ryan HTTP/1.1\r\n
Accept: text/plain\r\n
\r\n
</code></pre>
<p>To parse the URL into its parts:</p>
<pre><code class="language-js">new URL(request.url, `http://${request.headers.host}`);
</code></pre>
<p>When <code>request.url</code> is <code>'/status?name=ryan'</code> and
<code>request.headers.host</code> is <code>'localhost:3000'</code>:</p>
<pre><code class="language-console">$ node
> new URL(request.url, `http://${request.headers.host}`)
URL {
  href: 'http://localhost:3000/status?name=ryan',
  origin: 'http://localhost:3000',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost:3000',
  hostname: 'localhost',
  port: '3000',
  pathname: '/status',
  search: '?name=ryan',
  searchParams: URLSearchParams { 'name' => 'ryan' },
  hash: ''
}
</code></pre>
<h2><code>http.METHODS</code><span><a class="mark" href="#http_http_methods" id="http_http_methods">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>A list of the HTTP methods that are supported by the parser.</p>
<h2><code>http.STATUS_CODES</code><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">&#x3C;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><code>http.createServer([options][, requestListener])</code><span><a class="mark" href="#http_http_createserver_options_requestlistener" id="http_http_createserver_options_requestlistener">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.15.0</td>
<td><p>The <code>insecureHTTPParser</code> option is supported now.</p></td></tr>
<tr><td>v9.6.0, v8.12.0</td>
<td><p>The <code>options</code> argument is supported now.</p></td></tr>
<tr><td>v0.1.13</td>
<td><p><span>Added in: v0.1.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>IncomingMessage</code> <a href="#http_class_http_incomingmessage" class="type">&#x3C;http.IncomingMessage></a> Specifies the <code>IncomingMessage</code>
class to be used. Useful for extending the original <code>IncomingMessage</code>.
<strong>Default:</strong> <code>IncomingMessage</code>.</li>
<li><code>ServerResponse</code> <a href="#http_class_http_serverresponse" class="type">&#x3C;http.ServerResponse></a> Specifies the <code>ServerResponse</code> class
to be used. Useful for extending the original <code>ServerResponse</code>. <strong>Default:</strong>
<code>ServerResponse</code>.</li>
<li><code>insecureHTTPParser</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Use an insecure HTTP parser that accepts
invalid HTTP headers when <code>true</code>. Using the insecure parser should be
avoided. See <a href="#cli_insecure_http_parser"><code>--insecure-http-parser</code></a> for more information.
<strong>Default:</strong> <code>false</code></li>
</ul>
</li>
<li>
<p><code>requestListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
</li>
<li>
<p>Returns: <a href="#http_class_http_server" class="type">&#x3C;http.Server></a></p>
</li>
</ul>
<p>Returns a new instance of <a href="#http_class_http_server"><code>http.Server</code></a>.</p>
<p>The <code>requestListener</code> is a function which is automatically
added to the <a href="#http_event_request"><code>'request'</code></a> event.</p>
<h2><code>http.get(options[, callback])</code><span><a class="mark" href="#http_http_get_options_callback" id="http_http_get_options_callback">#</a></span></h2>
<h2><code>http.get(url[, options][, callback])</code><span><a class="mark" href="#http_http_get_url_options_callback" id="http_http_get_url_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr>
<tr><td>v7.5.0</td>
<td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr>
<tr><td>v0.3.6</td>
<td><p><span>Added in: v0.3.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Accepts the same <code>options</code> as
<a href="#http_http_request_options_callback"><code>http.request()</code></a>, with the <code>method</code> always set to <code>GET</code>.
Properties that are inherited from the prototype are ignored.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#http_class_http_clientrequest" class="type">&#x3C;http.ClientRequest></a></li>
</ul>
<p>Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and
<a href="#http_http_request_options_callback"><code>http.request()</code></a> is that it sets the method to GET and calls <code>req.end()</code>
automatically. The callback must take care to consume the response
data for reasons stated in <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> section.</p>
<p>The <code>callback</code> is invoked with a single argument that is an instance of
<a href="#http_class_http_incomingmessage"><code>http.IncomingMessage</code></a>.</p>
<p>JSON fetching example:</p>
<pre><code class="language-js">http.get('http://nodejs.org/dist/index.json', (res) => {
  const { statusCode } = res;
  const contentType = res.headers['content-type'];

  let error;
  if (statusCode !== 200) {
    error = new Error('Request Failed.\n' +
                      `Status Code: ${statusCode}`);
  } else if (!/^application\/json/.test(contentType)) {
    error = new Error('Invalid content-type.\n' +
                      `Expected application/json but received ${contentType}`);
  }
  if (error) {
    console.error(error.message);
    // Consume response data to free up memory
    res.resume();
    return;
  }

  res.setEncoding('utf8');
  let rawData = '';
  res.on('data', (chunk) => { rawData += chunk; });
  res.on('end', () => {
    try {
      const parsedData = JSON.parse(rawData);
      console.log(parsedData);
    } catch (e) {
      console.error(e.message);
    }
  });
}).on('error', (e) => {
  console.error(`Got error: ${e.message}`);
});
</code></pre>
<h2><code>http.globalAgent</code><span><a class="mark" href="#http_http_globalagent" id="http_http_globalagent">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div>
<ul>
<li><a href="#http_class_http_agent" class="type">&#x3C;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><code>http.maxHeaderSize</code><span><a class="mark" href="#http_http_maxheadersize" id="http_http_maxheadersize">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.6.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Read-only property specifying the maximum allowed size of HTTP headers in bytes.
Defaults to 8KB. Configurable using the <a href="#cli_max_http_header_size_size"><code>--max-http-header-size</code></a> CLI option.</p>
<h2><code>http.request(options[, callback])</code><span><a class="mark" href="#http_http_request_options_callback" id="http_http_request_options_callback">#</a></span></h2>
<h2><code>http.request(url[, options][, callback])</code><span><a class="mark" href="#http_http_request_url_options_callback" id="http_http_request_url_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.15.0</td>
<td><p>The <code>insecureHTTPParser</code> option is supported now.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr>
<tr><td>v7.5.0</td>
<td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr>
<tr><td>v0.3.6</td>
<td><p><span>Added in: v0.3.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li>
<p><code>agent</code> <a href="#http_class_http_agent" class="type">&#x3C;http.Agent></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Controls <a href="#http_class_http_agent"><code>Agent</code></a> behavior. Possible
values:</p>
<ul>
<li><code>undefined</code> (default): use <a href="#http_http_globalagent"><code>http.globalAgent</code></a> for this host and port.</li>
<li><code>Agent</code> object: explicitly use the passed in <code>Agent</code>.</li>
<li><code>false</code>: causes a new <code>Agent</code> with default values to be used.</li>
</ul>
</li>
<li><code>auth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Basic authentication i.e. <code>'user:password'</code> to compute an
Authorization header.</li>
<li><code>createConnection</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A function that produces a socket/stream to
use for the request when the <code>agent</code> option is not used. This can be used to
avoid creating a custom <code>Agent</code> class just to override the default
<code>createConnection</code> function. See <a href="#http_agent_createconnection_options_callback"><code>agent.createConnection()</code></a> for more
details. Any <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream is a valid return value.</li>
<li><code>defaultPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Default port for the protocol. <strong>Default:</strong>
<code>agent.defaultPort</code> if an <code>Agent</code> is used, else <code>undefined</code>.</li>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> IP address family to use when resolving <code>host</code> or
<code>hostname</code>. Valid values are <code>4</code> or <code>6</code>. When unspecified, both IP v4 and
v6 will be used.</li>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object containing request headers.</li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> A domain name or IP address of the server to issue the
request to. <strong>Default:</strong> <code>'localhost'</code>.</li>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Alias for <code>host</code>. To support <a href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>,
<code>hostname</code> will be used if both <code>host</code> and <code>hostname</code> are specified.</li>
<li><code>insecureHTTPParser</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Use an insecure HTTP parser that accepts
invalid HTTP headers when <code>true</code>. Using the insecure parser should be
avoided. See <a href="#cli_insecure_http_parser"><code>--insecure-http-parser</code></a> for more information.
<strong>Default:</strong> <code>false</code></li>
<li><code>localAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Local interface to bind for network connections.</li>
<li><code>lookup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Custom lookup function. <strong>Default:</strong> <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li>
<li><code>method</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> A string specifying the HTTP request method. <strong>Default:</strong>
<code>'GET'</code>.</li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Request path. Should include query string if any.
E.G. <code>'/index.html?page=12'</code>. An exception is thrown when the request path
contains illegal characters. Currently, only spaces are rejected but that
may change in the future. <strong>Default:</strong> <code>'/'</code>.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Port of remote server. <strong>Default:</strong> <code>defaultPort</code> if set,
else <code>80</code>.</li>
<li><code>protocol</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Protocol to use. <strong>Default:</strong> <code>'http:'</code>.</li>
<li><code>setHost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a>: Specifies whether or not to automatically add the
<code>Host</code> header. Defaults to <code>true</code>.</li>
<li><code>socketPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Unix Domain Socket (cannot be used if one of <code>host</code>
or <code>port</code> is specified, those specify a TCP Socket).</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a>: A number specifying the socket timeout in milliseconds.
This will set the timeout before the socket is connected.</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#http_class_http_clientrequest" class="type">&#x3C;http.ClientRequest></a></li>
</ul>
<p>Node.js maintains several connections per server to make HTTP requests.
This function allows one to transparently issue requests.</p>
<p><code>url</code> can be a string or a <a href="#url_the_whatwg_url_api"><code>URL</code></a> object. If <code>url</code> is a
string, it is automatically parsed with <a href="#url_constructor_new_url_input_base"><code>new URL()</code></a>. If it is a <a href="#url_the_whatwg_url_api"><code>URL</code></a>
object, it will be automatically converted to an ordinary <code>options</code> object.</p>
<p>If both <code>url</code> and <code>options</code> are specified, the objects are merged, with the
<code>options</code> properties taking precedence.</p>
<p>The optional <code>callback</code> parameter will be added as a one-time listener for
the <a href="#http_event_response"><code>'response'</code></a> event.</p>
<p><code>http.request()</code> returns an instance of the <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a>
class. The <code>ClientRequest</code> instance is a writable stream. If one needs to
upload a file with a POST request, then write to the <code>ClientRequest</code> object.</p>
<pre><code class="language-js">const postData = querystring.stringify({
  'msg': 'Hello World!'
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(postData)
  }
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();
</code></pre>
<p>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 RFC 2616 Section 8.2.3 for more
information.</p>
</li>
<li>
<p>Sending an Authorization header will override using the <code>auth</code> option
to compute basic authentication.</p>
</li>
</ul>
<p>Example using a <a href="#url_the_whatwg_url_api"><code>URL</code></a> as <code>options</code>:</p>
<pre><code class="language-js">const options = new URL('http://abc:xyz@example.com');

const req = http.request(options, (res) => {
  // ...
});
</code></pre>
<p>In a successful request, the following events will be emitted in the following
order:</p>
<ul>
<li><code>'socket'</code></li>
<li>
<p><code>'response'</code></p>
<ul>
<li><code>'data'</code> any number of times, on the <code>res</code> object
(<code>'data'</code> will not be emitted at all if the response body is empty, for
instance, in most redirects)</li>
<li><code>'end'</code> on the <code>res</code> object</li>
</ul>
</li>
<li><code>'close'</code></li>
</ul>
<p>In the case of a connection error, the following events will be emitted:</p>
<ul>
<li><code>'socket'</code></li>
<li><code>'error'</code></li>
<li><code>'close'</code></li>
</ul>
<p>If <code>req.abort()</code> is called before the connection succeeds, the following events
will be emitted in the following order:</p>
<ul>
<li><code>'socket'</code></li>
<li>(<code>req.abort()</code> called here)</li>
<li><code>'abort'</code></li>
<li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code
<code>'ECONNRESET'</code></li>
<li><code>'close'</code></li>
</ul>
<p>If <code>req.abort()</code> is called after the response is received, the following events
will be emitted in the following order:</p>
<ul>
<li><code>'socket'</code></li>
<li>
<p><code>'response'</code></p>
<ul>
<li><code>'data'</code> any number of times, on the <code>res</code> object</li>
</ul>
</li>
<li>(<code>req.abort()</code> called here)</li>
<li><code>'abort'</code></li>
<li><code>'aborted'</code> on the <code>res</code> object</li>
<li><code>'close'</code></li>
<li><code>'end'</code> on the <code>res</code> object</li>
<li><code>'close'</code> on the <code>res</code> object</li>
</ul>
<p>Setting the <code>timeout</code> option or using the <code>setTimeout()</code> function will
not abort the request or do anything besides add a <code>'timeout'</code> event.</p>
<h1>HTTP/2<span><a class="mark" href="#http2_http_2" id="http2_http_2">#</a></span></h1>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.10.0</td>
<td><p>HTTP/2 is now Stable. Previously, it had been Experimental.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>http2</code> module provides an implementation of the <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> protocol. It
can be accessed using:</p>
<pre><code class="language-js">const http2 = require('http2');
</code></pre>
<h2>Core API<span><a class="mark" href="#http2_core_api" id="http2_core_api">#</a></span></h2>
<p>The Core API provides a low-level interface designed specifically around
support for HTTP/2 protocol features. It is specifically <em>not</em> designed for
compatibility with the existing <a href="http.html">HTTP/1</a> module API. However,
the <a href="#http2_compatibility_api">Compatibility API</a> is.</p>
<p>The <code>http2</code> Core API is much more symmetric between client and server than the
<code>http</code> API. For instance, most events, like <code>'error'</code>, <code>'connect'</code> and
<code>'stream'</code>, can be emitted either by client-side code or server-side code.</p>
<h3>Server-side example<span><a class="mark" href="#http2_server_side_example" id="http2_server_side_example">#</a></span></h3>
<p>The following illustrates a simple HTTP/2 server using the Core API.
Since there are no browsers known that support
<a href="https://http2.github.io/faq/#does-http2-require-encryption">unencrypted HTTP/2</a>, the use of
<a href="#http2_http2_createsecureserver_options_onrequesthandler"><code>http2.createSecureServer()</code></a> is necessary when communicating
with browser clients.</p>
<pre><code class="language-js">const http2 = require('http2');
const fs = require('fs');

const server = http2.createSecureServer({
  key: fs.readFileSync('localhost-privkey.pem'),
  cert: fs.readFileSync('localhost-cert.pem')
});
server.on('error', (err) => console.error(err));

server.on('stream', (stream, headers) => {
  // stream is a Duplex
  stream.respond({
    'content-type': 'text/html',
    ':status': 200
  });
  stream.end('&#x3C;h1>Hello World&#x3C;/h1>');
});

server.listen(8443);
</code></pre>
<p>To generate the certificate and key for this example, run:</p>
<pre><code class="language-bash">openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
  -keyout localhost-privkey.pem -out localhost-cert.pem
</code></pre>
<h3>Client-side example<span><a class="mark" href="#http2_client_side_example" id="http2_client_side_example">#</a></span></h3>
<p>The following illustrates an HTTP/2 client:</p>
<pre><code class="language-js">const http2 = require('http2');
const fs = require('fs');
const client = http2.connect('https://localhost:8443', {
  ca: fs.readFileSync('localhost-cert.pem')
});
client.on('error', (err) => console.error(err));

const req = client.request({ ':path': '/' });

req.on('response', (headers, flags) => {
  for (const name in headers) {
    console.log(`${name}: ${headers[name]}`);
  }
});

req.setEncoding('utf8');
let data = '';
req.on('data', (chunk) => { data += chunk; });
req.on('end', () => {
  console.log(`\n${data}`);
  client.close();
});
req.end();
</code></pre>
<h3>Class: <code>Http2Session</code><span><a class="mark" href="#http2_class_http2session" id="http2_class_http2session">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Instances of the <code>http2.Http2Session</code> class represent an active communications
session between an HTTP/2 client and server. Instances of this class are <em>not</em>
intended to be constructed directly by user code.</p>
<p>Each <code>Http2Session</code> instance will exhibit slightly different behaviors
depending on whether it is operating as a server or a client. The
<code>http2session.type</code> property can be used to determine the mode in which an
<code>Http2Session</code> is operating. On the server side, user code should rarely
have occasion to work with the <code>Http2Session</code> object directly, with most
actions typically taken through interactions with either the <code>Http2Server</code> or
<code>Http2Stream</code> objects.</p>
<p>User code will not create <code>Http2Session</code> instances directly. Server-side
<code>Http2Session</code> instances are created by the <code>Http2Server</code> instance when a
new HTTP/2 connection is received. Client-side <code>Http2Session</code> instances are
created using the <code>http2.connect()</code> method.</p>
<h4><code>Http2Session</code> and sockets<span><a class="mark" href="#http2_http2session_and_sockets" id="http2_http2session_and_sockets">#</a></span></h4>
<p>Every <code>Http2Session</code> instance is associated with exactly one <a href="#net_class_net_socket"><code>net.Socket</code></a> or
<a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> when it is created. When either the <code>Socket</code> or the
<code>Http2Session</code> are destroyed, both will be destroyed.</p>
<p>Because of the specific serialization and processing requirements imposed
by the HTTP/2 protocol, it is not recommended for user code to read data from
or write data to a <code>Socket</code> instance bound to a <code>Http2Session</code>. Doing so can
put the HTTP/2 session into an indeterminate state causing the session and
the socket to become unusable.</p>
<p>Once a <code>Socket</code> has been bound to an <code>Http2Session</code>, user code should rely
solely on the API of the <code>Http2Session</code>.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#http2_event_close" id="http2_event_close">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'close'</code> event is emitted once the <code>Http2Session</code> has been destroyed. Its
listener does not expect any arguments.</p>
<h4>Event: <code>'connect'</code><span><a class="mark" href="#http2_event_connect" id="http2_event_connect">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>session</code> <a href="#http2_class_http2session" class="type">&#x3C;Http2Session></a></li>
<li><code>socket</code> <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>The <code>'connect'</code> event is emitted once the <code>Http2Session</code> has been successfully
connected to the remote peer and communication may begin.</p>
<p>User code will typically not listen for this event directly.</p>
<h4>Event: <code>'error'</code><span><a class="mark" href="#http2_event_error" id="http2_event_error">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p>The <code>'error'</code> event is emitted when an error occurs during the processing of
an <code>Http2Session</code>.</p>
<h4>Event: <code>'frameError'</code><span><a class="mark" href="#http2_event_frameerror" id="http2_event_frameerror">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The frame type.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The error code.</li>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The stream id (or <code>0</code> if the frame isn't associated with a
stream).</li>
</ul>
<p>The <code>'frameError'</code> event is emitted when an error occurs while attempting to
send a frame on the session. If the frame that could not be sent is associated
with a specific <code>Http2Stream</code>, an attempt to emit a <code>'frameError'</code> event on the
<code>Http2Stream</code> is made.</p>
<p>If the <code>'frameError'</code> event is associated with a stream, the stream will be
closed and destroyed immediately following the <code>'frameError'</code> event. If the
event is not associated with a stream, the <code>Http2Session</code> will be shut down
immediately following the <code>'frameError'</code> event.</p>
<h4>Event: <code>'goaway'</code><span><a class="mark" href="#http2_event_goaway" id="http2_event_goaway">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>errorCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The HTTP/2 error code specified in the <code>GOAWAY</code> frame.</li>
<li><code>lastStreamID</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The ID of the last stream the remote peer successfully
processed (or <code>0</code> if no ID is specified).</li>
<li><code>opaqueData</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> If additional opaque data was included in the <code>GOAWAY</code>
frame, a <code>Buffer</code> instance will be passed containing that data.</li>
</ul>
<p>The <code>'goaway'</code> event is emitted when a <code>GOAWAY</code> frame is received.</p>
<p>The <code>Http2Session</code> instance will be shut down automatically when the <code>'goaway'</code>
event is emitted.</p>
<h4>Event: <code>'localSettings'</code><span><a class="mark" href="#http2_event_localsettings" id="http2_event_localsettings">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#http2_settings_object" class="type">&#x3C;HTTP/2 Settings Object></a> A copy of the <code>SETTINGS</code> frame received.</li>
</ul>
<p>The <code>'localSettings'</code> event is emitted when an acknowledgment <code>SETTINGS</code> frame
has been received.</p>
<p>When using <code>http2session.settings()</code> to submit new settings, the modified
settings do not take effect until the <code>'localSettings'</code> event is emitted.</p>
<pre><code class="language-js">session.settings({ enablePush: false });

session.on('localSettings', (settings) => {
  /* Use the new settings */
});
</code></pre>
<h4>Event: <code>'ping'</code><span><a class="mark" href="#http2_event_ping" id="http2_event_ping">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<ul>
<li><code>payload</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The <code>PING</code> frame 8-byte payload</li>
</ul>
<p>The <code>'ping'</code> event is emitted whenever a <code>PING</code> frame is received from the
connected peer.</p>
<h4>Event: <code>'remoteSettings'</code><span><a class="mark" href="#http2_event_remotesettings" id="http2_event_remotesettings">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#http2_settings_object" class="type">&#x3C;HTTP/2 Settings Object></a> A copy of the <code>SETTINGS</code> frame received.</li>
</ul>
<p>The <code>'remoteSettings'</code> event is emitted when a new <code>SETTINGS</code> frame is received
from the connected peer.</p>
<pre><code class="language-js">session.on('remoteSettings', (settings) => {
  /* Use the new settings */
});
</code></pre>
<h4>Event: <code>'stream'</code><span><a class="mark" href="#http2_event_stream" id="http2_event_stream">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#http2_class_http2stream" class="type">&#x3C;Http2Stream></a> A reference to the stream</li>
<li><code>headers</code> <a href="#http2_headers_object" class="type">&#x3C;HTTP/2 Headers Object></a> An object describing the headers</li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The associated numeric flags</li>
<li><code>rawHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> An array containing the raw header names followed by
their respective values.</li>
</ul>
<p>The <code>'stream'</code> event is emitted when a new <code>Http2Stream</code> is created.</p>
<pre><code class="language-js">const http2 = require('http2');
session.on('stream', (stream, headers, flags) => {
  const method = headers[':method'];
  const path = headers[':path'];
  // ...
  stream.respond({
    ':status': 200,
    'content-type': 'text/plain'
  });
  stream.write('hello ');
  stream.end('world');
});
</code></pre>
<p>On the server side, user code will typically not listen for this event directly,
and would instead register a handler for the <code>'stream'</code> event emitted by the
<code>net.Server</code> or <code>tls.Server</code> instances returned by <code>http2.createServer()</code> and
<code>http2.createSecureServer()</code>, respectively, as in the example below:</p>
<pre><code class="language-js">const http2 = require('http2');

// Create an unencrypted HTTP/2 server
const server = http2.createServer();

server.on('stream', (stream, headers) => {
  stream.respond({
    'content-type': 'text/html',
    ':status': 200
  });
  stream.on('error', (error) => console.error(error));
  stream.end('&#x3C;h1>Hello World&#x3C;/h1>');
});

server.listen(80);
</code></pre>
<p>Even though HTTP/2 streams and network sockets are not in a 1:1 correspondence,
a network error will destroy each individual stream and must be handled on the
stream level, as shown above.</p>
<h4>Event: <code>'timeout'</code><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.
Its listener does not expect any arguments.</p>
<pre><code class="language-js">session.setTimeout(2000);
session.on('timeout', () => { /* .. */ });
</code></pre>
<h4><code>http2session.alpnProtocol</code><span><a class="mark" href="#http2_http2session_alpnprotocol" id="http2_http2session_alpnprotocol">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;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><code>http2session.close([callback])</code><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">&#x3C;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><code>http2session.closed</code><span><a class="mark" href="#http2_http2session_closed" id="http2_http2session_closed">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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><code>http2session.connecting</code><span><a class="mark" href="#http2_http2session_connecting" id="http2_http2session_connecting">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Will be <code>true</code> if this <code>Http2Session</code> instance is still connecting, will be set
to <code>false</code> before emitting <code>connect</code> event and/or calling the <code>http2.connect</code>
callback.</p>
<h4><code>http2session.destroy([error][, code])</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">&#x3C;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">&#x3C;number></a> The HTTP/2 error code to send in the final <code>GOAWAY</code> frame.
If unspecified, and <code>error</code> is not undefined, the default is <code>INTERNAL_ERROR</code>,
otherwise defaults to <code>NO_ERROR</code>.</li>
</ul>
<p>Immediately terminates the <code>Http2Session</code> and the associated <code>net.Socket</code> or
<code>tls.TLSSocket</code>.</p>
<p>Once destroyed, the <code>Http2Session</code> will emit the <code>'close'</code> event. If <code>error</code>
is not undefined, an <code>'error'</code> event will be emitted immediately before the
<code>'close'</code> event.</p>
<p>If there are any remaining open <code>Http2Streams</code> associated with the
<code>Http2Session</code>, those will also be destroyed.</p>
<h4><code>http2session.destroyed</code><span><a class="mark" href="#http2_http2session_destroyed" id="http2_http2session_destroyed">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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><code>http2session.encrypted</code><span><a class="mark" href="#http2_http2session_encrypted" id="http2_http2session_encrypted">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;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><code>http2session.goaway([code[, lastStreamID[, opaqueData]]])</code><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">&#x3C;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">&#x3C;number></a> The numeric ID of the last processed <code>Http2Stream</code></li>
<li><code>opaqueData</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> A <code>TypedArray</code> or <code>DataView</code>
instance containing additional data to be carried within the <code>GOAWAY</code> frame.</li>
</ul>
<p>Transmits a <code>GOAWAY</code> frame to the connected peer <em>without</em> shutting down the
<code>Http2Session</code>.</p>
<h4><code>http2session.localSettings</code><span><a class="mark" href="#http2_http2session_localsettings" id="http2_http2session_localsettings">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#http2_settings_object" class="type">&#x3C;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><code>http2session.originSet</code><span><a class="mark" href="#http2_http2session_originset" id="http2_http2session_originset">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>If the <code>Http2Session</code> is connected to a <code>TLSSocket</code>, the <code>originSet</code> property
will return an <code>Array</code> of origins for which the <code>Http2Session</code> may be
considered authoritative.</p>
<p>The <code>originSet</code> property is only available when using a secure TLS connection.</p>
<h4><code>http2session.pendingSettingsAck</code><span><a class="mark" href="#http2_http2session_pendingsettingsack" id="http2_http2session_pendingsettingsack">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Indicates whether the <code>Http2Session</code> is currently waiting for acknowledgment of
a sent <code>SETTINGS</code> frame. Will be <code>true</code> after calling the
<code>http2session.settings()</code> method. Will be <code>false</code> once all sent <code>SETTINGS</code>
frames have been acknowledged.</p>
<h4><code>http2session.ping([payload, ]callback)</code><span><a class="mark" href="#http2_http2session_ping_payload_callback" id="http2_http2session_ping_payload_callback">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.9.3</span>
</div>
<ul>
<li><code>payload</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;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">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Sends a <code>PING</code> frame to the connected HTTP/2 peer. A <code>callback</code> function must
be provided. The method will return <code>true</code> if the <code>PING</code> was sent, <code>false</code>
otherwise.</p>
<p>The maximum number of outstanding (unacknowledged) pings is determined by the
<code>maxOutstandingPings</code> configuration option. The default maximum is 10.</p>
<p>If provided, the <code>payload</code> must be a <code>Buffer</code>, <code>TypedArray</code>, or <code>DataView</code>
containing 8 bytes of data that will be transmitted with the <code>PING</code> and
returned with the ping acknowledgment.</p>
<p>The callback will be invoked with three arguments: an error argument that will
be <code>null</code> if the <code>PING</code> was successfully acknowledged, a <code>duration</code> argument
that reports the number of milliseconds elapsed since the ping was sent and the
acknowledgment was received, and a <code>Buffer</code> containing the 8-byte <code>PING</code>
payload.</p>
<pre><code class="language-js">session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => {
  if (!err) {
    console.log(`Ping acknowledged in ${duration} milliseconds`);
    console.log(`With payload '${payload.toString()}'`);
  }
});
</code></pre>
<p>If the <code>payload</code> argument is not specified, the default payload will be the
64-bit timestamp (little endian) marking the start of the <code>PING</code> duration.</p>
<h4><code>http2session.ref()</code><span><a class="mark" href="#http2_http2session_ref" id="http2_http2session_ref">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<p>Calls <a href="#net_socket_ref"><code>ref()</code></a> on this <code>Http2Session</code>
instance's underlying <a href="#net_class_net_socket"><code>net.Socket</code></a>.</p>
<h4><code>http2session.remoteSettings</code><span><a class="mark" href="#http2_http2session_remotesettings" id="http2_http2session_remotesettings">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#http2_settings_object" class="type">&#x3C;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><code>http2session.setTimeout(msecs, callback)</code><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">&#x3C;number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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><code>http2session.socket</code><span><a class="mark" href="#http2_http2session_socket" id="http2_http2session_socket">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> | <a href="#tls_class_tls_tlssocket" class="type">&#x3C;tls.TLSSocket></a></li>
</ul>
<p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but
limits available methods to ones safe to use with HTTP/2.</p>
<p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw
an error with code <code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See
<a href="#http2_http2session_and_sockets"><code>Http2Session</code> and Sockets</a> for more information.</p>
<p><code>setTimeout</code> method will be called on this <code>Http2Session</code>.</p>
<p>All other interactions will be routed directly to the socket.</p>
<h4><code>http2session.state</code><span><a class="mark" href="#http2_http2session_state" id="http2_http2session_state">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>Provides miscellaneous information about the current state of the
<code>Http2Session</code>.</p>
<ul>
<li>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>effectiveLocalWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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><code>http2session.settings([settings][, callback])</code><span><a class="mark" href="#http2_http2session_settings_settings_callback" id="http2_http2session_settings_settings_callback">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#http2_settings_object" class="type">&#x3C;HTTP/2 Settings Object></a></li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Callback that is called once the session is connected or
right away if the session is already connected.</p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
<li><code>settings</code> <a href="#http2_settings_object" class="type">&#x3C;HTTP/2 Settings Object></a> The updated <code>settings</code> object.</li>
<li><code>duration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
</li>
</ul>
<p>Updates the current local settings for this <code>Http2Session</code> and sends a new
<code>SETTINGS</code> frame to the connected HTTP/2 peer.</p>
<p>Once called, the <code>http2session.pendingSettingsAck</code> property will be <code>true</code>
while the session is waiting for the remote peer to acknowledge the new
settings.</p>
<p>The new settings will not become effective until the <code>SETTINGS</code> acknowledgment
is received and the <code>'localSettings'</code> event is emitted. It is possible to send
multiple <code>SETTINGS</code> frames while acknowledgment is still pending.</p>
<h4><code>http2session.type</code><span><a class="mark" href="#http2_http2session_type" id="http2_http2session_type">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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><code>http2session.unref()</code><span><a class="mark" href="#http2_http2session_unref" id="http2_http2session_unref">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<p>Calls <a href="#net_socket_unref"><code>unref()</code></a> on this <code>Http2Session</code>
instance's underlying <a href="#net_class_net_socket"><code>net.Socket</code></a>.</p>
<h3>Class: <code>ServerHttp2Session</code><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>
<ul>
<li>Extends: <a href="#http2_class_http2session" class="type">&#x3C;Http2Session></a></li>
</ul>
<h4><code>serverhttp2session.altsvc(alt, originOrStream)</code><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">&#x3C;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">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Either a URL string specifying
the origin (or an <code>Object</code> with an <code>origin</code> property) or the numeric
identifier of an active <code>Http2Stream</code> as given by the <code>http2stream.id</code>
property.</li>
</ul>
<p>Submits an <code>ALTSVC</code> frame (as defined by <a href="https://tools.ietf.org/html/rfc7838">RFC 7838</a>) to the connected client.</p>
<pre><code class="language-js">const http2 = require('http2');

const server = http2.createServer();
server.on('session', (session) => {
  // Set altsvc for origin https://example.org:80
  session.altsvc('h2=":8000"', 'https://example.org:80');
});

server.on('stream', (stream) => {
  // Set altsvc for a specific stream
  stream.session.altsvc('h2=":8000"', stream.id);
});
</code></pre>
<p>Sending an <code>ALTSVC</code> frame with a specific stream ID indicates that the alternate
service is associated with the origin of the given <code>Http2Stream</code>.</p>
<p>The <code>alt</code> and origin string <em>must</em> contain only ASCII bytes and are
strictly interpreted as a sequence of ASCII bytes. The special value <code>'clear'</code>
may be passed to clear any previously set alternative service for a given
domain.</p>
<p>When a string is passed for the <code>originOrStream</code> argument, it will be parsed as
a URL and the origin will be derived. For instance, the origin for the
HTTP URL <code>'https://example.org/foo/bar'</code> is the ASCII string
<code>'https://example.org'</code>. An error will be thrown if either the given string
cannot be parsed as a URL or if a valid origin cannot be derived.</p>
<p>A <code>URL</code> object, or any object with an <code>origin</code> property, may be passed as
<code>originOrStream</code>, in which case the value of the <code>origin</code> property will be
used. The value of the <code>origin</code> property <em>must</em> be a properly serialized
ASCII origin.</p>
<h4>Specifying alternative services<span><a class="mark" href="#http2_specifying_alternative_services" id="http2_specifying_alternative_services">#</a></span></h4>
<p>The format of the <code>alt</code> parameter is strictly defined by <a href="https://tools.ietf.org/html/rfc7838">RFC 7838</a> as an
ASCII string containing a comma-delimited list of "alternative" protocols
associated with a specific host and port.</p>
<p>For example, the value <code>'h2="example.org:81"'</code> indicates that the HTTP/2
protocol is available on the host <code>'example.org'</code> on TCP/IP port 81. The
host and port <em>must</em> be contained within the quote (<code>"</code>) characters.</p>
<p>Multiple alternatives may be specified, for instance: <code>'h2="example.org:81", h2=":82"'</code>.</p>
<p>The protocol identifier (<code>'h2'</code> in the examples) may be any valid
<a href="https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids">ALPN Protocol ID</a>.</p>
<p>The syntax of these values is not validated by the Node.js implementation and
are passed through as provided by the user or received from the peer.</p>
<h4><code>serverhttp2session.origin(...origins)</code><span><a class="mark" href="#http2_serverhttp2session_origin_origins" id="http2_serverhttp2session_origin_origins">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<ul>
<li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> One or more URL Strings passed as
separate arguments.</li>
</ul>
<p>Submits an <code>ORIGIN</code> frame (as defined by <a href="https://tools.ietf.org/html/rfc8336">RFC 8336</a>) to the connected client
to advertise the set of origins for which the server is capable of providing
authoritative responses.</p>
<pre><code class="language-js">const http2 = require('http2');
const options = getSecureOptionsSomehow();
const server = http2.createSecureServer(options);
server.on('stream', (stream) => {
  stream.respond();
  stream.end('ok');
});
server.on('session', (session) => {
  session.origin('https://example.com', 'https://example.org');
});
</code></pre>
<p>When a string is passed as an <code>origin</code>, it will be parsed as a URL and the
origin will be derived. For instance, the origin for the HTTP URL
<code>'https://example.org/foo/bar'</code> is the ASCII string
<code>'https://example.org'</code>. An error will be thrown if either the given string
cannot be parsed as a URL or if a valid origin cannot be derived.</p>
<p>A <code>URL</code> object, or any object with an <code>origin</code> property, may be passed as
an <code>origin</code>, in which case the value of the <code>origin</code> property will be
used. The value of the <code>origin</code> property <em>must</em> be a properly serialized
ASCII origin.</p>
<p>Alternatively, the <code>origins</code> option may be used when creating a new HTTP/2
server using the <code>http2.createSecureServer()</code> method:</p>
<pre><code class="language-js">const http2 = require('http2');
const options = getSecureOptionsSomehow();
options.origins = ['https://example.com', 'https://example.org'];
const server = http2.createSecureServer(options);
server.on('stream', (stream) => {
  stream.respond();
  stream.end('ok');
});
</code></pre>
<h3>Class: <code>ClientHttp2Session</code><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>
<ul>
<li>Extends: <a href="#http2_class_http2session" class="type">&#x3C;Http2Session></a></li>
</ul>
<h4>Event: <code>'altsvc'</code><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">&#x3C;string></a></li>
<li><code>origin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>streamId</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The <code>'altsvc'</code> event is emitted whenever an <code>ALTSVC</code> frame is received by
the client. The event is emitted with the <code>ALTSVC</code> value, origin, and stream
ID. If no <code>origin</code> is provided in the <code>ALTSVC</code> frame, <code>origin</code> will
be an empty string.</p>
<pre><code class="language-js">const http2 = require('http2');
const client = http2.connect('https://example.org');

client.on('altsvc', (alt, origin, streamId) => {
  console.log(alt);
  console.log(origin);
  console.log(streamId);
});
</code></pre>
<h4>Event: <code>'origin'</code><span><a class="mark" href="#http2_event_origin" id="http2_event_origin">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<ul>
<li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>The <code>'origin'</code> event is emitted whenever an <code>ORIGIN</code> frame is received by
the client. The event is emitted with an array of <code>origin</code> strings. The
<code>http2session.originSet</code> will be updated to include the received
origins.</p>
<pre><code class="language-js">const http2 = require('http2');
const client = http2.connect('https://example.org');

client.on('origin', (origins) => {
  for (let n = 0; n &#x3C; origins.length; n++)
    console.log(origins[n]);
});
</code></pre>
<p>The <code>'origin'</code> event is only emitted when using a secure TLS connection.</p>
<h4><code>clienthttp2session.request(headers[, options])</code><span><a class="mark" href="#http2_clienthttp2session_request_headers_options" id="http2_clienthttp2session_request_headers_options">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>
<p><code>headers</code> <a href="#http2_headers_object" class="type">&#x3C;HTTP/2 Headers Object></a></p>
</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;number></a> Specifies the relative dependency of a stream in relation
to other streams with the same <code>parent</code>. The value is a number between <code>1</code>
and <code>256</code> (inclusive).</li>
<li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the
<code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li>
</ul>
</li>
<li>
<p>Returns: <a href="#http2_class_clienthttp2stream" class="type">&#x3C;ClientHttp2Stream></a></p>
</li>
</ul>
<p>For HTTP/2 Client <code>Http2Session</code> instances only, the <code>http2session.request()</code>
creates and returns an <code>Http2Stream</code> instance that can be used to send an
HTTP/2 request to the connected server.</p>
<p>This method is only available if <code>http2session.type</code> is equal to
<code>http2.constants.NGHTTP2_SESSION_CLIENT</code>.</p>
<pre><code class="language-js">const http2 = require('http2');
const clientSession = http2.connect('https://localhost:1234');
const {
  HTTP2_HEADER_PATH,
  HTTP2_HEADER_STATUS
} = http2.constants;

const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' });
req.on('response', (headers) => {
  console.log(headers[HTTP2_HEADER_STATUS]);
  req.on('data', (chunk) => { /* .. */ });
  req.on('end', () => { /* .. */ });
});
</code></pre>
<p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event
is emitted immediately after queuing the last chunk of payload data to be sent.
The <code>http2stream.sendTrailers()</code> method can then be called to send trailing
headers to the peer.</p>
<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically
close when the final <code>DATA</code> frame is transmitted. User code must call either
<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the
<code>Http2Stream</code>.</p>
<p>The <code>:method</code> and <code>:path</code> pseudo-headers are not specified within <code>headers</code>,
they respectively default to:</p>
<ul>
<li><code>:method</code> = <code>'GET'</code></li>
<li><code>:path</code> = <code>/</code></li>
</ul>
<h3>Class: <code>Http2Stream</code><span><a class="mark" href="#http2_class_http2stream" id="http2_class_http2stream">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>Each instance of the <code>Http2Stream</code> class represents a bidirectional HTTP/2
communications stream over an <code>Http2Session</code> instance. Any single <code>Http2Session</code>
may have up to 2<sup>31</sup>-1 <code>Http2Stream</code> instances over its lifetime.</p>
<p>User code will not construct <code>Http2Stream</code> instances directly. Rather, these
are created, managed, and provided to user code through the <code>Http2Session</code>
instance. On the server, <code>Http2Stream</code> instances are created either in response
to an incoming HTTP request (and handed off to user code via the <code>'stream'</code>
event), or in response to a call to the <code>http2stream.pushStream()</code> method.
On the client, <code>Http2Stream</code> instances are created and returned when either the
<code>http2session.request()</code> method is called, or in response to an incoming
<code>'push'</code> event.</p>
<p>The <code>Http2Stream</code> class is a base for the <a href="#http2_class_serverhttp2stream"><code>ServerHttp2Stream</code></a> and
<a href="#http2_class_clienthttp2stream"><code>ClientHttp2Stream</code></a> classes, each of which is used specifically by either
the Server or Client side, respectively.</p>
<p>All <code>Http2Stream</code> instances are <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams. The <code>Writable</code> side of the
<code>Duplex</code> is used to send data to the connected peer, while the <code>Readable</code> side
is used to receive data sent by the connected peer.</p>
<h4><code>Http2Stream</code> Lifecycle<span><a class="mark" href="#http2_http2stream_lifecycle" id="http2_http2stream_lifecycle">#</a></span></h4>
<h5>Creation<span><a class="mark" href="#http2_creation" id="http2_creation">#</a></span></h5>
<p>On the server side, instances of <a href="#http2_class_serverhttp2stream"><code>ServerHttp2Stream</code></a> are created either
when:</p>
<ul>
<li>A new HTTP/2 <code>HEADERS</code> frame with a previously unused stream ID is received;</li>
<li>The <code>http2stream.pushStream()</code> method is called.</li>
</ul>
<p>On the client side, instances of <a href="#http2_class_clienthttp2stream"><code>ClientHttp2Stream</code></a> are created when the
<code>http2session.request()</code> method is called.</p>
<p>On the client, the <code>Http2Stream</code> instance returned by <code>http2session.request()</code>
may not be immediately ready for use if the parent <code>Http2Session</code> has not yet
been fully established. In such cases, operations called on the <code>Http2Stream</code>
will be buffered until the <code>'ready'</code> event is emitted. User code should rarely,
if ever, need to handle the <code>'ready'</code> event directly. The ready status of an
<code>Http2Stream</code> can be determined by checking the value of <code>http2stream.id</code>. If
the value is <code>undefined</code>, the stream is not yet ready for use.</p>
<h5>Destruction<span><a class="mark" href="#http2_destruction" id="http2_destruction">#</a></span></h5>
<p>All <a href="#http2_class_http2stream"><code>Http2Stream</code></a> instances are destroyed either when:</p>
<ul>
<li>An <code>RST_STREAM</code> frame for the stream is received by the connected peer,
and pending data has been read.</li>
<li>The <code>http2stream.close()</code> method is called, and pending data has been read.</li>
<li>The <code>http2stream.destroy()</code> or <code>http2session.destroy()</code> methods are called.</li>
</ul>
<p>When an <code>Http2Stream</code> instance is destroyed, an attempt will be made to send an
<code>RST_STREAM</code> frame 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: <code>'aborted'</code><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.
Its listener does not expect any arguments.</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: <code>'close'</code><span><a class="mark" href="#http2_event_close_1" id="http2_event_close_1">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'close'</code> event is emitted when the <code>Http2Stream</code> is destroyed. Once
this event is emitted, the <code>Http2Stream</code> instance is no longer usable.</p>
<p>The HTTP/2 error code used when closing the stream can be retrieved using
the <code>http2stream.rstCode</code> property. If the code is any value other than
<code>NGHTTP2_NO_ERROR</code> (<code>0</code>), an <code>'error'</code> event will have also been emitted.</p>
<h4>Event: <code>'error'</code><span><a class="mark" href="#http2_event_error_1" id="http2_event_error_1">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p>The <code>'error'</code> event is emitted when an error occurs during the processing of
an <code>Http2Stream</code>.</p>
<h4>Event: <code>'frameError'</code><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>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The frame type.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The error code.</li>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The stream id (or <code>0</code> if the frame isn't associated with a
stream).</li>
</ul>
<p>The <code>'frameError'</code> event is emitted when an error occurs while attempting to
send a frame. 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: <code>'timeout'</code><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>.
Its listener does not expect any arguments.</p>
<h4>Event: <code>'trailers'</code><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>
<ul>
<li><code>headers</code> <a href="#http2_headers_object" class="type">&#x3C;HTTP/2 Headers Object></a> An object describing the headers</li>
<li><code>flags</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The associated numeric flags</li>
</ul>
<p>The <code>'trailers'</code> event is emitted when a block of headers associated with
trailing header fields is received. The listener callback is passed the
<a href="#http2_headers_object">HTTP/2 Headers Object</a> and flags associated with the headers.</p>
<p>This event might not be emitted if <code>http2stream.end()</code> is called
before trailers are received and the incoming data is not being read or
listened for.</p>
<pre><code class="language-js">stream.on('trailers', (headers, flags) => {
  console.log(headers);
});
</code></pre>
<h4>Event: <code>'wantTrailers'</code><span><a class="mark" href="#http2_event_wanttrailers" id="http2_event_wanttrailers">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>The <code>'wantTrailers'</code> event is emitted when the <code>Http2Stream</code> has queued the
final <code>DATA</code> frame to be sent on a frame and the <code>Http2Stream</code> is ready to send
trailing headers. When initiating a request or response, the <code>waitForTrailers</code>
option must be set for this event to be emitted.</p>
<h4><code>http2stream.aborted</code><span><a class="mark" href="#http2_http2stream_aborted" id="http2_http2stream_aborted">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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><code>http2stream.bufferSize</code><span><a class="mark" href="#http2_http2stream_buffersize" id="http2_http2stream_buffersize">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.2.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>This property shows the number of characters currently buffered to be written.
See <a href="#net_socket_buffersize"><code>net.Socket.bufferSize</code></a> for details.</p>
<h4><code>http2stream.close(code[, callback])</code><span><a class="mark" href="#http2_http2stream_close_code_callback" id="http2_http2stream_close_code_callback">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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><code>http2stream.closed</code><span><a class="mark" href="#http2_http2stream_closed" id="http2_http2stream_closed">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Set to <code>true</code> if the <code>Http2Stream</code> instance has been closed.</p>
<h4><code>http2stream.destroyed</code><span><a class="mark" href="#http2_http2stream_destroyed" id="http2_http2stream_destroyed">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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><code>http2stream.endAfterHeaders</code><span><a class="mark" href="#http2_http2stream_endafterheaders" id="http2_http2stream_endafterheaders">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.11.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Set the <code>true</code> if the <code>END_STREAM</code> flag was set in the request or response
HEADERS frame received, indicating that no additional data should be received
and the readable side of the <code>Http2Stream</code> will be closed.</p>
<h4><code>http2stream.id</code><span><a class="mark" href="#http2_http2stream_id" id="http2_http2stream_id">#</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">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>The numeric stream identifier of this <code>Http2Stream</code> instance. Set to <code>undefined</code>
if the stream identifier has not yet been assigned.</p>
<h4><code>http2stream.pending</code><span><a class="mark" href="#http2_http2stream_pending" id="http2_http2stream_pending">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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><code>http2stream.priority(options)</code><span><a class="mark" href="#http2_http2stream_priority_options" id="http2_http2stream_priority_options">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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><code>http2stream.rstCode</code><span><a class="mark" href="#http2_http2stream_rstcode" id="http2_http2stream_rstcode">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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><code>http2stream.sentHeaders</code><span><a class="mark" href="#http2_http2stream_sentheaders" id="http2_http2stream_sentheaders">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.5.0</span>
</div>
<ul>
<li><a href="#http2_headers_object" class="type">&#x3C;HTTP/2 Headers Object></a></li>
</ul>
<p>An object containing the outbound headers sent for this <code>Http2Stream</code>.</p>
<h4><code>http2stream.sentInfoHeaders</code><span><a class="mark" href="#http2_http2stream_sentinfoheaders" id="http2_http2stream_sentinfoheaders">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.5.0</span>
</div>
<ul>
<li><a href="#http2_headers_object" class="type">&#x3C;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><code>http2stream.sentTrailers</code><span><a class="mark" href="#http2_http2stream_senttrailers" id="http2_http2stream_senttrailers">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v9.5.0</span>
</div>
<ul>
<li><a href="#http2_headers_object" class="type">&#x3C;HTTP/2 Headers Object></a></li>
</ul>
<p>An object containing the outbound trailers sent for this <code>HttpStream</code>.</p>
<h4><code>http2stream.session</code><span><a class="mark" href="#http2_http2stream_session" id="http2_http2stream_session">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#http2_class_http2session" class="type">&#x3C;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><code>http2stream.setTimeout(msecs, callback)</code><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">&#x3C;number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<pre><code class="language-js">const http2 = require('http2');
const client = http2.connect('http://example.org:8000');
const { NGHTTP2_CANCEL } = http2.constants;
const req = client.request({ ':path': '/' });

// Cancel the stream if there's no activity after 5 seconds
req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL));
</code></pre>
<h4><code>http2stream.state</code><span><a class="mark" href="#http2_http2stream_state" id="http2_http2stream_state">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>Provides miscellaneous information about the current state of the
<code>Http2Stream</code>.</p>
<ul>
<li>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>localWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;number></a> A flag indicating the low-level current state of the
<code>Http2Stream</code> as determined by <code>nghttp2</code>.</li>
<li><code>localClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <code>1</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">&#x3C;number></a> <code>1</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">&#x3C;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">&#x3C;number></a> The priority weight of this <code>Http2Stream</code>.</li>
</ul>
</li>
</ul>
<p>A current state of this <code>Http2Stream</code>.</p>
<h4><code>http2stream.sendTrailers(headers)</code><span><a class="mark" href="#http2_http2stream_sendtrailers_headers" id="http2_http2stream_sendtrailers_headers">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#http2_headers_object" class="type">&#x3C;HTTP/2 Headers Object></a></li>
</ul>
<p>Sends a trailing <code>HEADERS</code> frame to the connected HTTP/2 peer. This method
will cause the <code>Http2Stream</code> to be immediately closed and must only be
called after the <code>'wantTrailers'</code> event has been emitted. When sending a
request or sending a response, the <code>options.waitForTrailers</code> option must be set
in order to keep the <code>Http2Stream</code> open after the final <code>DATA</code> frame so that
trailers can be sent.</p>
<pre><code class="language-js">const http2 = require('http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  stream.respond(undefined, { waitForTrailers: true });
  stream.on('wantTrailers', () => {
    stream.sendTrailers({ xyz: 'abc' });
  });
  stream.end('Hello World');
});
</code></pre>
<p>The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header
fields (e.g. <code>':method'</code>, <code>':path'</code>, etc).</p>
<h3>Class: <code>ClientHttp2Stream</code><span><a class="mark" href="#http2_class_clienthttp2stream" id="http2_class_clienthttp2stream">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends <a href="#http2_class_http2stream" class="type">&#x3C;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: <code>'continue'</code><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: <code>'headers'</code><span><a class="mark" href="#http2_event_headers" id="http2_event_headers">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'headers'</code> event is emitted when an additional block of headers is received
for a stream, such as when a block of <code>1xx</code> informational headers is received.
The listener callback is passed the <a href="#http2_headers_object">HTTP/2 Headers Object</a> and flags
associated with the headers.</p>
<pre><code class="language-js">stream.on('headers', (headers, flags) => {
  console.log(headers);
});
</code></pre>
<h4>Event: <code>'push'</code><span><a class="mark" href="#http2_event_push" id="http2_event_push">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'push'</code> event is emitted when response headers for a Server Push stream
are received. The listener callback is passed the <a href="#http2_headers_object">HTTP/2 Headers Object</a> and
flags associated with the headers.</p>
<pre><code class="language-js">stream.on('push', (headers, flags) => {
  console.log(headers);
});
</code></pre>
<h4>Event: <code>'response'</code><span><a class="mark" href="#http2_event_response" id="http2_event_response">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'response'</code> event is emitted when a response <code>HEADERS</code> frame has been
received for this stream from the connected HTTP/2 server. The listener is
invoked with two arguments: an <code>Object</code> containing the received
<a href="#http2_headers_object">HTTP/2 Headers Object</a>, and flags associated with the headers.</p>
<pre><code class="language-js">const http2 = require('http2');
const client = http2.connect('https://localhost');
const req = client.request({ ':path': '/' });
req.on('response', (headers, flags) => {
  console.log(headers[':status']);
});
</code></pre>
<h3>Class: <code>ServerHttp2Stream</code><span><a class="mark" href="#http2_class_serverhttp2stream" id="http2_class_serverhttp2stream">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#http2_class_http2stream" class="type">&#x3C;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><code>http2stream.additionalHeaders(headers)</code><span><a class="mark" href="#http2_http2stream_additionalheaders_headers" id="http2_http2stream_additionalheaders_headers">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#http2_headers_object" class="type">&#x3C;HTTP/2 Headers Object></a></li>
</ul>
<p>Sends an additional informational <code>HEADERS</code> frame to the connected HTTP/2 peer.</p>
<h4><code>http2stream.headersSent</code><span><a class="mark" href="#http2_http2stream_headerssent" id="http2_http2stream_headerssent">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>True if headers were sent, false otherwise (read-only).</p>
<h4><code>http2stream.pushAllowed</code><span><a class="mark" href="#http2_http2stream_pushallowed" id="http2_http2stream_pushallowed">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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><code>http2stream.pushStream(headers[, options], callback)</code><span><a class="mark" href="#http2_http2stream_pushstream_headers_options_callback" id="http2_http2stream_pushstream_headers_options_callback">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#http2_headers_object" class="type">&#x3C;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">&#x3C;Object></a></p>
<ul>
<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;number></a> Specifies the numeric identifier of a stream the newly
created stream is dependent on.</li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Callback that is called once the push stream has been
initiated.</p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>pushStream</code> <a href="#http2_class_serverhttp2stream" class="type">&#x3C;ServerHttp2Stream></a> The returned <code>pushStream</code> object.</li>
<li><code>headers</code> <a href="#http2_headers_object" class="type">&#x3C;HTTP/2 Headers Object></a> Headers object the <code>pushStream</code> was
initiated with.</li>
</ul>
</li>
</ul>
<p>Initiates a push stream. The callback is invoked with the new <code>Http2Stream</code>
instance created for the push stream passed as the second argument, or an
<code>Error</code> passed as the first argument.</p>
<pre><code class="language-js">const http2 = require('http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  stream.respond({ ':status': 200 });
  stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {
    if (err) throw err;
    pushStream.respond({ ':status': 200 });
    pushStream.end('some pushed data');
  });
  stream.end('some data');
});
</code></pre>
<p>Setting the weight of a push stream is not allowed in the <code>HEADERS</code> frame. Pass
a <code>weight</code> value to <code>http2stream.priority</code> with the <code>silent</code> option set to
<code>true</code> to enable server-side bandwidth balancing between concurrent streams.</p>
<p>Calling <code>http2stream.pushStream()</code> from within a pushed stream is not permitted
and will throw an error.</p>
<h4><code>http2stream.respond([headers[, options]])</code><span><a class="mark" href="#http2_http2stream_respond_headers_options" id="http2_http2stream_respond_headers_options">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#http2_headers_object" class="type">&#x3C;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">&#x3C;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">&#x3C;boolean></a> Set to <code>true</code> to indicate that the response will not
include payload data.</li>
<li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the
<code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li>
</ul>
</li>
</ul>
<pre><code class="language-js">const http2 = require('http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  stream.respond({ ':status': 200 });
  stream.end('some data');
});
</code></pre>
<p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event
will be emitted immediately after queuing the last chunk of payload data to be
sent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing
header fields to the peer.</p>
<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically
close when the final <code>DATA</code> frame is transmitted. User code must call either
<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the
<code>Http2Stream</code>.</p>
<pre><code class="language-js">const http2 = require('http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  stream.respond({ ':status': 200 }, { waitForTrailers: true });
  stream.on('wantTrailers', () => {
    stream.sendTrailers({ ABC: 'some value to send' });
  });
  stream.end('some data');
});
</code></pre>
<h4><code>http2stream.respondWithFD(fd[, headers[, options]])</code><span><a class="mark" href="#http2_http2stream_respondwithfd_fd_headers_options" id="http2_http2stream_respondwithfd_fd_headers_options">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.12.0</td>
<td><p>The <code>fd</code> option may now be a <code>FileHandle</code>.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Any readable file descriptor, not necessarily for a regular file, is supported now.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="#fs_class_filehandle" class="type">&#x3C;FileHandle></a> A readable file descriptor.</li>
<li><code>headers</code> <a href="#http2_headers_object" class="type">&#x3C;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">&#x3C;Object></a></p>
<ul>
<li><code>statCheck</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the
<code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;number></a> The amount of data from the fd to send.</li>
</ul>
</li>
</ul>
<p>Initiates a response whose data is read from the given file descriptor. No
validation is performed on the given file descriptor. If an error occurs while
attempting to read data using the file descriptor, the <code>Http2Stream</code> will be
closed using an <code>RST_STREAM</code> frame using the standard <code>INTERNAL_ERROR</code> code.</p>
<p>When used, the <code>Http2Stream</code> object's <code>Duplex</code> interface will be closed
automatically.</p>
<pre><code class="language-js">const http2 = require('http2');
const fs = require('fs');

const server = http2.createServer();
server.on('stream', (stream) => {
  const fd = fs.openSync('/some/file', 'r');

  const stat = fs.fstatSync(fd);
  const headers = {
    'content-length': stat.size,
    'last-modified': stat.mtime.toUTCString(),
    'content-type': 'text/plain'
  };
  stream.respondWithFD(fd, headers);
  stream.on('close', () => fs.closeSync(fd));
});
</code></pre>
<p>The optional <code>options.statCheck</code> function may be specified to give user code
an opportunity to set additional content headers based on the <code>fs.Stat</code> details
of the given fd. If the <code>statCheck</code> function is provided, the
<code>http2stream.respondWithFD()</code> method will perform an <code>fs.fstat()</code> call to
collect details on the provided file descriptor.</p>
<p>The <code>offset</code> and <code>length</code> options may be used to limit the response to a
specific range subset. This can be used, for instance, to support HTTP Range
requests.</p>
<p>The file descriptor or <code>FileHandle</code> is not closed when the stream is closed,
so it will need to be closed manually once it is no longer needed.
Using the same file descriptor concurrently for multiple streams
is not supported and may result in data loss. Re-using a file descriptor
after a stream has finished is supported.</p>
<p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event
will be emitted immediately after queuing the last chunk of payload data to be
sent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing
header fields to the peer.</p>
<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically
close when the final <code>DATA</code> frame is transmitted. User code <em>must</em> call either
<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the
<code>Http2Stream</code>.</p>
<pre><code class="language-js">const http2 = require('http2');
const fs = require('fs');

const server = http2.createServer();
server.on('stream', (stream) => {
  const fd = fs.openSync('/some/file', 'r');

  const stat = fs.fstatSync(fd);
  const headers = {
    'content-length': stat.size,
    'last-modified': stat.mtime.toUTCString(),
    'content-type': 'text/plain'
  };
  stream.respondWithFD(fd, headers, { waitForTrailers: true });
  stream.on('wantTrailers', () => {
    stream.sendTrailers({ ABC: 'some value to send' });
  });

  stream.on('close', () => fs.closeSync(fd));
});
</code></pre>
<h4><code>http2stream.respondWithFile(path[, headers[, options]])</code><span><a class="mark" href="#http2_http2stream_respondwithfile_path_headers_options" id="http2_http2stream_respondwithfile_path_headers_options">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Any readable file, not necessarily a regular file, is supported now.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>headers</code> <a href="#http2_headers_object" class="type">&#x3C;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">&#x3C;Object></a></p>
<ul>
<li><code>statCheck</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li><code>onError</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Callback function invoked in the case of an
error before send.</li>
<li><code>waitForTrailers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, the <code>Http2Stream</code> will emit the
<code>'wantTrailers'</code> event after the final <code>DATA</code> frame has been sent.</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;number></a> The amount of data from the fd to send.</li>
</ul>
</li>
</ul>
<p>Sends a regular file as the response. The <code>path</code> must specify a regular file
or an <code>'error'</code> event will be emitted on the <code>Http2Stream</code> object.</p>
<p>When used, the <code>Http2Stream</code> object's <code>Duplex</code> interface will be closed
automatically.</p>
<p>The optional <code>options.statCheck</code> function may be specified to give user code
an opportunity to set additional content headers based on the <code>fs.Stat</code> details
of the given file:</p>
<p>If an error occurs while attempting to read the file data, the <code>Http2Stream</code>
will be closed using an <code>RST_STREAM</code> frame using the standard <code>INTERNAL_ERROR</code>
code. If the <code>onError</code> callback is defined, then it will be called. Otherwise
the stream will be destroyed.</p>
<p>Example using a file path:</p>
<pre><code class="language-js">const http2 = require('http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  function statCheck(stat, headers) {
    headers['last-modified'] = stat.mtime.toUTCString();
  }

  function onError(err) {
    if (err.code === 'ENOENT') {
      stream.respond({ ':status': 404 });
    } else {
      stream.respond({ ':status': 500 });
    }
    stream.end();
  }

  stream.respondWithFile('/some/file',
                         { 'content-type': 'text/plain' },
                         { statCheck, onError });
});
</code></pre>
<p>The <code>options.statCheck</code> function may also be used to cancel the send operation
by returning <code>false</code>. For instance, a conditional request may check the stat
results to determine if the file has been modified to return an appropriate
<code>304</code> response:</p>
<pre><code class="language-js">const http2 = require('http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  function statCheck(stat, headers) {
    // Check the stat here...
    stream.respond({ ':status': 304 });
    return false; // Cancel the send operation
  }
  stream.respondWithFile('/some/file',
                         { 'content-type': 'text/plain' },
                         { statCheck });
});
</code></pre>
<p>The <code>content-length</code> header field will be automatically set.</p>
<p>The <code>offset</code> and <code>length</code> options may be used to limit the response to a
specific range subset. This can be used, for instance, to support HTTP Range
requests.</p>
<p>The <code>options.onError</code> function may also be used to handle all the errors
that could happen before the delivery of the file is initiated. The
default behavior is to destroy the stream.</p>
<p>When the <code>options.waitForTrailers</code> option is set, the <code>'wantTrailers'</code> event
will be emitted immediately after queuing the last chunk of payload data to be
sent. The <code>http2stream.sendTrailers()</code> method can then be used to sent trailing
header fields to the peer.</p>
<p>When <code>options.waitForTrailers</code> is set, the <code>Http2Stream</code> will not automatically
close when the final <code>DATA</code> frame is transmitted. User code must call either
<code>http2stream.sendTrailers()</code> or <code>http2stream.close()</code> to close the
<code>Http2Stream</code>.</p>
<pre><code class="language-js">const http2 = require('http2');
const server = http2.createServer();
server.on('stream', (stream) => {
  stream.respondWithFile('/some/file',
                         { 'content-type': 'text/plain' },
                         { waitForTrailers: true });
  stream.on('wantTrailers', () => {
    stream.sendTrailers({ ABC: 'some value to send' });
  });
});
</code></pre>
<h3>Class: <code>Http2Server</code><span><a class="mark" href="#http2_class_http2server" id="http2_class_http2server">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#net_class_net_server" class="type">&#x3C;net.Server></a></li>
</ul>
<p>Instances of <code>Http2Server</code> are created using the <code>http2.createServer()</code>
function. The <code>Http2Server</code> class is not exported directly by the <code>http2</code>
module.</p>
<h4>Event: <code>'checkContinue'</code><span><a class="mark" href="#http2_event_checkcontinue" id="http2_event_checkcontinue">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>request</code> <a href="#http2_class_http2_http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#http2_class_http2_http2serverresponse" class="type">&#x3C;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>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: <code>'request'</code><span><a class="mark" href="#http2_event_request" id="http2_event_request">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>request</code> <a href="#http2_class_http2_http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#http2_class_http2_http2serverresponse" class="type">&#x3C;http2.Http2ServerResponse></a></li>
</ul>
<p>Emitted each time there is a request. There may be multiple requests
per session. See the <a href="#http2_compatibility_api">Compatibility API</a>.</p>
<h4>Event: <code>'session'</code><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: <code>'sessionError'</code><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: <code>'stream'</code><span><a class="mark" href="#http2_event_stream_1" id="http2_event_stream_1">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'stream'</code> event is emitted when a <code>'stream'</code> event has been emitted by
an <code>Http2Session</code> associated with the server.</p>
<pre><code class="language-js">const http2 = require('http2');
const {
  HTTP2_HEADER_METHOD,
  HTTP2_HEADER_PATH,
  HTTP2_HEADER_STATUS,
  HTTP2_HEADER_CONTENT_TYPE
} = http2.constants;

const server = http2.createServer();
server.on('stream', (stream, headers, flags) => {
  const method = headers[HTTP2_HEADER_METHOD];
  const path = headers[HTTP2_HEADER_PATH];
  // ...
  stream.respond({
    [HTTP2_HEADER_STATUS]: 200,
    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain'
  });
  stream.write('hello ');
  stream.end('world');
});
</code></pre>
<h4>Event: <code>'timeout'</code><span><a class="mark" href="#http2_event_timeout_2" id="http2_event_timeout_2">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for
a given number of milliseconds set using <code>http2server.setTimeout()</code>.
<strong>Default:</strong> 2 minutes.</p>
<p>To change the default timeout use the <a href="#cli_http_server_default_timeout_milliseconds"><code>--http-server-default-timeout</code></a>
flag.</p>
<h4><code>server.close([callback])</code><span><a class="mark" href="#http2_server_close_callback" id="http2_server_close_callback">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Stops the server from establishing new sessions. This does not prevent new
request streams from being created due to the persistent nature of HTTP/2
sessions. To gracefully shut down the server, call <a href="#http2_http2session_close_callback"><code>http2session.close()</code></a> on
all active sessions.</p>
<p>If <code>callback</code> is provided, it is not invoked until all active sessions have been
closed, although the server has already stopped allowing new sessions. See
<a href="#net_server_close_callback"><code>net.Server.close()</code></a> for more details.</p>
<h4><code>server.setTimeout([msecs][, callback])</code><span><a class="mark" href="#http2_server_settimeout_msecs_callback" id="http2_server_settimeout_msecs_callback">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#http2_class_http2server" class="type">&#x3C;Http2Server></a></li>
</ul>
<p>Used to set the timeout value for http2 server requests,
and sets a callback function that is called when there is no activity
on the <code>Http2Server</code> after <code>msecs</code> milliseconds.</p>
<p>The given callback is registered as a listener on the <code>'timeout'</code> event.</p>
<p>In case of no callback function were assigned, a new <code>ERR_INVALID_CALLBACK</code>
error will be thrown.</p>
<p>To change the default timeout use the <a href="#cli_http_server_default_timeout_milliseconds"><code>--http-server-default-timeout</code></a>
flag.</p>
<h3>Class: <code>Http2SecureServer</code><span><a class="mark" href="#http2_class_http2secureserver" id="http2_class_http2secureserver">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#tls_class_tls_server" class="type">&#x3C;tls.Server></a></li>
</ul>
<p>Instances of <code>Http2SecureServer</code> are created using the
<code>http2.createSecureServer()</code> function. The <code>Http2SecureServer</code> class is not
exported directly by the <code>http2</code> module.</p>
<h4>Event: <code>'checkContinue'</code><span><a class="mark" href="#http2_event_checkcontinue_1" id="http2_event_checkcontinue_1">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>request</code> <a href="#http2_class_http2_http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#http2_class_http2_http2serverresponse" class="type">&#x3C;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>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: <code>'request'</code><span><a class="mark" href="#http2_event_request_1" id="http2_event_request_1">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>request</code> <a href="#http2_class_http2_http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#http2_class_http2_http2serverresponse" class="type">&#x3C;http2.Http2ServerResponse></a></li>
</ul>
<p>Emitted each time there is a request. There may be multiple requests
per session. See the <a href="#http2_compatibility_api">Compatibility API</a>.</p>
<h4>Event: <code>'session'</code><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: <code>'sessionError'</code><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: <code>'stream'</code><span><a class="mark" href="#http2_event_stream_2" id="http2_event_stream_2">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'stream'</code> event is emitted when a <code>'stream'</code> event has been emitted by
an <code>Http2Session</code> associated with the server.</p>
<pre><code class="language-js">const http2 = require('http2');
const {
  HTTP2_HEADER_METHOD,
  HTTP2_HEADER_PATH,
  HTTP2_HEADER_STATUS,
  HTTP2_HEADER_CONTENT_TYPE
} = http2.constants;

const options = getOptionsSomehow();

const server = http2.createSecureServer(options);
server.on('stream', (stream, headers, flags) => {
  const method = headers[HTTP2_HEADER_METHOD];
  const path = headers[HTTP2_HEADER_PATH];
  // ...
  stream.respond({
    [HTTP2_HEADER_STATUS]: 200,
    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain'
  });
  stream.write('hello ');
  stream.end('world');
});
</code></pre>
<h4>Event: <code>'timeout'</code><span><a class="mark" href="#http2_event_timeout_3" id="http2_event_timeout_3">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for
a given number of milliseconds set using <code>http2secureServer.setTimeout()</code>.
<strong>Default:</strong> 2 minutes.</p>
<h4>Event: <code>'unknownProtocol'</code><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>
<h4><code>server.close([callback])</code><span><a class="mark" href="#http2_server_close_callback_1" id="http2_server_close_callback_1">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Stops the server from establishing new sessions. This does not prevent new
request streams from being created due to the persistent nature of HTTP/2
sessions. To gracefully shut down the server, call <a href="#http2_http2session_close_callback"><code>http2session.close()</code></a> on
all active sessions.</p>
<p>If <code>callback</code> is provided, it is not invoked until all active sessions have been
closed, although the server has already stopped allowing new sessions. See
<a href="#tls_server_close_callback"><code>tls.Server.close()</code></a> for more details.</p>
<h4><code>server.setTimeout([msecs][, callback])</code><span><a class="mark" href="#http2_server_settimeout_msecs_callback_1" id="http2_server_settimeout_msecs_callback_1">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>msecs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#http2_class_http2secureserver" class="type">&#x3C;Http2SecureServer></a></li>
</ul>
<p>Used to set the timeout value for http2 secure server requests,
and sets a callback function that is called when there is no activity
on the <code>Http2SecureServer</code> after <code>msecs</code> milliseconds.</p>
<p>The given callback is registered as a listener on the <code>'timeout'</code> event.</p>
<p>In case of no callback function were assigned, a new <code>ERR_INVALID_CALLBACK</code>
error will be thrown.</p>
<h3><code>http2.createServer(options[, onRequestHandler])</code><span><a class="mark" href="#http2_http2_createserver_options_onrequesthandler" id="http2_http2_createserver_options_onrequesthandler">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.18.0</td>
<td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr>
<tr><td>v12.16.0</td>
<td><p>Added <code>maxSessionRejectedStreams</code> option with a default of 100.</p></td></tr>
<tr><td>v12.16.0</td>
<td><p>Added <code>maxSessionInvalidFrames</code> option with a default of 1000.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p>The <code>options</code> parameter now supports <code>net.createServer()</code> options.</p></td></tr>
<tr><td>v9.6.0</td>
<td><p>Added the <code>Http1IncomingMessage</code> and <code>Http1ServerResponse</code> option.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum dynamic table size
for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li>
<li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of settings entries per
<code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li>
<li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum memory that the <code>Http2Session</code>
is permitted to use. The value is expressed in terms of number of megabytes,
e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>.
This is a credit based limit, existing <code>Http2Stream</code>s may cause this
limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected
while this limit is exceeded. The current number of <code>Http2Stream</code> sessions,
the current memory use of the header compression tables, current data
queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all
counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of header entries.
This is similar to <a href="#http_server_maxheaderscount"><code>http.Server#maxHeadersCount</code></a> or
<a href="#http_request_maxheaderscount"><code>http.ClientRequest#maxHeadersCount</code></a>. The minimum value is <code>4</code>.
<strong>Default:</strong> <code>128</code>.</li>
<li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of outstanding,
unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum allowed size for a
serialized, compressed block of headers. Attempts to send headers that
exceed this limit will result in a <code>'frameError'</code> event being emitted
and the stream being closed and destroyed.</li>
<li>
<p><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The strategy used for determining the amount of
padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong>
<code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:</p>
<ul>
<li><code>http2.constants.PADDING_STRATEGY_NONE</code>: Specifies that no padding is
to be applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_MAX</code>: Specifies that the maximum
amount of padding, as determined by the internal implementation, is to
be applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_CALLBACK</code>: Specifies that the user
provided <code>options.selectPadding()</code> callback is to be used to determine
the amount of padding.</li>
<li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code>: Will <em>attempt</em> to apply
enough padding to ensure that the total frame length, including the
9-byte header, is a multiple of 8. For each frame, however, there is a
maximum allowed number of padding bytes that is determined by current
flow control state and settings. If this maximum is less than the
calculated amount needed to ensure alignment, the maximum will be used
and the total frame length will <em>not</em> necessarily be aligned at 8 bytes.</li>
</ul>
</li>
<li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of concurrent
streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will
be overridden if the remote peer sets its own value for
<code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li>
<li><code>maxSessionInvalidFrames</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Sets the maximum number of invalid
frames that will be tolerated before the session is closed.
<strong>Default:</strong> <code>1000</code>.</li>
<li><code>maxSessionRejectedStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Sets the maximum number of rejected
upon creation streams that will be tolerated before the session is closed.
Each rejection is associated with an <code>NGHTTP2_ENHANCE_YOUR_CALM</code>
error that should tell the peer to not open any more streams, continuing
to open streams is therefore regarded as a sign of a misbehaving peer.
<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">&#x3C;Function></a> When <code>options.paddingStrategy</code> is equal to
<code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, provides the callback function
used to determine the padding. See <a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a>.</li>
<li><code>settings</code> <a href="#http2_settings_object" class="type">&#x3C;HTTP/2 Settings Object></a> The initial settings to send to the
remote peer upon connection.</li>
<li><code>Http1IncomingMessage</code> <a href="#http_class_http_incomingmessage" class="type">&#x3C;http.IncomingMessage></a> Specifies the
<code>IncomingMessage</code> class to used for HTTP/1 fallback. Useful for extending
the original <code>http.IncomingMessage</code>. <strong>Default:</strong> <code>http.IncomingMessage</code>.</li>
<li><code>Http1ServerResponse</code> <a href="#http_class_http_serverresponse" class="type">&#x3C;http.ServerResponse></a> Specifies the <code>ServerResponse</code>
class to used for HTTP/1 fallback. Useful for extending the original
<code>http.ServerResponse</code>. <strong>Default:</strong> <code>http.ServerResponse</code>.</li>
<li><code>Http2ServerRequest</code> <a href="#http2_class_http2_http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a> Specifies the
<code>Http2ServerRequest</code> class to use.
Useful for extending the original <code>Http2ServerRequest</code>.
<strong>Default:</strong> <code>Http2ServerRequest</code>.</li>
<li><code>Http2ServerResponse</code> <a href="#http2_class_http2_http2serverresponse" class="type">&#x3C;http2.Http2ServerResponse></a> Specifies the
<code>Http2ServerResponse</code> class to use.
Useful for extending the original <code>Http2ServerResponse</code>.
<strong>Default:</strong> <code>Http2ServerResponse</code>.</li>
<li>...: Any <a href="#net_net_createserver_options_connectionlistener"><code>net.createServer()</code></a> option can be provided.</li>
</ul>
</li>
<li><code>onRequestHandler</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> See <a href="#http2_compatibility_api">Compatibility API</a></li>
<li>Returns: <a href="#http2_class_http2server" class="type">&#x3C;Http2Server></a></li>
</ul>
<p>Returns a <code>net.Server</code> instance that creates and manages <code>Http2Session</code>
instances.</p>
<p>Since there are no browsers known that support
<a href="https://http2.github.io/faq/#does-http2-require-encryption">unencrypted HTTP/2</a>, the use of
<a href="#http2_http2_createsecureserver_options_onrequesthandler"><code>http2.createSecureServer()</code></a> is necessary when communicating
with browser clients.</p>
<pre><code class="language-js">const http2 = require('http2');

// Create an unencrypted HTTP/2 server.
// Since there are no browsers known that support
// unencrypted HTTP/2, the use of `http2.createSecureServer()`
// is necessary when communicating with browser clients.
const server = http2.createServer();

server.on('stream', (stream, headers) => {
  stream.respond({
    'content-type': 'text/html',
    ':status': 200
  });
  stream.end('&#x3C;h1>Hello World&#x3C;/h1>');
});

server.listen(80);
</code></pre>
<h3><code>http2.createSecureServer(options[, onRequestHandler])</code><span><a class="mark" href="#http2_http2_createsecureserver_options_onrequesthandler" id="http2_http2_createsecureserver_options_onrequesthandler">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.18.0</td>
<td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr>
<tr><td>v12.16.0</td>
<td><p>Added <code>maxSessionRejectedStreams</code> option with a default of 100.</p></td></tr>
<tr><td>v12.16.0</td>
<td><p>Added <code>maxSessionInvalidFrames</code> option with a default of 1000.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p>Added the <code>origins</code> option to automatically send an <code>ORIGIN</code> frame on <code>Http2Session</code> startup.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>allowHTTP1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Incoming client connections that do not support
HTTP/2 will be downgraded to HTTP/1.x when set to <code>true</code>.
See the <a href="#http2_event_unknownprotocol"><code>'unknownProtocol'</code></a> event. See <a href="#http2_alpn_negotiation">ALPN negotiation</a>.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum dynamic table size
for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li>
<li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of settings entries per
<code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li>
<li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum memory that the <code>Http2Session</code>
is permitted to use. The value is expressed in terms of number of megabytes,
e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>. This is a
credit based limit, existing <code>Http2Stream</code>s may cause this
limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected
while this limit is exceeded. The current number of <code>Http2Stream</code> sessions,
the current memory use of the header compression tables, current data
queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all
counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of header entries.
This is similar to <a href="#http_server_maxheaderscount"><code>http.Server#maxHeadersCount</code></a> or
<a href="#http_request_maxheaderscount"><code>http.ClientRequest#maxHeadersCount</code></a>. The minimum value is <code>4</code>.
<strong>Default:</strong> <code>128</code>.</li>
<li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of outstanding,
unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum allowed size for a
serialized, compressed block of headers. Attempts to send headers that
exceed this limit will result in a <code>'frameError'</code> event being emitted
and the stream being closed and destroyed.</li>
<li>
<p><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Strategy used for determining the amount of
padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong>
<code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:</p>
<ul>
<li><code>http2.constants.PADDING_STRATEGY_NONE</code>: Specifies that no padding is
to be applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_MAX</code>: Specifies that the maximum
amount of padding, as determined by the internal implementation, is to
be applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_CALLBACK</code>: Specifies that the user
provided <code>options.selectPadding()</code> callback is to be used to determine
the amount of padding.</li>
<li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code>: Will <em>attempt</em> to apply
enough padding to ensure that the total frame length, including the
9-byte header, is a multiple of 8. For each frame, however, there is a
maximum allowed number of padding bytes that is determined by current
flow control state and settings. If this maximum is less than the
calculated amount needed to ensure alignment, the maximum will be used
and the total frame length will <em>not</em> necessarily be aligned at 8 bytes.</li>
</ul>
</li>
<li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of concurrent
streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will
be overridden if the remote peer sets its own value for
<code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li>
<li><code>maxSessionInvalidFrames</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Sets the maximum number of invalid
frames that will be tolerated before the session is closed.
<strong>Default:</strong> <code>1000</code>.</li>
<li><code>maxSessionRejectedStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Sets the maximum number of rejected
upon creation streams that will be tolerated before the session is closed.
Each rejection is associated with an <code>NGHTTP2_ENHANCE_YOUR_CALM</code>
error that should tell the peer to not open any more streams, continuing
to open streams is therefore regarded as a sign of a misbehaving peer.
<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">&#x3C;Function></a> When <code>options.paddingStrategy</code> is equal to
<code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, provides the callback function
used to determine the padding. See <a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a>.</li>
<li><code>settings</code> <a href="#http2_settings_object" class="type">&#x3C;HTTP/2 Settings Object></a> The initial settings to send to the
remote peer upon connection.</li>
<li>...: Any <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a> options can be provided. For
servers, the identity options (<code>pfx</code> or <code>key</code>/<code>cert</code>) are usually required.</li>
<li><code>origins</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> An array of origin strings to send within an <code>ORIGIN</code>
frame immediately following creation of a new server <code>Http2Session</code>.</li>
</ul>
</li>
<li><code>onRequestHandler</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> See <a href="#http2_compatibility_api">Compatibility API</a></li>
<li>Returns: <a href="#http2_class_http2secureserver" class="type">&#x3C;Http2SecureServer></a></li>
</ul>
<p>Returns a <code>tls.Server</code> instance that creates and manages <code>Http2Session</code>
instances.</p>
<pre><code class="language-js">const http2 = require('http2');
const fs = require('fs');

const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem')
};

// Create a secure HTTP/2 server
const server = http2.createSecureServer(options);

server.on('stream', (stream, headers) => {
  stream.respond({
    'content-type': 'text/html',
    ':status': 200
  });
  stream.end('&#x3C;h1>Hello World&#x3C;/h1>');
});

server.listen(80);
</code></pre>
<h3><code>http2.connect(authority[, options][, listener])</code><span><a class="mark" href="#http2_http2_connect_authority_options_listener" id="http2_http2_connect_authority_options_listener">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.18.0</td>
<td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>authority</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> The remote HTTP/2 server to connect to. This must
be in the form of a minimal, valid URL with the <code>http://</code> or <code>https://</code>
prefix, host name, and IP port (if a non-default port is used). Userinfo
(user ID and password), path, querystring, and fragment details in the
URL will be ignored.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>maxDeflateDynamicTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum dynamic table size
for deflating header fields. <strong>Default:</strong> <code>4Kib</code>.</li>
<li><code>maxSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of settings entries per
<code>SETTINGS</code> frame. The minimum value allowed is <code>1</code>. <strong>Default:</strong> <code>32</code>.</li>
<li><code>maxSessionMemory</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum memory that the <code>Http2Session</code>
is permitted to use. The value is expressed in terms of number of megabytes,
e.g. <code>1</code> equal 1 megabyte. The minimum value allowed is <code>1</code>.
This is a credit based limit, existing <code>Http2Stream</code>s may cause this
limit to be exceeded, but new <code>Http2Stream</code> instances will be rejected
while this limit is exceeded. The current number of <code>Http2Stream</code> sessions,
the current memory use of the header compression tables, current data
queued to be sent, and unacknowledged <code>PING</code> and <code>SETTINGS</code> frames are all
counted towards the current limit. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxHeaderListPairs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of header entries.
This is similar to <a href="#http_server_maxheaderscount"><code>http.Server#maxHeadersCount</code></a> or
<a href="#http_request_maxheaderscount"><code>http.ClientRequest#maxHeadersCount</code></a>. The minimum value is <code>1</code>.
<strong>Default:</strong> <code>128</code>.</li>
<li><code>maxOutstandingPings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of outstanding,
unacknowledged pings. <strong>Default:</strong> <code>10</code>.</li>
<li><code>maxReservedRemoteStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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. The minimum allowed value
is 0. The maximum allowed value is 2<sup>32</sup>-1. A negative value sets
this option to the maximum allowed value. <strong>Default:</strong> <code>200</code>.</li>
<li><code>maxSendHeaderBlockLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum allowed size for a
serialized, compressed block of headers. Attempts to send headers that
exceed this limit will result in a <code>'frameError'</code> event being emitted
and the stream being closed and destroyed.</li>
<li>
<p><code>paddingStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Strategy used for determining the amount of
padding to use for <code>HEADERS</code> and <code>DATA</code> frames. <strong>Default:</strong>
<code>http2.constants.PADDING_STRATEGY_NONE</code>. Value may be one of:</p>
<ul>
<li><code>http2.constants.PADDING_STRATEGY_NONE</code>: Specifies that no padding is
to be applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_MAX</code>: Specifies that the maximum
amount of padding, as determined by the internal implementation, is to
be applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_CALLBACK</code>: Specifies that the user
provided <code>options.selectPadding()</code> callback is to be used to determine
the amount of padding.</li>
<li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code>: Will <em>attempt</em> to apply
enough padding to ensure that the total frame length, including the
9-byte header, is a multiple of 8. For each frame, however, there is a
maximum allowed number of padding bytes that is determined by current
flow control state and settings. If this maximum is less than the
calculated amount needed to ensure alignment, the maximum will be used
and the total frame length will <em>not</em> necessarily be aligned at 8 bytes.</li>
</ul>
</li>
<li><code>peerMaxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Sets the maximum number of concurrent
streams for the remote peer as if a <code>SETTINGS</code> frame had been received. Will
be overridden if the remote peer sets its own value for
<code>maxConcurrentStreams</code>. <strong>Default:</strong> <code>100</code>.</li>
<li><code>selectPadding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> When <code>options.paddingStrategy</code> is equal to
<code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, provides the callback function
used to determine the padding. See <a href="#http2_using_options_selectpadding">Using <code>options.selectPadding()</code></a>.</li>
<li><code>protocol</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The protocol to connect with, if not set in the
<code>authority</code>. Value may be either <code>'http:'</code> or <code>'https:'</code>. <strong>Default:</strong>
<code>'https:'</code></li>
<li><code>settings</code> <a href="#http2_settings_object" class="type">&#x3C;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">&#x3C;Function></a> An optional callback that receives the <code>URL</code>
instance passed to <code>connect</code> and the <code>options</code> object, and returns any
<a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream that is to be used as the connection for this session.</li>
<li>...: Any <a href="#net_net_connect"><code>net.connect()</code></a> or <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> options can be provided.</li>
</ul>
</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Will be registered as a one-time listener of the
<a href="#http2_event_connect"><code>'connect'</code></a> event.</li>
<li>Returns: <a href="#http2_class_clienthttp2session" class="type">&#x3C;ClientHttp2Session></a></li>
</ul>
<p>Returns a <code>ClientHttp2Session</code> instance.</p>
<pre><code class="language-js">const http2 = require('http2');
const client = http2.connect('https://localhost:1234');

/* Use the client */

client.close();
</code></pre>
<h3><code>http2.constants</code><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 <code>RST_STREAM</code> and <code>GOAWAY</code><span><a class="mark" href="#http2_error_codes_for_rst_stream_and_goaway" id="http2_error_codes_for_rst_stream_and_goaway">#</a></span></h4>
<p><a id="error_codes"></a></p>
















































































<table><thead><tr><th>Value</th><th>Name</th><th>Constant</th></tr></thead><tbody><tr><td><code>0x00</code></td><td>No Error</td><td><code>http2.constants.NGHTTP2_NO_ERROR</code></td></tr><tr><td><code>0x01</code></td><td>Protocol Error</td><td><code>http2.constants.NGHTTP2_PROTOCOL_ERROR</code></td></tr><tr><td><code>0x02</code></td><td>Internal Error</td><td><code>http2.constants.NGHTTP2_INTERNAL_ERROR</code></td></tr><tr><td><code>0x03</code></td><td>Flow Control Error</td><td><code>http2.constants.NGHTTP2_FLOW_CONTROL_ERROR</code></td></tr><tr><td><code>0x04</code></td><td>Settings Timeout</td><td><code>http2.constants.NGHTTP2_SETTINGS_TIMEOUT</code></td></tr><tr><td><code>0x05</code></td><td>Stream Closed</td><td><code>http2.constants.NGHTTP2_STREAM_CLOSED</code></td></tr><tr><td><code>0x06</code></td><td>Frame Size Error</td><td><code>http2.constants.NGHTTP2_FRAME_SIZE_ERROR</code></td></tr><tr><td><code>0x07</code></td><td>Refused Stream</td><td><code>http2.constants.NGHTTP2_REFUSED_STREAM</code></td></tr><tr><td><code>0x08</code></td><td>Cancel</td><td><code>http2.constants.NGHTTP2_CANCEL</code></td></tr><tr><td><code>0x09</code></td><td>Compression Error</td><td><code>http2.constants.NGHTTP2_COMPRESSION_ERROR</code></td></tr><tr><td><code>0x0a</code></td><td>Connect Error</td><td><code>http2.constants.NGHTTP2_CONNECT_ERROR</code></td></tr><tr><td><code>0x0b</code></td><td>Enhance Your Calm</td><td><code>http2.constants.NGHTTP2_ENHANCE_YOUR_CALM</code></td></tr><tr><td><code>0x0c</code></td><td>Inadequate Security</td><td><code>http2.constants.NGHTTP2_INADEQUATE_SECURITY</code></td></tr><tr><td><code>0x0d</code></td><td>HTTP/1.1 Required</td><td><code>http2.constants.NGHTTP2_HTTP_1_1_REQUIRED</code></td></tr></tbody></table>
<p>The <code>'timeout'</code> event is emitted when there is no activity on the Server for
a given number of milliseconds set using <code>http2server.setTimeout()</code>.</p>
<h3><code>http2.getDefaultSettings()</code><span><a class="mark" href="#http2_http2_getdefaultsettings" id="http2_http2_getdefaultsettings">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Returns: <a href="#http2_settings_object" class="type">&#x3C;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><code>http2.getPackedSettings([settings])</code><span><a class="mark" href="#http2_http2_getpackedsettings_settings" id="http2_http2_getpackedsettings_settings">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#http2_settings_object" class="type">&#x3C;HTTP/2 Settings Object></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Returns a <code>Buffer</code> instance containing serialized representation of the given
HTTP/2 settings as specified in the <a href="https://tools.ietf.org/html/rfc7540">HTTP/2</a> specification. This is intended
for use with the <code>HTTP2-Settings</code> header field.</p>
<pre><code class="language-js">const http2 = require('http2');

const packed = http2.getPackedSettings({ enablePush: false });

console.log(packed.toString('base64'));
// Prints: AAIAAAAA
</code></pre>
<h3><code>http2.getUnpackedSettings(buf)</code><span><a class="mark" href="#http2_http2_getunpackedsettings_buf" id="http2_http2_getunpackedsettings_buf">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>buf</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> The packed settings.</li>
<li>Returns: <a href="#http2_settings_object" class="type">&#x3C;HTTP/2 Settings Object></a></li>
</ul>
<p>Returns a <a href="#http2_settings_object">HTTP/2 Settings Object</a> containing the deserialized settings from
the given <code>Buffer</code> as generated by <code>http2.getPackedSettings()</code>.</p>
<h3>Headers object<span><a class="mark" href="#http2_headers_object" id="http2_headers_object">#</a></span></h3>
<p>Headers are represented as own-properties on JavaScript objects. The property
keys will be serialized to lower-case. Property values should be strings (if
they are not they will be coerced to strings) or an <code>Array</code> of strings (in order
to send more than one value per header field).</p>
<pre><code class="language-js">const headers = {
  ':status': '200',
  'content-type': 'text-plain',
  'ABC': ['has', 'more', 'than', 'one', 'value']
};

stream.respond(headers);
</code></pre>
<p>Header objects passed to callback functions will have a <code>null</code> prototype. This
means that normal JavaScript object methods such as
<code>Object.prototype.toString()</code> and <code>Object.prototype.hasOwnProperty()</code> will
not work.</p>
<p>For incoming headers:</p>
<ul>
<li>The <code>:status</code> header is converted to <code>number</code>.</li>
<li>Duplicates of <code>:status</code>, <code>:method</code>, <code>:authority</code>, <code>:scheme</code>, <code>:path</code>,
<code>:protocol</code>, <code>age</code>, <code>authorization</code>, <code>access-control-allow-credentials</code>,
<code>access-control-max-age</code>, <code>access-control-request-method</code>, <code>content-encoding</code>,
<code>content-language</code>, <code>content-length</code>, <code>content-location</code>, <code>content-md5</code>,
<code>content-range</code>, <code>content-type</code>, <code>date</code>, <code>dnt</code>, <code>etag</code>, <code>expires</code>, <code>from</code>,
<code>if-match</code>, <code>if-modified-since</code>, <code>if-none-match</code>, <code>if-range</code>,
<code>if-unmodified-since</code>, <code>last-modified</code>, <code>location</code>, <code>max-forwards</code>,
<code>proxy-authorization</code>, <code>range</code>, <code>referer</code>,<code>retry-after</code>, <code>tk</code>,
<code>upgrade-insecure-requests</code>, <code>user-agent</code> or <code>x-content-type-options</code> are
discarded.</li>
<li><code>set-cookie</code> is always an array. Duplicates are added to the array.</li>
<li>For duplicate <code>cookie</code> headers, the values are joined together with '; '.</li>
<li>For all other headers, the values are joined together with ', '.</li>
</ul>
<pre><code class="language-js">const http2 = require('http2');
const server = http2.createServer();
server.on('stream', (stream, headers) => {
  console.log(headers[':path']);
  console.log(headers.ABC);
});
</code></pre>
<h3>Settings object<span><a class="mark" href="#http2_settings_object" id="http2_settings_object">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.12.0</td>
<td><p>The <code>maxConcurrentStreams</code> setting is stricter.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>The <code>maxHeaderListSize</code> setting is now strictly enforced.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>http2.getDefaultSettings()</code>, <code>http2.getPackedSettings()</code>,
<code>http2.createServer()</code>, <code>http2.createSecureServer()</code>,
<code>http2session.settings()</code>, <code>http2session.localSettings</code>, and
<code>http2session.remoteSettings</code> APIs either return or receive as input an
object that defines configuration settings for an <code>Http2Session</code> object.
These objects are ordinary JavaScript objects containing the following
properties.</p>
<ul>
<li><code>headerTableSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the maximum number of bytes used for
header compression. The minimum allowed value is 0. The maximum allowed value
is 2<sup>32</sup>-1. <strong>Default:</strong> <code>4096</code>.</li>
<li><code>enablePush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Specifies <code>true</code> if HTTP/2 Push Streams are to be
permitted on the <code>Http2Session</code> instances. <strong>Default:</strong> <code>true</code>.</li>
<li><code>initialWindowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the <em>sender's</em> initial window size in
bytes for stream-level flow control. The minimum allowed value is 0. The
maximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>65535</code>.</li>
<li><code>maxFrameSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the size in bytes of the largest frame
payload. The minimum allowed value is 16,384. The maximum allowed value is
2<sup>24</sup>-1. <strong>Default:</strong> <code>16384</code>.</li>
<li><code>maxConcurrentStreams</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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>32</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>32</sup>-1. <strong>Default:</strong>
<code>4294967295</code>.</li>
<li><code>maxHeaderListSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the maximum size (uncompressed octets)
of header list that will be accepted. The minimum allowed value is 0. The
maximum allowed value is 2<sup>32</sup>-1. <strong>Default:</strong> <code>65535</code>.</li>
<li><code>enableConnectProtocol</code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Specifies <code>true</code> if the "Extended Connect
Protocol" defined by <a href="https://tools.ietf.org/html/rfc8441">RFC 8441</a> is to be enabled. This setting is only
meaningful if sent by the server. Once the <code>enableConnectProtocol</code> setting
has been enabled for a given <code>Http2Session</code>, it cannot be disabled.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
<p>All additional properties on the settings object are ignored.</p>
<h3>Using <code>options.selectPadding()</code><span><a class="mark" href="#http2_using_options_selectpadding" id="http2_using_options_selectpadding">#</a></span></h3>
<p>When <code>options.paddingStrategy</code> is equal to
<code>http2.constants.PADDING_STRATEGY_CALLBACK</code>, the HTTP/2 implementation will
consult the <code>options.selectPadding()</code> callback function, if provided, to
determine the specific amount of padding to use per <code>HEADERS</code> and <code>DATA</code> frame.</p>
<p>The <code>options.selectPadding()</code> function receives two numeric arguments,
<code>frameLen</code> and <code>maxFrameLen</code> and must return a number <code>N</code> such that
<code>frameLen &#x3C;= N &#x3C;= maxFrameLen</code>.</p>
<pre><code class="language-js">const http2 = require('http2');
const server = http2.createServer({
  paddingStrategy: http2.constants.PADDING_STRATEGY_CALLBACK,
  selectPadding(frameLen, maxFrameLen) {
    return maxFrameLen;
  }
});
</code></pre>
<p>The <code>options.selectPadding()</code> function is invoked once for <em>every</em> <code>HEADERS</code> and
<code>DATA</code> frame. This has a definite noticeable impact on performance.</p>
<h3>Error handling<span><a class="mark" href="#http2_error_handling" id="http2_error_handling">#</a></span></h3>
<p>There are several types of error conditions that may arise when using the
<code>http2</code> module:</p>
<p>Validation errors occur when an incorrect argument, option, or setting value is
passed in. These will always be reported by a synchronous <code>throw</code>.</p>
<p>State errors occur when an action is attempted at an incorrect time (for
instance, attempting to send data on a stream after it has closed). These will
be reported using either a synchronous <code>throw</code> or via an <code>'error'</code> event on
the <code>Http2Stream</code>, <code>Http2Session</code> or HTTP/2 Server objects, depending on where
and when the error occurs.</p>
<p>Internal errors occur when an HTTP/2 session fails unexpectedly. These will be
reported via an <code>'error'</code> event on the <code>Http2Session</code> or HTTP/2 Server objects.</p>
<p>Protocol errors occur when various HTTP/2 protocol constraints are violated.
These will be reported using either a synchronous <code>throw</code> or via an <code>'error'</code>
event on the <code>Http2Stream</code>, <code>Http2Session</code> or HTTP/2 Server objects, depending
on where and when the error occurs.</p>
<h3>Invalid character handling in header names and values<span><a class="mark" href="#http2_invalid_character_handling_in_header_names_and_values" id="http2_invalid_character_handling_in_header_names_and_values">#</a></span></h3>
<p>The HTTP/2 implementation applies stricter handling of invalid characters in
HTTP header names and values than the HTTP/1 implementation.</p>
<p>Header field names are <em>case-insensitive</em> and are transmitted over the wire
strictly as lower-case strings. The API provided by Node.js allows header
names to be set as mixed-case strings (e.g. <code>Content-Type</code>) but will convert
those to lower-case (e.g. <code>content-type</code>) upon transmission.</p>
<p>Header field-names <em>must only</em> contain one or more of the following ASCII
characters: <code>a</code>-<code>z</code>, <code>A</code>-<code>Z</code>, <code>0</code>-<code>9</code>, <code>!</code>, <code>#</code>, <code>$</code>, <code>%</code>, <code>&#x26;</code>, <code>'</code>, <code>*</code>, <code>+</code>,
<code>-</code>, <code>.</code>, <code>^</code>, <code>_</code>, <code>`</code> (backtick), <code>|</code>, and <code>~</code>.</p>
<p>Using invalid characters within an HTTP header field name will cause the
stream to be closed with a protocol error being reported.</p>
<p>Header field values are handled with more leniency but <em>should</em> not contain
new-line or carriage return characters and <em>should</em> be limited to US-ASCII
characters, per the requirements of the HTTP specification.</p>
<h3>Push streams on the client<span><a class="mark" href="#http2_push_streams_on_the_client" id="http2_push_streams_on_the_client">#</a></span></h3>
<p>To receive pushed streams on the client, set a listener for the <code>'stream'</code>
event on the <code>ClientHttp2Session</code>:</p>
<pre><code class="language-js">const http2 = require('http2');

const client = http2.connect('http://localhost');

client.on('stream', (pushedStream, requestHeaders) => {
  pushedStream.on('push', (responseHeaders) => {
    // Process response headers
  });
  pushedStream.on('data', (chunk) => { /* handle pushed data */ });
});

const req = client.request({ ':path': '/' });
</code></pre>
<h3>Supporting the <code>CONNECT</code> method<span><a class="mark" href="#http2_supporting_the_connect_method" id="http2_supporting_the_connect_method">#</a></span></h3>
<p>The <code>CONNECT</code> method is used to allow an HTTP/2 server to be used as a proxy
for TCP/IP connections.</p>
<p>A simple TCP Server:</p>
<pre><code class="language-js">const net = require('net');

const server = net.createServer((socket) => {
  let name = '';
  socket.setEncoding('utf8');
  socket.on('data', (chunk) => name += chunk);
  socket.on('end', () => socket.end(`hello ${name}`));
});

server.listen(8000);
</code></pre>
<p>An HTTP/2 CONNECT proxy:</p>
<pre><code class="language-js">const http2 = require('http2');
const { NGHTTP2_REFUSED_STREAM } = http2.constants;
const net = require('net');

const proxy = http2.createServer();
proxy.on('stream', (stream, headers) => {
  if (headers[':method'] !== 'CONNECT') {
    // Only accept CONNECT requests
    stream.close(NGHTTP2_REFUSED_STREAM);
    return;
  }
  const auth = new URL(`tcp://${headers[':authority']}`);
  // It's a very good idea to verify that hostname and port are
  // things this proxy should be connecting to.
  const socket = net.connect(auth.port, auth.hostname, () => {
    stream.respond();
    socket.pipe(stream);
    stream.pipe(socket);
  });
  socket.on('error', (error) => {
    stream.close(http2.constants.NGHTTP2_CONNECT_ERROR);
  });
});

proxy.listen(8001);
</code></pre>
<p>An HTTP/2 CONNECT client:</p>
<pre><code class="language-js">const http2 = require('http2');

const client = http2.connect('http://localhost:8001');

// Must not specify the ':path' and ':scheme' headers
// for CONNECT requests or an error will be thrown.
const req = client.request({
  ':method': 'CONNECT',
  ':authority': `localhost:${port}`
});

req.on('response', (headers) => {
  console.log(headers[http2.constants.HTTP2_HEADER_STATUS]);
});
let data = '';
req.setEncoding('utf8');
req.on('data', (chunk) => data += chunk);
req.on('end', () => {
  console.log(`The server says: ${data}`);
  client.close();
});
req.end('Jane');
</code></pre>
<h3>The extended <code>CONNECT</code> protocol<span><a class="mark" href="#http2_the_extended_connect_protocol" id="http2_the_extended_connect_protocol">#</a></span></h3>
<p><a href="https://tools.ietf.org/html/rfc8441">RFC 8441</a> defines an "Extended CONNECT Protocol" extension to HTTP/2 that
may be used to bootstrap the use of an <code>Http2Stream</code> using the <code>CONNECT</code>
method as a tunnel for other communication protocols (such as WebSockets).</p>
<p>The use of the Extended CONNECT Protocol is enabled by HTTP/2 servers by using
the <code>enableConnectProtocol</code> setting:</p>
<pre><code class="language-js">const http2 = require('http2');
const settings = { enableConnectProtocol: true };
const server = http2.createServer({ settings });
</code></pre>
<p>Once the client receives the <code>SETTINGS</code> frame from the server indicating that
the extended CONNECT may be used, it may send <code>CONNECT</code> requests that use the
<code>':protocol'</code> HTTP/2 pseudo-header:</p>
<pre><code class="language-js">const http2 = require('http2');
const client = http2.connect('http://localhost:8080');
client.on('remoteSettings', (settings) => {
  if (settings.enableConnectProtocol) {
    const req = client.request({ ':method': 'CONNECT', ':protocol': 'foo' });
    // ...
  }
});
</code></pre>
<h2>Compatibility API<span><a class="mark" href="#http2_compatibility_api" id="http2_compatibility_api">#</a></span></h2>
<p>The Compatibility API has the goal of providing a similar developer experience
of HTTP/1 when using HTTP/2, making it possible to develop applications
that support both <a href="http.html">HTTP/1</a> and HTTP/2. This API targets only the
<strong>public API</strong> of the <a href="http.html">HTTP/1</a>. However many modules use internal
methods or state, and those <em>are not supported</em> as it is a completely
different implementation.</p>
<p>The following example creates an HTTP/2 server using the compatibility
API:</p>
<pre><code class="language-js">const http2 = require('http2');
const server = http2.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ok');
});
</code></pre>
<p>In order to create a mixed <a href="https.html">HTTPS</a> and HTTP/2 server, refer to the
<a href="#http2_alpn_negotiation">ALPN negotiation</a> section.
Upgrading from non-tls HTTP/1 servers is not supported.</p>
<p>The HTTP/2 compatibility API is composed of <a href="#http2_class_http2_http2serverrequest"><code>Http2ServerRequest</code></a> and
<a href="#class-http2http2serverresponse"><code>Http2ServerResponse</code></a>. They aim at API compatibility with HTTP/1, but
they do not hide the differences between the protocols. As an example,
the status message for HTTP codes is ignored.</p>
<h3>ALPN negotiation<span><a class="mark" href="#http2_alpn_negotiation" id="http2_alpn_negotiation">#</a></span></h3>
<p>ALPN negotiation allows supporting both <a href="https.html">HTTPS</a> and HTTP/2 over
the same socket. The <code>req</code> and <code>res</code> objects can be either HTTP/1 or
HTTP/2, and an application <strong>must</strong> restrict itself to the public API of
<a href="http.html">HTTP/1</a>, and detect if it is possible to use the more advanced
features of HTTP/2.</p>
<p>The following example creates a server that supports both protocols:</p>
<pre><code class="language-js">const { createSecureServer } = require('http2');
const { readFileSync } = require('fs');

const cert = readFileSync('./cert.pem');
const key = readFileSync('./key.pem');

const server = createSecureServer(
  { cert, key, allowHTTP1: true },
  onRequest
).listen(4443);

function onRequest(req, res) {
  // Detects if it is a HTTPS request or HTTP/2
  const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ?
    req.stream.session : req;
  res.writeHead(200, { 'content-type': 'application/json' });
  res.end(JSON.stringify({
    alpnProtocol,
    httpVersion: req.httpVersion
  }));
}
</code></pre>
<p>The <code>'request'</code> event works identically on both <a href="https.html">HTTPS</a> and
HTTP/2.</p>
<h3>Class: <code>http2.Http2ServerRequest</code><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>
<ul>
<li>Extends: <a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<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>
<h4>Event: <code>'aborted'</code><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: <code>'close'</code><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><code>request.aborted</code><span><a class="mark" href="#http2_request_aborted" id="http2_request_aborted">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.1.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <code>request.aborted</code> property will be <code>true</code> if the request has
been aborted.</p>
<h4><code>request.authority</code><span><a class="mark" href="#http2_request_authority" id="http2_request_authority">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The request authority pseudo header field. It can also be accessed via
<code>req.headers[':authority']</code>.</p>
<h4><code>request.complete</code><span><a class="mark" href="#http2_request_complete" id="http2_request_complete">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <code>request.complete</code> property will be <code>true</code> if the request has
been completed, aborted, or destroyed.</p>
<h4><code>request.destroy([error])</code><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">&#x3C;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><code>request.headers</code><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">&#x3C;Object></a></li>
</ul>
<p>The request/response headers object.</p>
<p>Key-value pairs of header names and values. Header names are lower-cased.</p>
<pre><code class="language-js">// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
//   host: '127.0.0.1:8000',
//   accept: '*/*' }
console.log(request.headers);
</code></pre>
<p>See <a href="#http2_headers_object">HTTP/2 Headers Object</a>.</p>
<p>In HTTP/2, the request path, host name, protocol, and method are represented as
special headers prefixed with the <code>:</code> character (e.g. <code>':path'</code>). These special
headers will be included in the <code>request.headers</code> object. Care must be taken not
to inadvertently modify these special headers or errors may occur. For instance,
removing all headers from the request will cause errors to occur:</p>
<pre><code class="language-js">removeAllHeaders(request.headers);
assert(request.url);   // Fails because the :path header has been removed
</code></pre>
<h4><code>request.httpVersion</code><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">&#x3C;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><code>request.method</code><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">&#x3C;string></a></li>
</ul>
<p>The request method as a string. Read-only. Examples: <code>'GET'</code>, <code>'DELETE'</code>.</p>
<h4><code>request.rawHeaders</code><span><a class="mark" href="#http2_request_rawheaders" id="http2_request_rawheaders">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>The raw request/response headers list exactly as they were received.</p>
<p>The keys and values are in the same list. It is <em>not</em> a
list of tuples. So, the even-numbered offsets are key values, and the
odd-numbered offsets are the associated values.</p>
<p>Header names are not lowercased, and duplicates are not merged.</p>
<pre><code class="language-js">// Prints something like:
//
// [ 'user-agent',
//   'this is invalid because there can be only one',
//   'User-Agent',
//   'curl/7.22.0',
//   'Host',
//   '127.0.0.1:8000',
//   'ACCEPT',
//   '*/*' ]
console.log(request.rawHeaders);
</code></pre>
<h4><code>request.rawTrailers</code><span><a class="mark" href="#http2_request_rawtrailers" id="http2_request_rawtrailers">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>The raw request/response trailer keys and values exactly as they were
received. Only populated at the <code>'end'</code> event.</p>
<h4><code>request.scheme</code><span><a class="mark" href="#http2_request_scheme" id="http2_request_scheme">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The request scheme pseudo header field indicating the scheme
portion of the target URL.</p>
<h4><code>request.setTimeout(msecs, callback)</code><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">&#x3C;number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#http2_class_http2_http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a></li>
</ul>
<p>Sets the <a href="#http2_class_http2stream"><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="#http2_class_http2stream"><code>Http2Stream</code></a>s are destroyed when they time out. If a
handler is assigned to the request, the response, or the server's <code>'timeout'</code>
events, timed out sockets must be handled explicitly.</p>
<h4><code>request.socket</code><span><a class="mark" href="#http2_request_socket" id="http2_request_socket">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> | <a href="#tls_class_tls_tlssocket" class="type">&#x3C;tls.TLSSocket></a></li>
</ul>
<p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but
applies getters, setters, and methods based on HTTP/2 logic.</p>
<p><code>destroyed</code>, <code>readable</code>, and <code>writable</code> properties will be retrieved from and
set on <code>request.stream</code>.</p>
<p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>on</code> and <code>once</code> methods will be called on
<code>request.stream</code>.</p>
<p><code>setTimeout</code> method will be called on <code>request.stream.session</code>.</p>
<p><code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw an error with code
<code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href="#http2_http2session_and_sockets"><code>Http2Session</code> and Sockets</a> for
more information.</p>
<p>All other interactions will be routed directly to the socket. With TLS support,
use <a href="#tls_tlssocket_getpeercertificate_detailed"><code>request.socket.getPeerCertificate()</code></a> to obtain the client's
authentication details.</p>
<h4><code>request.stream</code><span><a class="mark" href="#http2_request_stream" id="http2_request_stream">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#http2_class_http2stream" class="type">&#x3C;Http2Stream></a></li>
</ul>
<p>The <a href="#http2_class_http2stream"><code>Http2Stream</code></a> object backing the request.</p>
<h4><code>request.trailers</code><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">&#x3C;Object></a></li>
</ul>
<p>The request/response trailers object. Only populated at the <code>'end'</code> event.</p>
<h4><code>request.url</code><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">&#x3C;string></a></li>
</ul>
<p>Request URL string. This contains only the URL that is
present in the actual HTTP request. If the request is:</p>
<pre><code class="language-http">GET /status?name=ryan HTTP/1.1\r\n
Accept: text/plain\r\n
\r\n
</code></pre>
<p>Then <code>request.url</code> will be:</p>
<!-- eslint-disable semi -->
<pre><code class="language-js">'/status?name=ryan'
</code></pre>
<p>To parse the url into its parts <code>require('url').parse(request.url)</code>
can be used:</p>
<pre><code class="language-console">$ node
> require('url').parse('/status?name=ryan')
Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?name=ryan',
  query: 'name=ryan',
  pathname: '/status',
  path: '/status?name=ryan',
  href: '/status?name=ryan' }
</code></pre>
<p>To extract the parameters from the query string, the
<code>require('querystring').parse</code> function can be used, or
<code>true</code> can be passed as the second argument to <code>require('url').parse</code>.</p>
<pre><code class="language-console">$ 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: <code>http2.Http2ServerResponse</code><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>
<ul>
<li>Extends: <a href="#stream_stream" class="type">&#x3C;Stream></a></li>
</ul>
<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>
<h4>Event: <code>'close'</code><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="#http2_class_http2stream"><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: <code>'finish'</code><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><code>response.addTrailers(headers)</code><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">&#x3C;Object></a></li>
</ul>
<p>This method adds HTTP trailing headers (a header but at the end of the
message) to the response.</p>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p>
<h4><code>response.connection</code><span><a class="mark" href="#http2_response_connection" id="http2_response_connection">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> | <a href="#tls_class_tls_tlssocket" class="type">&#x3C;tls.TLSSocket></a></li>
</ul>
<p>See <a href="#http2_response_socket"><code>response.socket</code></a>.</p>
<h4><code>response.end([data[, encoding]][, callback])</code><span><a class="mark" href="#http2_response_end_data_encoding_callback" id="http2_response_end_data_encoding_callback">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>This method now returns a reference to <code>ServerResponse</code>.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type">&#x3C;this></a></li>
</ul>
<p>This method signals to the server that all of the response headers and body
have been sent; that server should consider this message complete.
The method, <code>response.end()</code>, MUST be called on each response.</p>
<p>If <code>data</code> is specified, it is equivalent to calling
<a href="#http_response_write_chunk_encoding_callback"><code>response.write(data, encoding)</code></a> followed by <code>response.end(callback)</code>.</p>
<p>If <code>callback</code> is specified, it will be called when the response stream
is finished.</p>
<h4><code>response.finished</code><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><span>Deprecated since: v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated. Use <a href="#http2_response_writableended"><code>response.writableEnded</code></a>.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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><code>response.getHeader(name)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Reads out a header that has already been queued but not sent to the client.
The name is case-insensitive.</p>
<pre><code class="language-js">const contentType = response.getHeader('content-type');
</code></pre>
<h4><code>response.getHeaderNames()</code><span><a class="mark" href="#http2_response_getheadernames" id="http2_response_getheadernames">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>Returns an array containing the unique names of the current outgoing headers.
All header names are lowercase.</p>
<pre><code class="language-js">response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

const headerNames = response.getHeaderNames();
// headerNames === ['foo', 'set-cookie']
</code></pre>
<h4><code>response.getHeaders()</code><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">&#x3C;Object></a></li>
</ul>
<p>Returns a shallow copy of the current outgoing headers. Since a shallow copy
is used, array values may be mutated without additional calls to various
header-related http module methods. The keys of the returned object are the
header names and the values are the respective header values. All header names
are lowercase.</p>
<p>The object returned by the <code>response.getHeaders()</code> method <em>does not</em>
prototypically inherit from the JavaScript <code>Object</code>. This means that typical
<code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others
are not defined and <em>will not work</em>.</p>
<pre><code class="language-js">response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

const headers = response.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
</code></pre>
<h4><code>response.hasHeader(name)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the header identified by <code>name</code> is currently set in the
outgoing headers. The header name matching is case-insensitive.</p>
<pre><code class="language-js">const hasContentType = response.hasHeader('content-type');
</code></pre>
<h4><code>response.headersSent</code><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">&#x3C;boolean></a></li>
</ul>
<p>True if headers were sent, false otherwise (read-only).</p>
<h4><code>response.removeHeader(name)</code><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">&#x3C;string></a></li>
</ul>
<p>Removes a header that has been queued for implicit sending.</p>
<pre><code class="language-js">response.removeHeader('Content-Encoding');
</code></pre>
<h4><code>response.sendDate</code><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">&#x3C;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><code>response.setHeader(name, value)</code><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">&#x3C;string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>Sets a single header value for implicit headers. If this header already exists
in the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name.</p>
<pre><code class="language-js">response.setHeader('Content-Type', 'text/html');
</code></pre>
<p>or</p>
<pre><code class="language-js">response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
</code></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p>
<p>When headers have been set with <a href="#http2_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="language-js">// Returns content-type = text/plain
const server = http2.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ok');
});
</code></pre>
<h4><code>response.setTimeout(msecs[, callback])</code><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">&#x3C;number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#http2_class_http2_http2serverresponse" class="type">&#x3C;http2.Http2ServerResponse></a></li>
</ul>
<p>Sets the <a href="#http2_class_http2stream"><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="#http2_class_http2stream"><code>Http2Stream</code></a>s are destroyed when they time out. If a
handler is assigned to the request, the response, or the server's <code>'timeout'</code>
events, timed out sockets must be handled explicitly.</p>
<h4><code>response.socket</code><span><a class="mark" href="#http2_response_socket" id="http2_response_socket">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> | <a href="#tls_class_tls_tlssocket" class="type">&#x3C;tls.TLSSocket></a></li>
</ul>
<p>Returns a <code>Proxy</code> object that acts as a <code>net.Socket</code> (or <code>tls.TLSSocket</code>) but
applies getters, setters, and methods based on HTTP/2 logic.</p>
<p><code>destroyed</code>, <code>readable</code>, and <code>writable</code> properties will be retrieved from and
set on <code>response.stream</code>.</p>
<p><code>destroy</code>, <code>emit</code>, <code>end</code>, <code>on</code> and <code>once</code> methods will be called on
<code>response.stream</code>.</p>
<p><code>setTimeout</code> method will be called on <code>response.stream.session</code>.</p>
<p><code>pause</code>, <code>read</code>, <code>resume</code>, and <code>write</code> will throw an error with code
<code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code>. See <a href="#http2_http2session_and_sockets"><code>Http2Session</code> and Sockets</a> for
more information.</p>
<p>All other interactions will be routed directly to the socket.</p>
<pre><code class="language-js">const http2 = require('http2');
const server = http2.createServer((req, res) => {
  const ip = req.socket.remoteAddress;
  const port = req.socket.remotePort;
  res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);
</code></pre>
<h4><code>response.statusCode</code><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">&#x3C;number></a></li>
</ul>
<p>When using implicit headers (not calling <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> explicitly),
this property controls the status code that will be sent to the client when
the headers get flushed.</p>
<pre><code class="language-js">response.statusCode = 404;
</code></pre>
<p>After response header was sent to the client, this property indicates the
status code which was sent out.</p>
<h4><code>response.statusMessage</code><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">&#x3C;string></a></li>
</ul>
<p>Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns
an empty string.</p>
<h4><code>response.stream</code><span><a class="mark" href="#http2_response_stream" id="http2_response_stream">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#http2_class_http2stream" class="type">&#x3C;Http2Stream></a></li>
</ul>
<p>The <a href="#http2_class_http2stream"><code>Http2Stream</code></a> object backing the response.</p>
<h4><code>response.writableEnded</code><span><a class="mark" href="#http2_response_writableended" id="http2_response_writableended">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> after <a href="#http2_response_end_data_encoding_callback"><code>response.end()</code></a> has been called. This property
does not indicate whether the data has been flushed, for this use
<a href="#stream_writable_writablefinished"><code>writable.writableFinished</code></a> instead.</p>
<h4><code>response.write(chunk[, encoding][, callback])</code><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">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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>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><code>response.writeContinue()</code><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><code>response.writeHead(statusCode[, statusMessage][, headers])</code><span><a class="mark" href="#http2_response_writehead_statuscode_statusmessage_headers" id="http2_response_writehead_statuscode_statusmessage_headers">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.10.0</td>
<td><p>Return <code>this</code> from <code>writeHead()</code> to allow chaining with <code>end()</code>.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>statusMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li>Returns: <a href="#http2_class_http2_http2serverresponse" class="type">&#x3C;http2.Http2ServerResponse></a></li>
</ul>
<p>Sends a response header to the request. The status code is a 3-digit HTTP
status code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers.</p>
<p>Returns a reference to the <code>Http2ServerResponse</code>, so that calls can be chained.</p>
<p>For compatibility with <a href="http.html">HTTP/1</a>, a human-readable <code>statusMessage</code> may be
passed as the second argument. However, because the <code>statusMessage</code> has no
meaning within HTTP/2, the argument will have no effect and a process warning
will be emitted.</p>
<pre><code class="language-js">const body = 'hello world';
response.writeHead(200, {
  'Content-Length': Buffer.byteLength(body),
  'Content-Type': 'text/plain' });
</code></pre>
<p><code>Content-Length</code> 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
<code>Content-Length</code> does not match the actual payload size.</p>
<p>This method may be called at most one time on a message before
<a href="#http2_response_end_data_encoding_callback"><code>response.end()</code></a> is called.</p>
<p>If <a href="#http2_response_write_chunk_encoding_callback"><code>response.write()</code></a> or <a href="#http2_response_end_data_encoding_callback"><code>response.end()</code></a> are called before calling
this, the implicit/mutable headers will be calculated and call this function.</p>
<p>When headers have been set with <a href="#http2_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#http2_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="language-js">// Returns content-type = text/plain
const server = http2.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ok');
});
</code></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p>
<h4><code>response.createPushResponse(headers, callback)</code><span><a class="mark" href="#http2_response_createpushresponse_headers_callback" id="http2_response_createpushresponse_headers_callback">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#http2_headers_object" class="type">&#x3C;HTTP/2 Headers Object></a> An object describing the headers</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called once <code>http2stream.pushStream()</code> is finished,
or either when the attempt to create the pushed <code>Http2Stream</code> has failed or
has been rejected, or the state of <code>Http2ServerRequest</code> is closed prior to
calling the <code>http2stream.pushStream()</code> method</p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>stream</code> <a href="#http2_class_serverhttp2stream" class="type">&#x3C;ServerHttp2Stream></a> The newly-created <code>ServerHttp2Stream</code> object</li>
</ul>
</li>
</ul>
<p>Call <a href="#http2_http2stream_pushstream_headers_options_callback"><code>http2stream.pushStream()</code></a> with the given headers, and wrap the
given <a href="#http2_class_http2stream"><code>Http2Stream</code></a> on a newly created <code>Http2ServerResponse</code> as the callback
parameter if successful. When <code>Http2ServerRequest</code> is closed, the callback is
called with an error <code>ERR_HTTP2_INVALID_STREAM</code>.</p>
<h2>Collecting HTTP/2 performance metrics<span><a class="mark" href="#http2_collecting_http_2_performance_metrics" id="http2_collecting_http_2_performance_metrics">#</a></span></h2>
<p>The <a href="perf_hooks.html">Performance Observer</a> API can be used to collect basic performance
metrics for each <code>Http2Session</code> and <code>Http2Stream</code> instance.</p>
<pre><code class="language-js">const { PerformanceObserver } = require('perf_hooks');

const obs = new PerformanceObserver((items) => {
  const entry = items.getEntries()[0];
  console.log(entry.entryType);  // prints 'http2'
  if (entry.name === 'Http2Session') {
    // Entry contains statistics about the Http2Session
  } else if (entry.name === 'Http2Stream') {
    // Entry contains statistics about the Http2Stream
  }
});
obs.observe({ entryTypes: ['http2'] });
</code></pre>
<p>The <code>entryType</code> property of the <code>PerformanceEntry</code> will be equal to <code>'http2'</code>.</p>
<p>The <code>name</code> property of the <code>PerformanceEntry</code> will be equal to either
<code>'Http2Stream'</code> or <code>'Http2Session'</code>.</p>
<p>If <code>name</code> is equal to <code>Http2Stream</code>, the <code>PerformanceEntry</code> will contain the
following additional properties:</p>
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of <code>DATA</code> frame bytes received for this
<code>Http2Stream</code>.</li>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of <code>DATA</code> frame bytes sent for this
<code>Http2Stream</code>.</li>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;string></a> Either <code>'server'</code> or <code>'client'</code> to identify the type of
<code>Http2Session</code>.</li>
</ul>
<h1>HTTPS<span><a class="mark" href="#https_https" id="https_https">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.</p>
<h2>Class: <code>https.Agent</code><span><a class="mark" href="#https_class_https_agent" id="https_class_https_agent">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.3.0</td>
<td><p>support <code>0</code> <code>maxCachedSessions</code> to disable TLS session caching.</p></td></tr>
<tr><td>v2.5.0</td>
<td><p>parameter <code>maxCachedSessions</code> added to <code>options</code> for TLS sessions reuse.</p></td></tr>
<tr><td>v0.4.5</td>
<td><p><span>Added in: v0.4.5</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An <a href="#https_class_https_agent"><code>Agent</code></a> object for HTTPS similar to <a href="#http_class_http_agent"><code>http.Agent</code></a>. See
<a href="#https_https_request_options_callback"><code>https.request()</code></a> for more information.</p>
<h3><code>new Agent([options])</code><span><a class="mark" href="#https_new_agent_options" id="https_new_agent_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.5.0</td>
<td><p>do not automatically set servername if the target host was specified using an IP address.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Set of configurable options to set on the agent.
Can have the same fields as for <a href="#http_new_agent_options"><code>http.Agent(options)</code></a>, and</p>
<ul>
<li>
<p><code>maxCachedSessions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> maximum number of TLS cached sessions.
Use <code>0</code> to disable TLS session caching. <strong>Default:</strong> <code>100</code>.</p>
</li>
<li>
<p><code>servername</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> the value of
<a href="https://en.wikipedia.org/wiki/Server_Name_Indication">Server Name Indication extension</a> to be sent to the server. Use
empty string <code>''</code> to disable sending the extension.
<strong>Default:</strong> host name of the target server, unless the target server
is specified using an IP address, in which case the default is <code>''</code> (no
extension).</p>
<p>See <a href="#tls_session_resumption"><code>Session Resumption</code></a> for information about TLS session reuse.</p>
</li>
</ul>
</li>
</ul>
<h4>Event: <code>'keylog'</code><span><a class="mark" href="#https_event_keylog" id="https_event_keylog">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li><code>line</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> Line of ASCII text, in NSS <code>SSLKEYLOGFILE</code> format.</li>
<li><code>tlsSocket</code> <a href="#tls_class_tls_tlssocket" class="type">&#x3C;tls.TLSSocket></a> The <code>tls.TLSSocket</code> instance on which it was
generated.</li>
</ul>
<p>The <code>keylog</code> event is emitted when key material is generated or received by a
connection managed by this agent (typically before handshake has completed, but
not necessarily). This keying material can be stored for debugging, as it
allows captured TLS traffic to be decrypted. It may be emitted multiple times
for each socket.</p>
<p>A typical use case is to append received lines to a common text file, which is
later used by software (such as Wireshark) to decrypt the traffic:</p>
<pre><code class="language-js">// ...
https.globalAgent.on('keylog', (line, tlsSocket) => {
  fs.appendFileSync('/tmp/ssl-keys.log', line, { mode: 0o600 });
});
</code></pre>
<h2>Class: <code>https.Server</code><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>
<ul>
<li>Extends: <a href="#tls_class_tls_server" class="type">&#x3C;tls.Server></a></li>
</ul>
<p>See <a href="#http_class_http_server"><code>http.Server</code></a> for more information.</p>
<h3><code>server.close([callback])</code><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">&#x3C;Function></a></li>
<li>Returns: <a href="#https_class_https_server" class="type">&#x3C;https.Server></a></li>
</ul>
<p>See <a href="#http_server_close_callback"><code>server.close()</code></a> from the HTTP module for details.</p>
<h3><code>server.headersTimeout</code><span><a class="mark" href="#https_server_headerstimeout" id="https_server_headerstimeout">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <strong>Default:</strong> <code>60000</code></li>
</ul>
<p>See <a href="#http_server_headerstimeout"><code>http.Server#headersTimeout</code></a>.</p>
<h3><code>server.listen()</code><span><a class="mark" href="#https_server_listen" id="https_server_listen">#</a></span></h3>
<p>Starts the HTTPS server listening for encrypted connections.
This method is identical to <a href="#net_server_listen"><code>server.listen()</code></a> from <a href="#net_class_net_server"><code>net.Server</code></a>.</p>
<h3><code>server.maxHeadersCount</code><span><a class="mark" href="#https_server_maxheaderscount" id="https_server_maxheaderscount">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <strong>Default:</strong> <code>2000</code></li>
</ul>
<p>See <a href="#http_server_maxheaderscount"><code>http.Server#maxHeadersCount</code></a>.</p>
<h3><code>server.setTimeout([msecs][, callback])</code><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">&#x3C;number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#https_class_https_server" class="type">&#x3C;https.Server></a></li>
</ul>
<p>See <a href="#http_server_settimeout_msecs_callback"><code>http.Server#setTimeout()</code></a>.</p>
<h3><code>server.timeout</code><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">&#x3C;number></a> <strong>Default:</strong> <code>120000</code> (2 minutes)</li>
</ul>
<p>See <a href="#http_server_timeout"><code>http.Server#timeout</code></a>.</p>
<h3><code>server.keepAliveTimeout</code><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">&#x3C;number></a> <strong>Default:</strong> <code>5000</code> (5 seconds)</li>
</ul>
<p>See <a href="#http_server_keepalivetimeout"><code>http.Server#keepAliveTimeout</code></a>.</p>
<h2><code>https.createServer([options][, requestListener])</code><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">&#x3C;Object></a> Accepts <code>options</code> from <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>,
<a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> and <a href="#http_http_createserver_options_requestlistener"><code>http.createServer()</code></a>.</li>
<li><code>requestListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A listener to be added to the <code>'request'</code> event.</li>
<li>Returns: <a href="#https_class_https_server" class="type">&#x3C;https.Server></a></li>
</ul>
<pre><code class="language-js">// curl -k https://localhost:8000/
const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
}).listen(8000);
</code></pre>
<p>Or</p>
<pre><code class="language-js">const https = require('https');
const fs = require('fs');

const options = {
  pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
  passphrase: 'sample'
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
}).listen(8000);
</code></pre>
<h2><code>https.get(options[, callback])</code><span><a class="mark" href="#https_https_get_options_callback" id="https_https_get_options_callback">#</a></span></h2>
<h2><code>https.get(url[, options][, callback])</code><span><a class="mark" href="#https_https_get_url_options_callback" id="https_https_get_url_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr>
<tr><td>v7.5.0</td>
<td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr>
<tr><td>v0.3.6</td>
<td><p><span>Added in: v0.3.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;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">&#x3C;Function></a></li>
</ul>
<p>Like <a href="#http_http_get_options_callback"><code>http.get()</code></a> but for HTTPS.</p>
<p><code>options</code> can be an object, a string, or a <a href="#url_the_whatwg_url_api"><code>URL</code></a> object. If <code>options</code> is a
string, it is automatically parsed with <a href="#url_constructor_new_url_input_base"><code>new URL()</code></a>. If it is a <a href="#url_the_whatwg_url_api"><code>URL</code></a>
object, it will be automatically converted to an ordinary <code>options</code> object.</p>
<pre><code class="language-js">const https = require('https');

https.get('https://encrypted.google.com/', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });

}).on('error', (e) => {
  console.error(e);
});
</code></pre>
<h2><code>https.globalAgent</code><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><code>https.request(options[, callback])</code><span><a class="mark" href="#https_https_request_options_callback" id="https_https_request_options_callback">#</a></span></h2>
<h2><code>https.request(url[, options][, callback])</code><span><a class="mark" href="#https_https_request_url_options_callback" id="https_https_request_url_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr>
<tr><td>v9.3.0</td>
<td><p>The <code>options</code> parameter can now include <code>clientCertEngine</code>.</p></td></tr>
<tr><td>v7.5.0</td>
<td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr>
<tr><td>v0.3.6</td>
<td><p><span>Added in: v0.3.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> Accepts all <code>options</code> from
<a href="#http_http_request_options_callback"><code>http.request()</code></a>, with some differences in default values:</p>
<ul>
<li><code>protocol</code> <strong>Default:</strong> <code>'https:'</code></li>
<li><code>port</code> <strong>Default:</strong> <code>443</code></li>
<li><code>agent</code> <strong>Default:</strong> <code>https.globalAgent</code></li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Makes a request to a secure web server.</p>
<p>The following additional <code>options</code> from <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> are also accepted:
<code>ca</code>, <code>cert</code>, <code>ciphers</code>, <code>clientCertEngine</code>, <code>crl</code>, <code>dhparam</code>, <code>ecdhCurve</code>,
<code>honorCipherOrder</code>, <code>key</code>, <code>passphrase</code>, <code>pfx</code>, <code>rejectUnauthorized</code>,
<code>secureOptions</code>, <code>secureProtocol</code>, <code>servername</code>, <code>sessionIdContext</code>.</p>
<p><code>options</code> can be an object, a string, or a <a href="#url_the_whatwg_url_api"><code>URL</code></a> object. If <code>options</code> is a
string, it is automatically parsed with <a href="#url_constructor_new_url_input_base"><code>new URL()</code></a>. If it is a <a href="#url_the_whatwg_url_api"><code>URL</code></a>
object, it will be automatically converted to an ordinary <code>options</code> object.</p>
<pre><code class="language-js">const https = require('https');

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET'
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});
req.end();
</code></pre>
<p>Example using options from <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>:</p>
<pre><code class="language-js">const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
options.agent = new https.Agent(options);

const req = https.request(options, (res) => {
  // ...
});
</code></pre>
<p>Alternatively, opt out of connection pooling by not using an <a href="#https_class_https_agent"><code>Agent</code></a>.</p>
<pre><code class="language-js">const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
  agent: false
};

const req = https.request(options, (res) => {
  // ...
});
</code></pre>
<p>Example using a <a href="#url_the_whatwg_url_api"><code>URL</code></a> as <code>options</code>:</p>
<pre><code class="language-js">const options = new URL('https://abc:xyz@example.com');

const req = https.request(options, (res) => {
  // ...
});
</code></pre>
<p>Example pinning on certificate fingerprint, or the public key (similar to
<code>pin-sha256</code>):</p>
<pre><code class="language-js">const tls = require('tls');
const https = require('https');
const crypto = require('crypto');

function sha256(s) {
  return crypto.createHash('sha256').update(s).digest('base64');
}
const options = {
  hostname: 'github.com',
  port: 443,
  path: '/',
  method: 'GET',
  checkServerIdentity: function(host, cert) {
    // Make sure the certificate is issued to the host we are connected to
    const err = tls.checkServerIdentity(host, cert);
    if (err) {
      return err;
    }

    // Pin the public key, similar to HPKP pin-sha25 pinning
    const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';
    if (sha256(cert.pubkey) !== pubkey256) {
      const msg = 'Certificate verification error: ' +
        `The public key of '${cert.subject.CN}' ` +
        'does not match our pinned fingerprint';
      return new Error(msg);
    }

    // Pin the exact certificate, rather than the pub key
    const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +
      'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';
    if (cert.fingerprint256 !== cert256) {
      const msg = 'Certificate verification error: ' +
        `The certificate of '${cert.subject.CN}' ` +
        'does not match our pinned fingerprint';
      return new Error(msg);
    }

    // This loop is informational only.
    // Print the certificate and public key fingerprints of all certs in the
    // chain. Its common to pin the public key of the issuer on the public
    // internet, while pinning the public key of the service in sensitive
    // environments.
    do {
      console.log('Subject Common Name:', cert.subject.CN);
      console.log('  Certificate SHA256 fingerprint:', cert.fingerprint256);

      hash = crypto.createHash('sha256');
      console.log('  Public key ping-sha256:', sha256(cert.pubkey));

      lastprint256 = cert.fingerprint256;
      cert = cert.issuerCertificate;
    } while (cert.fingerprint256 !== lastprint256);

  },
};

options.agent = new https.Agent(options);
const req = https.request(options, (res) => {
  console.log('All OK. Server matched our pinned cert or public key');
  console.log('statusCode:', res.statusCode);
  // Print the HPKP values
  console.log('headers:', res.headers['public-key-pins']);

  res.on('data', (d) => {});
});

req.on('error', (e) => {
  console.error(e.message);
});
req.end();
</code></pre>
<p>Outputs for example:</p>
<pre><code class="language-text">Subject Common Name: github.com
  Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16
  Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=
Subject Common Name: DigiCert SHA2 Extended Validation Server CA
  Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A
  Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=
Subject Common Name: DigiCert High Assurance EV Root CA
  Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF
  Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=
All OK. Server matched our pinned cert or public key
statusCode: 200
headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains
</code></pre>
<h1>Inspector<span><a class="mark" href="#inspector_inspector" id="inspector_inspector">#</a></span></h1>

<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>The <code>inspector</code> module provides an API for interacting with the V8 inspector.</p>
<p>It can be accessed using:</p>
<pre><code class="language-js">const inspector = require('inspector');
</code></pre>
<h2><code>inspector.close()</code><span><a class="mark" href="#inspector_inspector_close" id="inspector_inspector_close">#</a></span></h2>
<p>Deactivate the inspector. Blocks until there are no active connections.</p>
<h2><code>inspector.console</code><span><a class="mark" href="#inspector_inspector_console" id="inspector_inspector_console">#</a></span></h2>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object to send messages to the remote inspector console.</li>
</ul>
<pre><code class="language-js">require('inspector').console.log('a message');
</code></pre>
<p>The inspector console does not have API parity with Node.js
console.</p>
<h2><code>inspector.open([port[, host[, wait]]])</code><span><a class="mark" href="#inspector_inspector_open_port_host_wait" id="inspector_inspector_open_port_host_wait">#</a></span></h2>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Port to listen on for inspector connections. Optional.
<strong>Default:</strong> what was specified on the CLI.</li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Host to listen on for inspector connections. Optional.
<strong>Default:</strong> what was specified on the CLI.</li>
<li><code>wait</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Block until a client has connected. Optional.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
<p>Activate inspector on host and port. Equivalent to <code>node --inspect=[[host:]port]</code>, but can be done programmatically after node has
started.</p>
<p>If wait is <code>true</code>, will block until a client has connected to the inspect port
and flow control has been passed to the debugger client.</p>
<p>See the <a href="#inspector_security">security warning</a> regarding the <code>host</code>
parameter usage.</p>
<h2><code>inspector.url()</code><span><a class="mark" href="#inspector_inspector_url" id="inspector_inspector_url">#</a></span></h2>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>Return the URL of the active inspector, or <code>undefined</code> if there is none.</p>
<pre><code class="language-console">$ node --inspect -p 'inspector.url()'
Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34
For help see https://nodejs.org/en/docs/inspector
ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34

$ node --inspect=localhost:3000 -p 'inspector.url()'
Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a
For help see https://nodejs.org/en/docs/inspector
ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a

$ node -p 'inspector.url()'
undefined
</code></pre>
<h2><code>inspector.waitForDebugger()</code><span><a class="mark" href="#inspector_inspector_waitfordebugger" id="inspector_inspector_waitfordebugger">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.7.0</span>
</div>
<p>Blocks until a client (existing or connected later) has sent
<code>Runtime.runIfWaitingForDebugger</code> command.</p>
<p>An exception will be thrown if there is no active inspector.</p>
<h2>Class: <code>inspector.Session</code><span><a class="mark" href="#inspector_class_inspector_session" id="inspector_class_inspector_session">#</a></span></h2>
<ul>
<li>Extends: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<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: <code>new inspector.Session()</code><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>
<h3>Event: <code>'inspectorNotification'</code><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">&#x3C;Object></a> The notification message object</li>
</ul>
<p>Emitted when any notification from the V8 Inspector is received.</p>
<pre><code class="language-js">session.on('inspectorNotification', (message) => console.log(message.method));
// Debugger.paused
// Debugger.resumed
</code></pre>
<p>It is also possible to subscribe only to notifications with specific method:</p>
<h3>Event: <code>&#x3C;inspector-protocol-method></code>;<span><a class="mark" href="#inspector_event_inspector_protocol_method" id="inspector_event_inspector_protocol_method">#</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">&#x3C;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>&#x3C;inspector-protocol-method></code> value.</p>
<p>The following snippet installs a listener on the <a href="https://chromedevtools.github.io/devtools-protocol/v8/Debugger#event-paused"><code>'Debugger.paused'</code></a>
event, and prints the reason for program suspension whenever program
execution is suspended (through breakpoints, for example):</p>
<pre><code class="language-js">session.on('Debugger.paused', ({ params }) => {
  console.log(params.hitBreakpoints);
});
// [ '/the/file/that/has/the/breakpoint.js:11:0' ]
</code></pre>
<h3><code>session.connect()</code><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.</p>
<h3><code>session.connectToMainThread()</code><span><a class="mark" href="#inspector_session_connecttomainthread" id="inspector_session_connecttomainthread">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.11.0</span>
</div>
<p>Connects a session to the main thread inspector back-end. An exception will
be thrown if this API was not called on a Worker thread.</p>
<h3><code>session.disconnect()</code><span><a class="mark" href="#inspector_session_disconnect" id="inspector_session_disconnect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Immediately close the session. All pending message callbacks will be called
with an error. <a href="#inspector_session_connect"><code>session.connect()</code></a> will need to be called to be able to send
messages again. Reconnected session will lose all inspector state, such as
enabled agents or configured breakpoints.</p>
<h3><code>session.post(method[, params][, callback])</code><span><a class="mark" href="#inspector_session_post_method_params_callback" id="inspector_session_post_method_params_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>method</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Posts a message to the inspector back-end. <code>callback</code> will be notified when
a response is received. <code>callback</code> is a function that accepts two optional
arguments: error and message-specific result.</p>
<pre><code class="language-js">session.post('Runtime.evaluate', { expression: '2 + 2' },
             (error, { result }) => console.log(result));
// Output: { type: 'number', value: 4, description: '4' }
</code></pre>
<p>The latest version of the V8 inspector protocol is published on the
<a href="https://chromedevtools.github.io/devtools-protocol/v8/">Chrome DevTools Protocol Viewer</a>.</p>
<p>Node.js inspector supports all the Chrome DevTools Protocol domains declared
by V8. Chrome DevTools Protocol domain provides an interface for interacting
with one of the runtime agents used to inspect the application state and listen
to the run-time events.</p>
<h2>Example usage<span><a class="mark" href="#inspector_example_usage" id="inspector_example_usage">#</a></span></h2>
<p>Apart from the debugger, various V8 Profilers are available through the DevTools
protocol.</p>
<h3>CPU profiler<span><a class="mark" href="#inspector_cpu_profiler" id="inspector_cpu_profiler">#</a></span></h3>
<p>Here's an example showing how to use the <a href="https://chromedevtools.github.io/devtools-protocol/v8/Profiler">CPU Profiler</a>:</p>
<pre><code class="language-js">const inspector = require('inspector');
const fs = require('fs');
const session = new inspector.Session();
session.connect();

session.post('Profiler.enable', () => {
  session.post('Profiler.start', () => {
    // Invoke business logic under measurement here...

    // some time later...
    session.post('Profiler.stop', (err, { profile }) => {
      // Write profile to disk, upload, etc.
      if (!err) {
        fs.writeFileSync('./profile.cpuprofile', JSON.stringify(profile));
      }
    });
  });
});
</code></pre>
<h3>Heap profiler<span><a class="mark" href="#inspector_heap_profiler" id="inspector_heap_profiler">#</a></span></h3>
<p>Here's an example showing how to use the <a href="https://chromedevtools.github.io/devtools-protocol/v8/HeapProfiler">Heap Profiler</a>:</p>
<pre><code class="language-js">const inspector = require('inspector');
const fs = require('fs');
const session = new inspector.Session();

const fd = fs.openSync('profile.heapsnapshot', 'w');

session.connect();

session.on('HeapProfiler.addHeapSnapshotChunk', (m) => {
  fs.writeSync(fd, m.params.chunk);
});

session.post('HeapProfiler.takeHeapSnapshot', null, (err, r) => {
  console.log('HeapProfiler.takeHeapSnapshot done:', err, r);
  session.disconnect();
  fs.closeSync(fd);
});
</code></pre>
<h1>Internationalization support<span><a class="mark" href="#intl_internationalization_support" id="intl_internationalization_support">#</a></span></h1>


<p>Node.js has many features that make it easier to write internationalized
programs. Some of them are:</p>
<ul>
<li>
<p>Locale-sensitive or Unicode-aware functions in the <a href="https://tc39.github.io/ecma262/">ECMAScript Language
Specification</a>:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase"><code>String.prototype.toLowerCase()</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase"><code>String.prototype.toUpperCase()</code></a></li>
</ul>
</li>
<li>
<p>All functionality described in the <a href="https://tc39.github.io/ecma402/">ECMAScript Internationalization API
Specification</a> (aka ECMA-402):</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl"><code>Intl</code></a> object</li>
<li>Locale-sensitive methods like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare"><code>String.prototype.localeCompare()</code></a> and
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString"><code>Date.prototype.toLocaleString()</code></a></li>
</ul>
</li>
<li>The <a href="#url_the_whatwg_url_api">WHATWG URL parser</a>'s <a href="https://en.wikipedia.org/wiki/Internationalized_domain_name">internationalized domain names</a> (IDNs) support</li>
<li><a href="#buffer_buffer_transcode_source_fromenc_toenc"><code>require('buffer').transcode()</code></a></li>
<li>More accurate <a href="#repl_repl">REPL</a> line editing</li>
<li><a href="#util_class_util_textdecoder"><code>require('util').TextDecoder</code></a></li>
<li><a href="https://github.com/tc39/proposal-regexp-unicode-property-escapes"><code>RegExp</code> Unicode Property Escapes</a></li>
</ul>
<p>Node.js (and its underlying V8 engine) uses <a href="http://site.icu-project.org/">ICU</a> to implement these features
in native C/C++ code. However, some of them require a very large ICU data file
in order to support all locales of the world. Because it is expected that most
Node.js users will make use of only a small portion of ICU functionality, only
a subset of the full ICU data set is provided by Node.js by default. Several
options are provided for customizing and expanding the ICU data set either when
building or running Node.js.</p>
<h2>Options for building Node.js<span><a class="mark" href="#intl_options_for_building_node_js" id="intl_options_for_building_node_js">#</a></span></h2>
<p>To control how ICU is used in Node.js, four <code>configure</code> options are available
during compilation. Additional details on how to compile Node.js are documented
in <a href="https://github.com/nodejs/node/blob/master/BUILDING.md">BUILDING.md</a>.</p>
<ul>
<li><code>--with-intl=none</code>/<code>--without-intl</code></li>
<li><code>--with-intl=system-icu</code></li>
<li><code>--with-intl=small-icu</code> (default)</li>
<li><code>--with-intl=full-icu</code></li>
</ul>
<p>An overview of available Node.js and JavaScript features for each <code>configure</code>
option:</p>
































































































<table><thead><tr><th></th><th><code>none</code></th><th><code>system-icu</code></th><th><code>small-icu</code></th><th><code>full-icu</code></th></tr></thead><tbody><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a></td><td>none (function is no-op)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><code>String.prototype.to*Case()</code></td><td>full</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl"><code>Intl</code></a></td><td>none (object does not exist)</td><td>partial/full (depends on OS)</td><td>partial (English-only)</td><td>full</td></tr><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare"><code>String.prototype.localeCompare()</code></a></td><td>partial (not locale-aware)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><code>String.prototype.toLocale*Case()</code></td><td>partial (not locale-aware)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString"><code>Number.prototype.toLocaleString()</code></a></td><td>partial (not locale-aware)</td><td>partial/full (depends on OS)</td><td>partial (English-only)</td><td>full</td></tr><tr><td><code>Date.prototype.toLocale*String()</code></td><td>partial (not locale-aware)</td><td>partial/full (depends on OS)</td><td>partial (English-only)</td><td>full</td></tr><tr><td><a href="#url_the_whatwg_url_api">WHATWG URL Parser</a></td><td>partial (no IDN support)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="#buffer_buffer_transcode_source_fromenc_toenc"><code>require('buffer').transcode()</code></a></td><td>none (function does not exist)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="#repl_repl">REPL</a></td><td>partial (inaccurate line editing)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="#util_class_util_textdecoder"><code>require('util').TextDecoder</code></a></td><td>partial (basic encodings support)</td><td>partial/full (depends on OS)</td><td>partial (Unicode-only)</td><td>full</td></tr><tr><td><a href="https://github.com/tc39/proposal-regexp-unicode-property-escapes"><code>RegExp</code> Unicode Property Escapes</a></td><td>none (invalid <code>RegExp</code> error)</td><td>full</td><td>full</td><td>full</td></tr></tbody></table>
<p>The "(not locale-aware)" designation denotes that the function carries out its
operation just like the non-<code>Locale</code> version of the function, if one
exists. For example, under <code>none</code> mode, <code>Date.prototype.toLocaleString()</code>'s
operation is identical to that of <code>Date.prototype.toString()</code>.</p>
<h3>Disable all internationalization features (<code>none</code>)<span><a class="mark" href="#intl_disable_all_internationalization_features_none" id="intl_disable_all_internationalization_features_none">#</a></span></h3>
<p>If this option is chosen, most internationalization features mentioned above
will be <strong>unavailable</strong> in the resulting <code>node</code> binary.</p>
<h3>Build with a pre-installed ICU (<code>system-icu</code>)<span><a class="mark" href="#intl_build_with_a_pre_installed_icu_system_icu" id="intl_build_with_a_pre_installed_icu_system_icu">#</a></span></h3>
<p>Node.js can link against an ICU build already installed on the system. In fact,
most Linux distributions already come with ICU installed, and this option would
make it possible to reuse the same set of data used by other components in the
OS.</p>
<p>Functionalities that only require the ICU library itself, such as
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a> and the <a href="#url_the_whatwg_url_api">WHATWG URL parser</a>, are fully
supported under <code>system-icu</code>. Features that require ICU locale data in
addition, such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat"><code>Intl.DateTimeFormat</code></a> <em>may</em> be fully or partially
supported, depending on the completeness of the ICU data installed on the
system.</p>
<h3>Embed a limited set of ICU data (<code>small-icu</code>)<span><a class="mark" href="#intl_embed_a_limited_set_of_icu_data_small_icu" id="intl_embed_a_limited_set_of_icu_data_small_icu">#</a></span></h3>
<p>This option makes the resulting binary link against the ICU library statically,
and includes a subset of ICU data (typically only the English locale) within
the <code>node</code> executable.</p>
<p>Functionalities that only require the ICU library itself, such as
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a> and the <a href="#url_the_whatwg_url_api">WHATWG URL parser</a>, are fully
supported under <code>small-icu</code>. Features that require ICU locale data in addition,
such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat"><code>Intl.DateTimeFormat</code></a>, generally only work with the English locale:</p>
<pre><code class="language-js">const january = new Date(9e8);
const english = new Intl.DateTimeFormat('en', { month: 'long' });
const spanish = new Intl.DateTimeFormat('es', { month: 'long' });

console.log(english.format(january));
// Prints "January"
console.log(spanish.format(january));
// Prints "M01" on small-icu
// Should print "enero"
</code></pre>
<p>This mode provides a good balance between features and binary size, and it is
the default behavior if no <code>--with-intl</code> flag is passed. The official binaries
are also built in this mode.</p>
<h4>Providing ICU data at runtime<span><a class="mark" href="#intl_providing_icu_data_at_runtime" id="intl_providing_icu_data_at_runtime">#</a></span></h4>
<p>If the <code>small-icu</code> option is used, one can still provide additional locale data
at runtime so that the JS methods would work for all ICU locales. Assuming the
data file is stored at <code>/some/directory</code>, it can be made available to ICU
through either:</p>
<ul>
<li>
<p>The <a href="#cli_node_icu_data_file"><code>NODE_ICU_DATA</code></a> environment variable:</p>
<pre><code class="language-bash">env NODE_ICU_DATA=/some/directory node
</code></pre>
</li>
<li>
<p>The <a href="#cli_icu_data_dir_file"><code>--icu-data-dir</code></a> CLI parameter:</p>
<pre><code class="language-bash">node --icu-data-dir=/some/directory
</code></pre>
</li>
</ul>
<p>(If both are specified, the <code>--icu-data-dir</code> CLI parameter takes precedence.)</p>
<p>ICU is able to automatically find and load a variety of data formats, but the
data must be appropriate for the ICU version, and the file correctly named.
The most common name for the data file is <code>icudt6X[bl].dat</code>, where <code>6X</code> denotes
the intended ICU version, and <code>b</code> or <code>l</code> indicates the system's endianness.
Check <a href="http://userguide.icu-project.org/icudata">"ICU Data"</a> article in the ICU User Guide for other supported formats
and more details on ICU data in general.</p>
<p>The <a href="https://www.npmjs.com/package/full-icu">full-icu</a> npm module can greatly simplify ICU data installation by
detecting the ICU version of the running <code>node</code> executable and downloading the
appropriate data file. After installing the module through <code>npm i full-icu</code>,
the data file will be available at <code>./node_modules/full-icu</code>. This path can be
then passed either to <code>NODE_ICU_DATA</code> or <code>--icu-data-dir</code> as shown above to
enable full <code>Intl</code> support.</p>
<h3>Embed the entire ICU (<code>full-icu</code>)<span><a class="mark" href="#intl_embed_the_entire_icu_full_icu" id="intl_embed_the_entire_icu_full_icu">#</a></span></h3>
<p>This option makes the resulting binary link against ICU statically and include
a full set of ICU data. A binary created this way has no further external
dependencies and supports all locales, but might be rather large. See
<a href="https://github.com/nodejs/node/blob/master/BUILDING.md#build-with-full-icu-support-all-locales-supported-by-icu">BUILDING.md</a> on how to compile a binary using this mode.</p>
<h2>Detecting internationalization support<span><a class="mark" href="#intl_detecting_internationalization_support" id="intl_detecting_internationalization_support">#</a></span></h2>
<p>To verify that ICU is enabled at all (<code>system-icu</code>, <code>small-icu</code>, or
<code>full-icu</code>), simply checking the existence of <code>Intl</code> should suffice:</p>
<pre><code class="language-js">const hasICU = typeof Intl === 'object';
</code></pre>
<p>Alternatively, checking for <code>process.versions.icu</code>, a property defined only
when ICU is enabled, works too:</p>
<pre><code class="language-js">const hasICU = typeof process.versions.icu === 'string';
</code></pre>
<p>To check for support for a non-English locale (i.e. <code>full-icu</code> or
<code>system-icu</code>), <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat"><code>Intl.DateTimeFormat</code></a> can be a good distinguishing factor:</p>
<pre><code class="language-js">const hasFullICU = (() => {
  try {
    const january = new Date(9e8);
    const spanish = new Intl.DateTimeFormat('es', { month: 'long' });
    return spanish.format(january) === 'enero';
  } catch (err) {
    return false;
  }
})();
</code></pre>
<p>For more verbose tests for <code>Intl</code> support, the following resources may be found
to be helpful:</p>
<ul>
<li><a href="https://github.com/srl295/btest402">btest402</a>: Generally used to check whether Node.js with <code>Intl</code> support is
built correctly.</li>
<li><a href="https://github.com/tc39/test262/tree/master/test/intl402">Test262</a>: ECMAScript's official conformance test suite includes a section
dedicated to ECMA-402.</li>
</ul>
<h1>Modules<span><a class="mark" href="#modules_modules" id="modules_modules">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>

<p>In the Node.js module system, each file is treated as a separate module. For
example, consider a file named <code>foo.js</code>:</p>
<pre><code class="language-js">const circle = require('./circle.js');
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);
</code></pre>
<p>On the first line, <code>foo.js</code> loads the module <code>circle.js</code> that is in the same
directory as <code>foo.js</code>.</p>
<p>Here are the contents of <code>circle.js</code>:</p>
<pre><code class="language-js">const { PI } = Math;

exports.area = (r) => PI * r ** 2;

exports.circumference = (r) => 2 * PI * r;
</code></pre>
<p>The module <code>circle.js</code> has exported the functions <code>area()</code> and
<code>circumference()</code>. Functions and objects are added to the root of a module
by specifying additional properties on the special <code>exports</code> object.</p>
<p>Variables local to the module will be private, because the module is wrapped
in a function by Node.js (see <a href="#modules_the_module_wrapper">module wrapper</a>).
In this example, the variable <code>PI</code> is private to <code>circle.js</code>.</p>
<p>The <code>module.exports</code> property can be assigned a new value (such as a function
or object).</p>
<p>Below, <code>bar.js</code> makes use of the <code>square</code> module, which exports a Square class:</p>
<pre><code class="language-js">const Square = require('./square.js');
const mySquare = new Square(2);
console.log(`The area of mySquare is ${mySquare.area()}`);
</code></pre>
<p>The <code>square</code> module is defined in <code>square.js</code>:</p>
<pre><code class="language-js">// Assigning to exports will not modify module, must use module.exports
module.exports = class Square {
  constructor(width) {
    this.width = width;
  }

  area() {
    return this.width ** 2;
  }
};
</code></pre>
<p>The module system is implemented in the <code>require('module')</code> module.</p>
<h2>Accessing the main module<span><a class="mark" href="#modules_accessing_the_main_module" id="modules_accessing_the_main_module">#</a></span></h2>

<p>When a file is run directly from Node.js, <code>require.main</code> is set to its
<code>module</code>. That means that it is possible to determine whether a file has been
run directly by testing <code>require.main === module</code>.</p>
<p>For a file <code>foo.js</code>, this will be <code>true</code> if run via <code>node foo.js</code>, but
<code>false</code> if run by <code>require('./foo')</code>.</p>
<p>Because <code>module</code> provides a <code>filename</code> property (normally equivalent to
<code>__filename</code>), the entry point of the current application can be obtained
by checking <code>require.main.filename</code>.</p>
<h2>Addenda: Package manager tips<span><a class="mark" href="#modules_addenda_package_manager_tips" id="modules_addenda_package_manager_tips">#</a></span></h2>

<p>The semantics of the Node.js <code>require()</code> function were designed to be general
enough to support 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/&#x3C;some-package>/&#x3C;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/&#x3C;name>/&#x3C;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>Addenda: The <code>.mjs</code> extension<span><a class="mark" href="#modules_addenda_the_mjs_extension" id="modules_addenda_the_mjs_extension">#</a></span></h2>
<p>It is not possible to <code>require()</code> files that have the <code>.mjs</code> extension.
Attempting to do so will throw <a href="#errors_err_require_esm">an error</a>. The <code>.mjs</code> extension is
reserved for <a href="esm.html">ECMAScript Modules</a> which cannot be loaded via <code>require()</code>.
See <a href="esm.html">ECMAScript Modules</a> for more details.</p>
<h2>All together...<span><a class="mark" href="#modules_all_together" id="modules_all_together">#</a></span></h2>

<p>To get the exact filename that will be loaded when <code>require()</code> is called, use
the <code>require.resolve()</code> function.</p>
<p>Putting together all of the above, here is the high-level algorithm
in pseudocode of what <code>require()</code> does:</p>
<pre><code class="language-text">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)
   c. THROW "not found"
4. LOAD_SELF_REFERENCE(X, dirname(Y))
5. LOAD_NODE_MODULES(X, dirname(Y))
6. THROW "not found"

LOAD_AS_FILE(X)
1. If X is a file, load X as its file extension format. STOP
2. If X.js is a file, load X.js as JavaScript text. STOP
3. If X.json is a file, parse X.json to a JavaScript Object. STOP
4. If X.node is a file, load X.node as binary addon. STOP

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. If "main" is a falsy value, GOTO 2.
   c. let M = X + (json main field)
   d. LOAD_AS_FILE(M)
   e. LOAD_INDEX(M)
   f. LOAD_INDEX(X) DEPRECATED
   g. THROW "not found"
2. LOAD_INDEX(X)

LOAD_NODE_MODULES(X, START)
1. let DIRS = NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
   a. LOAD_PACKAGE_EXPORTS(DIR, X)
   b. LOAD_AS_FILE(DIR/X)
   c. LOAD_AS_DIRECTORY(DIR/X)

NODE_MODULES_PATHS(START)
1. let PARTS = path split(START)
2. let I = count of PARTS - 1
3. let DIRS = [GLOBAL_FOLDERS]
4. while I >= 0,
   a. if PARTS[I] = "node_modules" CONTINUE
   b. DIR = path join(PARTS[0 .. I] + "node_modules")
   c. DIRS = DIRS + DIR
   d. let I = I - 1
5. return DIRS

LOAD_SELF_REFERENCE(X, START)
1. Find the closest package scope to START.
2. If no scope was found, return.
3. If the `package.json` has no "exports", return.
4. If the name in `package.json` is a prefix of X, then
   a. Load the remainder of X relative to this package as if it was
      loaded via `LOAD_NODE_MODULES` with a name in `package.json`.

LOAD_PACKAGE_EXPORTS(DIR, X)
1. Try to interpret X as a combination of name and subpath where the name
   may have a @scope/ prefix and the subpath begins with a slash (`/`).
2. If X does not match this pattern or DIR/name/package.json is not a file,
   return.
3. Parse DIR/name/package.json, and look for "exports" field.
4. If "exports" is null or undefined, return.
5. If "exports" is an object with some keys starting with "." and some keys
  not starting with ".", throw "invalid config".
6. If "exports" is a string, or object with no keys starting with ".", treat
  it as having that value as its "." object property.
7. If subpath is "." and "exports" does not have a "." entry, return.
8. Find the longest key in "exports" that the subpath starts with.
9. If no such key can be found, throw "not found".
10. let RESOLVED =
    fileURLToPath(PACKAGE_EXPORTS_TARGET_RESOLVE(pathToFileURL(DIR/name),
    exports[key], subpath.slice(key.length), ["node", "require"])), as defined
    in the ESM resolver.
11. If key ends with "/":
    a. LOAD_AS_FILE(RESOLVED)
    b. LOAD_AS_DIRECTORY(RESOLVED)
12. Otherwise
   a. If RESOLVED is a file, load it as its file extension format. STOP
13. Throw "not found"
</code></pre>
<h2>Caching<span><a class="mark" href="#modules_caching" id="modules_caching">#</a></span></h2>

<p>Modules are cached after the first time they are loaded. This means (among other
things) that every call to <code>require('foo')</code> will get exactly the same object
returned, if it would resolve to the same file.</p>
<p>Provided <code>require.cache</code> is not modified, multiple calls to <code>require('foo')</code>
will not cause the module code to be executed multiple times. This is an
important feature. With it, "partially done" objects can be returned, thus
allowing transitive dependencies to be loaded even when they would cause cycles.</p>
<p>To have a module execute code multiple times, export a function, and call that
function.</p>
<h3>Module caching caveats<span><a class="mark" href="#modules_module_caching_caveats" id="modules_module_caching_caveats">#</a></span></h3>

<p>Modules are cached based on their resolved filename. Since modules may resolve
to a different filename based on the location of the calling module (loading
from <code>node_modules</code> folders), it is not a <em>guarantee</em> that <code>require('foo')</code> will
always return the exact same object, if it would resolve to different files.</p>
<p>Additionally, on case-insensitive file systems or operating systems, different
resolved filenames can point to the same file, but the cache will still treat
them as different modules and will reload the file multiple times. For example,
<code>require('./foo')</code> and <code>require('./FOO')</code> return two different objects,
irrespective of whether or not <code>./foo</code> and <code>./FOO</code> are the same file.</p>
<h2>Core modules<span><a class="mark" href="#modules_core_modules" id="modules_core_modules">#</a></span></h2>

<p>Node.js has several modules compiled into the binary. These modules are
described in greater detail elsewhere in this documentation.</p>
<p>The core modules are defined within the Node.js source and are located in the
<code>lib/</code> folder.</p>
<p>Core modules are always preferentially loaded if their identifier is
passed to <code>require()</code>. For instance, <code>require('http')</code> will always
return the built in HTTP module, even if there is a file by that name.</p>
<h2>Cycles<span><a class="mark" href="#modules_cycles" id="modules_cycles">#</a></span></h2>

<p>When there are circular <code>require()</code> calls, a module might not have finished
executing when it is returned.</p>
<p>Consider this situation:</p>
<p><code>a.js</code>:</p>
<pre><code class="language-js">console.log('a starting');
exports.done = false;
const b = require('./b.js');
console.log('in a, b.done = %j', b.done);
exports.done = true;
console.log('a done');
</code></pre>
<p><code>b.js</code>:</p>
<pre><code class="language-js">console.log('b starting');
exports.done = false;
const a = require('./a.js');
console.log('in b, a.done = %j', a.done);
exports.done = true;
console.log('b done');
</code></pre>
<p><code>main.js</code>:</p>
<pre><code class="language-js">console.log('main starting');
const a = require('./a.js');
const b = require('./b.js');
console.log('in main, a.done = %j, b.done = %j', a.done, b.done);
</code></pre>
<p>When <code>main.js</code> loads <code>a.js</code>, then <code>a.js</code> in turn loads <code>b.js</code>. At that
point, <code>b.js</code> tries to load <code>a.js</code>. In order to prevent an infinite
loop, an <strong>unfinished copy</strong> of the <code>a.js</code> exports object is returned to the
<code>b.js</code> module. <code>b.js</code> then finishes loading, and its <code>exports</code> object is
provided to the <code>a.js</code> module.</p>
<p>By the time <code>main.js</code> has loaded both modules, they're both finished.
The output of this program would thus be:</p>
<pre><code class="language-console">$ node main.js
main starting
a starting
b starting
in b, a.done = false
b done
in a, b.done = true
a done
in main, a.done = true, b.done = true
</code></pre>
<p>Careful planning is required to allow cyclic module dependencies to work
correctly within an application.</p>
<h2>File modules<span><a class="mark" href="#modules_file_modules" id="modules_file_modules">#</a></span></h2>

<p>If the exact filename is not found, then Node.js will attempt to load the
required filename with the added extensions: <code>.js</code>, <code>.json</code>, and finally
<code>.node</code>.</p>
<p><code>.js</code> files are interpreted as JavaScript text files, and <code>.json</code> files are
parsed as JSON text files. <code>.node</code> files are interpreted as compiled addon
modules loaded with <code>process.dlopen()</code>.</p>
<p>A required module prefixed with <code>'/'</code> is an absolute path to the file. For
example, <code>require('/home/marco/foo.js')</code> will load the file at
<code>/home/marco/foo.js</code>.</p>
<p>A required module prefixed with <code>'./'</code> is relative to the file calling
<code>require()</code>. That is, <code>circle.js</code> must be in the same directory as <code>foo.js</code> for
<code>require('./circle')</code> to find it.</p>
<p>Without a leading <code>'/'</code>, <code>'./'</code>, or <code>'../'</code> to indicate a file, the module must
either be a core module or is loaded from a <code>node_modules</code> folder.</p>
<p>If the given path does not exist, <code>require()</code> will throw an <a href="#errors_class_error"><code>Error</code></a> with its
<code>code</code> property set to <code>'MODULE_NOT_FOUND'</code>.</p>
<h2>Folders as modules<span><a class="mark" href="#modules_folders_as_modules" id="modules_folders_as_modules">#</a></span></h2>

<p>It is convenient to organize programs and libraries into self-contained
directories, and then provide a single entry point to those directories.
There are three ways in which a folder may be passed to <code>require()</code> as
an argument.</p>
<p>The first is to create a <code>package.json</code> file in the root of the folder,
which specifies a <code>main</code> module. An example <code>package.json</code> file might
look like this:</p>
<pre><code class="language-json">{ "name" : "some-library",
  "main" : "./lib/some-library.js" }
</code></pre>
<p>If this was in a folder at <code>./some-library</code>, then
<code>require('./some-library')</code> would attempt to load
<code>./some-library/lib/some-library.js</code>.</p>
<p>This is the extent of the awareness of <code>package.json</code> files within Node.js.</p>
<p>If there is no <code>package.json</code> file present in the directory, or if the
<code>'main'</code> entry is missing or cannot be resolved, then Node.js
will attempt to load an <code>index.js</code> or <code>index.node</code> file out of that
directory. For example, if there was no <code>package.json</code> file in the above
example, then <code>require('./some-library')</code> would attempt to load:</p>
<ul>
<li><code>./some-library/index.js</code></li>
<li><code>./some-library/index.node</code></li>
</ul>
<p>If these attempts fail, then Node.js will report the entire module as missing
with the default error:</p>
<pre><code class="language-console">Error: Cannot find module 'some-library'
</code></pre>
<h2>Loading from <code>node_modules</code> folders<span><a class="mark" href="#modules_loading_from_node_modules_folders" id="modules_loading_from_node_modules_folders">#</a></span></h2>

<p>If the module identifier passed to <code>require()</code> is not a
<a href="#modules_core_modules">core</a> module, and does not begin with <code>'/'</code>, <code>'../'</code>, or
<code>'./'</code>, then Node.js starts at the parent directory of the current module, and
adds <code>/node_modules</code>, and attempts to load the module from that location.
Node.js will not append <code>node_modules</code> to a path already ending in
<code>node_modules</code>.</p>
<p>If it is not found there, then it moves to the parent directory, and so
on, until the root of the file system is reached.</p>
<p>For example, if the file at <code>'/home/ry/projects/foo.js'</code> called
<code>require('bar.js')</code>, then Node.js would look in the following locations, in
this order:</p>
<ul>
<li><code>/home/ry/projects/node_modules/bar.js</code></li>
<li><code>/home/ry/node_modules/bar.js</code></li>
<li><code>/home/node_modules/bar.js</code></li>
<li><code>/node_modules/bar.js</code></li>
</ul>
<p>This allows programs to localize their dependencies, so that they do not
clash.</p>
<p>It is possible to require specific files or sub modules distributed with a
module by including a path suffix after the module name. For instance
<code>require('example-module/path/to/file')</code> would resolve <code>path/to/file</code>
relative to where <code>example-module</code> is located. The suffixed path follows the
same module resolution semantics.</p>
<h2>Loading from the global folders<span><a class="mark" href="#modules_loading_from_the_global_folders" id="modules_loading_from_the_global_folders">#</a></span></h2>

<p>If the <code>NODE_PATH</code> environment variable is set to a colon-delimited list
of absolute paths, then Node.js will search those paths for modules if they
are not found elsewhere.</p>
<p>On Windows, <code>NODE_PATH</code> is delimited by semicolons (<code>;</code>) instead of colons.</p>
<p><code>NODE_PATH</code> was originally created to support loading modules from
varying paths before the current <a href="#modules_all_together">module resolution</a> algorithm was defined.</p>
<p><code>NODE_PATH</code> is still supported, but is less necessary now that the Node.js
ecosystem has settled on a convention for locating dependent modules.
Sometimes deployments that rely on <code>NODE_PATH</code> show surprising behavior
when people are unaware that <code>NODE_PATH</code> must be set. Sometimes a
module's dependencies change, causing a different version (or even a
different module) to be loaded as the <code>NODE_PATH</code> is searched.</p>
<p>Additionally, Node.js will search in the following list of GLOBAL_FOLDERS:</p>
<ul>
<li>1: <code>$HOME/.node_modules</code></li>
<li>2: <code>$HOME/.node_libraries</code></li>
<li>3: <code>$PREFIX/lib/node</code></li>
</ul>
<p>Where <code>$HOME</code> is the user's home directory, and <code>$PREFIX</code> is the Node.js
configured <code>node_prefix</code>.</p>
<p>These are mostly for historic reasons.</p>
<p>It is strongly encouraged to place dependencies in the local <code>node_modules</code>
folder. These will be loaded faster, and more reliably.</p>
<h2>The module wrapper<span><a class="mark" href="#modules_the_module_wrapper" id="modules_the_module_wrapper">#</a></span></h2>

<p>Before a module's code is executed, Node.js will wrap it with a function
wrapper that looks like the following:</p>
<pre><code class="language-js">(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
});
</code></pre>
<p>By doing this, Node.js achieves a few things:</p>
<ul>
<li>It keeps top-level variables (defined with <code>var</code>, <code>const</code> or <code>let</code>) scoped to
the module rather than the global object.</li>
<li>
<p>It helps to provide some global-looking variables that are actually specific
to the module, such as:</p>
<ul>
<li>The <code>module</code> and <code>exports</code> objects that the implementor can use to export
values from the module.</li>
<li>The convenience variables <code>__filename</code> and <code>__dirname</code>, containing the
module's absolute filename and directory path.</li>
</ul>
</li>
</ul>
<h2>The module scope<span><a class="mark" href="#modules_the_module_scope" id="modules_the_module_scope">#</a></span></h2>
<h3><code>__dirname</code><span><a class="mark" href="#modules_dirname" id="modules_dirname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div>

<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The directory name of the current module. This is the same as the
<a href="#path_path_dirname_path"><code>path.dirname()</code></a> of the <a href="#modules_filename"><code>__filename</code></a>.</p>
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p>
<pre><code class="language-js">console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
</code></pre>
<h3><code>__filename</code><span><a class="mark" href="#modules_filename" id="modules_filename">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>

<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The file name of the current module. This is the current module file's absolute
path with symlinks resolved.</p>
<p>For a main program this is not necessarily the same as the file name used in the
command line.</p>
<p>See <a href="#modules_dirname"><code>__dirname</code></a> for the directory name of the current module.</p>
<p>Examples:</p>
<p>Running <code>node example.js</code> from <code>/Users/mjr</code></p>
<pre><code class="language-js">console.log(__filename);
// Prints: /Users/mjr/example.js
console.log(__dirname);
// Prints: /Users/mjr
</code></pre>
<p>Given two modules: <code>a</code> and <code>b</code>, where <code>b</code> is a dependency of
<code>a</code> and there is a directory structure of:</p>
<ul>
<li><code>/Users/mjr/app/a.js</code></li>
<li><code>/Users/mjr/app/node_modules/b/b.js</code></li>
</ul>
<p>References to <code>__filename</code> within <code>b.js</code> will return
<code>/Users/mjr/app/node_modules/b/b.js</code> while references to <code>__filename</code> within
<code>a.js</code> will return <code>/Users/mjr/app/a.js</code>.</p>
<h3><code>exports</code><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>

<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<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><code>module</code><span><a class="mark" href="#modules_module" id="modules_module">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>

<ul>
<li><a href="#modules_the_module_object" class="type">&#x3C;module></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><code>require(id)</code><span><a class="mark" href="#modules_require_id" id="modules_require_id">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.13</span>
</div>

<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> module name or path</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> exported module content</li>
</ul>
<p>Used to import modules, <code>JSON</code>, and local files. Modules can be imported
from <code>node_modules</code>. Local modules and JSON files can be imported using
a relative path (e.g. <code>./</code>, <code>./foo</code>, <code>./bar/baz</code>, <code>../foo</code>) that will be
resolved against the directory named by <a href="#modules_dirname"><code>__dirname</code></a> (if defined) or
the current working directory. The relative paths of POSIX style are resolved
in an OS independent fashion, meaning that the examples above will work on
Windows in the same way they would on Unix systems.</p>
<pre><code class="language-js">// Importing a local module with a path relative to the `__dirname` or current
// working directory. (On Windows, this would resolve to .\path\myLocalModule.)
const myLocalModule = require('./path/myLocalModule');

// Importing a JSON file:
const jsonData = require('./path/filename.json');

// Importing a module from node_modules or Node.js built-in module:
const crypto = require('crypto');
</code></pre>
<h4><code>require.cache</code><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">&#x3C;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.
This does not apply to <a href="addons.html">native addons</a>, for which reloading will result in an
error.</p>
<p>Adding or replacing entries is also possible. This cache is checked before
native modules and if a name matching a native module is added to the cache,
no require call is
going to receive the native module anymore. Use with care!</p>
<h4><code>require.extensions</code><span><a class="mark" href="#modules_require_extensions" id="modules_require_extensions">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span><span>Deprecated since: v0.10.6</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Instruct <code>require</code> on how to handle certain file extensions.</p>
<p>Process files with the extension <code>.sjs</code> as <code>.js</code>:</p>
<pre><code class="language-js">require.extensions['.sjs'] = require.extensions['.js'];
</code></pre>
<p><strong>Deprecated.</strong> In the past, this list has been used to load non-JavaScript
modules into Node.js by compiling them on-demand. However, in practice, there
are much better ways to do this, such as loading modules via some other Node.js
program, or compiling them to JavaScript ahead of time.</p>
<p>Avoid using <code>require.extensions</code>. Use could cause subtle bugs and resolving the
extensions gets slower with each registered extension.</p>
<h4><code>require.main</code><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="#modules_the_module_object" class="type">&#x3C;module></a></li>
</ul>
<p>The <code>Module</code> object representing the entry script loaded when the Node.js
process launched.
See <a href="#modules_accessing_the_main_module">"Accessing the main module"</a>.</p>
<p>In <code>entry.js</code> script:</p>
<pre><code class="language-js">console.log(require.main);
</code></pre>
<pre><code class="language-bash">node entry.js
</code></pre>
<!-- eslint-skip -->
<pre><code class="language-js">Module {
  id: '.',
  path: '/absolute/path/to',
  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><code>require.resolve(request[, options])</code><span><a class="mark" href="#modules_require_resolve_request_options" id="modules_require_resolve_request_options">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.9.0</td>
<td><p>The <code>paths</code> option is now supported.</p></td></tr>
<tr><td>v0.3.0</td>
<td><p><span>Added in: v0.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>request</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The module path to resolve.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>paths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Paths to resolve module location from. If present, these
paths are used instead of the default resolution paths, with the exception
of <a href="#modules_loading_from_the_global_folders">GLOBAL_FOLDERS</a> like <code>$HOME/.node_modules</code>, which are always
included. 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">&#x3C;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>
<p>If the module can not be found, a <code>MODULE_NOT_FOUND</code> error is thrown.</p>
<h5><code>require.resolve.paths(request)</code><span><a class="mark" href="#modules_require_resolve_paths_request" id="modules_require_resolve_paths_request">#</a></span></h5>
<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">&#x3C;string></a> The module path whose lookup paths are being retrieved.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
</ul>
<p>Returns an array containing the paths searched during resolution of <code>request</code> or
<code>null</code> if the <code>request</code> string references a core module, for example <code>http</code> or
<code>fs</code>.</p>
<h2>The <code>module</code> object<span><a class="mark" href="#modules_the_module_object" id="modules_the_module_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>


<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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><code>module.children</code><span><a class="mark" href="#modules_module_children" id="modules_module_children">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><a href="#modules_the_module_object" class="type">&#x3C;module[]></a></li>
</ul>
<p>The module objects required for the first time by this one.</p>
<h3><code>module.exports</code><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">&#x3C;Object></a></li>
</ul>
<p>The <code>module.exports</code> object is created by the <code>Module</code> system. Sometimes this is
not acceptable; many want their module to be an instance of some class. To do
this, assign the desired export object to <code>module.exports</code>. Assigning
the desired object to <code>exports</code> will simply rebind the local <code>exports</code> variable,
which is probably not what is desired.</p>
<p>For example, suppose we were making a module called <code>a.js</code>:</p>
<pre><code class="language-js">const EventEmitter = require('events');

module.exports = new EventEmitter();

// Do some work, and after some time emit
// the 'ready' event from the module itself.
setTimeout(() => {
  module.exports.emit('ready');
}, 1000);
</code></pre>
<p>Then in another file we could do:</p>
<pre><code class="language-js">const a = require('./a');
a.on('ready', () => {
  console.log('module "a" is ready');
});
</code></pre>
<p>Assignment to <code>module.exports</code> must be done immediately. It cannot be
done in any callbacks. This does not work:</p>
<p><code>x.js</code>:</p>
<pre><code class="language-js">setTimeout(() => {
  module.exports = { a: 'hello' };
}, 0);
</code></pre>
<p><code>y.js</code>:</p>
<pre><code class="language-js">const x = require('./x');
console.log(x.a);
</code></pre>
<h4><code>exports</code> shortcut<span><a class="mark" href="#modules_exports_shortcut" id="modules_exports_shortcut">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<p>The <code>exports</code> variable is available within a module's file-level scope, and is
assigned the value of <code>module.exports</code> before the module is evaluated.</p>
<p>It allows a shortcut, so that <code>module.exports.f = ...</code> can be written more
succinctly as <code>exports.f = ...</code>. However, be aware that like any variable, if a
new value is assigned to <code>exports</code>, it is no longer bound to <code>module.exports</code>:</p>
<pre><code class="language-js">module.exports.hello = true; // Exported from require of module
exports = { hello: false };  // Not exported, only available in the module
</code></pre>
<p>When the <code>module.exports</code> property is being completely replaced by a new
object, it is common to also reassign <code>exports</code>:</p>
<!-- eslint-disable func-name-matching -->
<pre><code class="language-js">module.exports = exports = function Constructor() {
  // ... etc.
};
</code></pre>
<p>To illustrate the behavior, imagine this hypothetical implementation of
<code>require()</code>, which is quite similar to what is actually done by <code>require()</code>:</p>
<pre><code class="language-js">function require(/* ... */) {
  const module = { exports: {} };
  ((module, exports) => {
    // Module code here. In this example, define a function.
    function someFunc() {}
    exports = someFunc;
    // At this point, exports is no longer a shortcut to module.exports, and
    // this module will still export an empty default object.
    module.exports = someFunc;
    // At this point, the module will now export someFunc, instead of the
    // default object.
  })(module, module.exports);
  return module.exports;
}
</code></pre>
<h3><code>module.filename</code><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">&#x3C;string></a></li>
</ul>
<p>The fully resolved filename of the module.</p>
<h3><code>module.id</code><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">&#x3C;string></a></li>
</ul>
<p>The identifier for the module. Typically this is the fully resolved
filename.</p>
<h3><code>module.loaded</code><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">&#x3C;boolean></a></li>
</ul>
<p>Whether or not the module is done loading, or is in the process of
loading.</p>
<h3><code>module.parent</code><span><a class="mark" href="#modules_module_parent" id="modules_module_parent">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><a href="#modules_the_module_object" class="type">&#x3C;module></a></li>
</ul>
<p>The module that first required this one.</p>
<h3><code>module.path</code><span><a class="mark" href="#modules_module_path" id="modules_module_path">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.14.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The directory name of the module. This is usually the same as the
<a href="#path_path_dirname_path"><code>path.dirname()</code></a> of the <a href="#modules_module_id"><code>module.id</code></a>.</p>
<h3><code>module.paths</code><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">&#x3C;string[]></a></li>
</ul>
<p>The search paths for the module.</p>
<h3><code>module.require(id)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> exported module content</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">&#x3C;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><code>module.builtinModules</code><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, v8.10.0, v6.13.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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><code>module</code> in this context isn't the same object that's provided
by the <a href="#modules_the_module_wrapper">module wrapper</a>. To access it, require the <code>Module</code> module:</p>
<pre><code class="language-js">const builtin = require('module').builtinModules;
</code></pre>
<h3><code>module.createRequire(filename)</code><span><a class="mark" href="#modules_module_createrequire_filename" id="modules_module_createrequire_filename">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.2.0</span>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> Filename to be used to construct the require
function. Must be a file URL object, file URL string, or absolute path
string.</li>
<li>Returns: <a href="#modules_require_id" class="type">&#x3C;require></a> Require function</li>
</ul>
<pre><code class="language-js">import { createRequire } from 'module';
const require = createRequire(import.meta.url);

// sibling-module.js is a CommonJS module.
const siblingModule = require('./sibling-module');
</code></pre>
<h3><code>module.createRequireFromPath(filename)</code><span><a class="mark" href="#modules_module_createrequirefrompath_filename" id="modules_module_createrequirefrompath_filename">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.12.0</span><span>Deprecated since: v12.2.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Please use <a href="#modules_module_createrequire_filename"><code>createRequire()</code></a> instead.</div><p></p>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Filename to be used to construct the relative require
function.</li>
<li>Returns: <a href="#modules_require_id" class="type">&#x3C;require></a> Require function</li>
</ul>
<pre><code class="language-js">const { createRequireFromPath } = require('module');
const requireUtil = createRequireFromPath('../src/utils/');

// Require `../src/utils/some-tool`
requireUtil('./some-tool');
</code></pre>
<h3><code>module.syncBuiltinESMExports()</code><span><a class="mark" href="#modules_module_syncbuiltinesmexports" id="modules_module_syncbuiltinesmexports">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<p>The <code>module.syncBuiltinESMExports()</code> method updates all the live bindings for
builtin ES Modules to match the properties of the CommonJS exports. It does
not add or remove exported names from the ES Modules.</p>
<pre><code class="language-js">const fs = require('fs');
const { syncBuiltinESMExports } = require('module');

fs.readFile = null;

delete fs.readFileSync;

fs.newAPI = function newAPI() {
  // ...
};

syncBuiltinESMExports();

import('fs').then((esmFS) => {
  assert.strictEqual(esmFS.readFile, null);
  assert.strictEqual('readFileSync' in fs, true);
  assert.strictEqual(esmFS.newAPI, undefined);
});
</code></pre>
<h2>Source map v3 support<span><a class="mark" href="#modules_source_map_v3_support" id="modules_source_map_v3_support">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>Helpers for interacting with the source map cache. This cache is
populated when source map parsing is enabled and
<a href="https://sourcemaps.info/spec.html#h.lmz475t4mvbx">source map include directives</a> are found in a modules' footer.</p>
<p>To enable source map parsing, Node.js must be run with the flag
<a href="#cli_enable_source_maps"><code>--enable-source-maps</code></a>, or with code coverage enabled by setting
<a href="#cli_node_v8_coverage_dir"><code>NODE_V8_COVERAGE=dir</code></a>.</p>
<pre><code class="language-js">const { findSourceMap, SourceMap } = require('module');
</code></pre>
<h3><code>module.findSourceMap(path[, error])</code><span><a class="mark" href="#modules_module_findsourcemap_path_error" id="modules_module_findsourcemap_path_error">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.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">&#x3C;string></a></li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li>Returns: <a href="#modules_class_module_sourcemap" class="type">&#x3C;module.SourceMap></a></li>
</ul>
<p><code>path</code> is the resolved path for the file for which a corresponding source map
should be fetched.</p>
<p>The <code>error</code> instance should be passed as the second parameter to <code>findSourceMap</code>
in exceptional flows, e.g., when an overridden
<a href="https://v8.dev/docs/stack-trace-api#customizing-stack-traces"><code>Error.prepareStackTrace(error, trace)</code></a> is invoked. Modules are not added to
the module cache until they are successfully loaded, in these cases source maps
will be associated with the <code>error</code> instance along with the <code>path</code>.</p>
<h3>Class: <code>module.SourceMap</code><span><a class="mark" href="#modules_class_module_sourcemap" id="modules_class_module_sourcemap">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<h4><code>new SourceMap(payload)</code><span><a class="mark" href="#modules_new_sourcemap_payload" id="modules_new_sourcemap_payload">#</a></span></h4>
<ul>
<li><code>payload</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Creates a new <code>sourceMap</code> instance.</p>
<p><code>payload</code> is an object with keys matching the <a href="https://sourcemaps.info/spec.html#h.mofvlxcwqzej">Source map v3 format</a>:</p>
<ul>
<li><code>file</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>version</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>sources</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
<li><code>sourcesContent</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
<li><code>names</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
<li><code>mappings</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>sourceRoot</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<h4><code>sourceMap.payload</code><span><a class="mark" href="#modules_sourcemap_payload" id="modules_sourcemap_payload">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Getter for the payload used to construct the <a href="#modules_class_module_sourcemap"><code>SourceMap</code></a> instance.</p>
<h4><code>sourceMap.findEntry(lineNumber, columnNumber)</code><span><a class="mark" href="#modules_sourcemap_findentry_linenumber_columnnumber" id="modules_sourcemap_findentry_linenumber_columnnumber">#</a></span></h4>
<ul>
<li><code>lineNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>columnNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Given a line number and column number in the generated source file, returns
an object representing the position in the original file. The object returned
consists of the following keys:</p>
<ul>
<li>generatedLine: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li>generatedColumn: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li>originalSource: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>originalLine: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li>originalColumn: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<h1>Net<span><a class="mark" href="#net_net" id="net_net">#</a></span></h1>

<!--lint disable maximum-line-length-->
<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>net</code> module provides an asynchronous network API for creating stream-based
TCP or <a href="#net_ipc_support">IPC</a> servers (<a href="#net_net_createserver_options_connectionlistener"><code>net.createServer()</code></a>) and clients
(<a href="#net_net_createconnection"><code>net.createConnection()</code></a>).</p>
<p>It can be accessed using:</p>
<pre><code class="language-js">const net = require('net');
</code></pre>
<h2>IPC support<span><a class="mark" href="#net_ipc_support" id="net_ipc_support">#</a></span></h2>
<p>The <code>net</code> module supports IPC with named pipes on Windows, and Unix domain
sockets on other operating systems.</p>
<h3>Identifying paths for IPC connections<span><a class="mark" href="#net_identifying_paths_for_ipc_connections" id="net_identifying_paths_for_ipc_connections">#</a></span></h3>
<p><a href="#net_net_connect"><code>net.connect()</code></a>, <a href="#net_net_createconnection"><code>net.createConnection()</code></a>, <a href="#net_server_listen"><code>server.listen()</code></a> and
<a href="#net_socket_connect"><code>socket.connect()</code></a> take a <code>path</code> parameter to identify IPC endpoints.</p>
<p>On Unix, the local domain is also known as the Unix domain. The path is a
filesystem pathname. It gets truncated to an OS-dependent length of
<code>sizeof(sockaddr_un.sun_path) - 1</code>. Typical values are 107 bytes on Linux and
103 bytes on macOS. If a Node.js API abstraction creates the Unix domain socket,
it will unlink the Unix domain socket as well. For example,
<a href="#net_net_createserver_options_connectionlistener"><code>net.createServer()</code></a> may create a Unix domain socket and
<a href="#net_server_close_callback"><code>server.close()</code></a> will unlink it. But if a user creates the Unix domain
socket outside of these abstractions, the user will need to remove it. The same
applies when a Node.js API creates a Unix domain socket but the program then
crashes. In short, a Unix domain socket will be visible in the filesystem and
will persist until unlinked.</p>
<p>On Windows, the local domain is implemented using a named pipe. The path <em>must</em>
refer to an entry in <code>\\?\pipe\</code> or <code>\\.\pipe\</code>. Any characters are permitted,
but the latter may do some processing of pipe names, such as resolving <code>..</code>
sequences. Despite how it might look, the pipe namespace is flat. Pipes will
<em>not persist</em>. They are removed when the last reference to them is closed.
Unlike Unix domain sockets, Windows will close and remove the pipe when the
owning process exits.</p>
<p>JavaScript string escaping requires paths to be specified with extra backslash
escaping such as:</p>
<pre><code class="language-js">net.createServer().listen(
  path.join('\\\\?\\pipe', process.cwd(), 'myctl'));
</code></pre>
<h2>Class: <code>net.Server</code><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>
<ul>
<li>Extends: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>This class is used to create a TCP or <a href="#net_ipc_support">IPC</a> server.</p>
<h3><code>new net.Server([options][, connectionListener])</code><span><a class="mark" href="#net_new_net_server_options_connectionlistener" id="net_new_net_server_options_connectionlistener">#</a></span></h3>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> See
<a href="#net_net_createserver_options_connectionlistener"><code>net.createServer([options][, connectionListener])</code></a>.</li>
<li><code>connectionListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Automatically set as a listener for the
<a href="#net_event_connection"><code>'connection'</code></a> event.</li>
<li>Returns: <a href="#net_class_net_server" class="type">&#x3C;net.Server></a></li>
</ul>
<p><code>net.Server</code> is an <a href="#events_class_eventemitter"><code>EventEmitter</code></a> with the following events:</p>
<h3>Event: <code>'close'</code><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. If connections exist, this
event is not emitted until all connections are ended.</p>
<h3>Event: <code>'connection'</code><span><a class="mark" href="#net_event_connection" id="net_event_connection">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#net_class_net_socket" class="type">&#x3C;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: <code>'error'</code><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">&#x3C;Error></a></li>
</ul>
<p>Emitted when an error occurs. Unlike <a href="#net_class_net_socket"><code>net.Socket</code></a>, the <a href="#net_event_close"><code>'close'</code></a>
event will <strong>not</strong> be emitted directly following this event unless
<a href="#net_server_close_callback"><code>server.close()</code></a> is manually called. See the example in discussion of
<a href="#net_server_listen"><code>server.listen()</code></a>.</p>
<h3>Event: <code>'listening'</code><span><a class="mark" href="#net_event_listening" id="net_event_listening">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<p>Emitted when the server has been bound after calling <a href="#net_server_listen"><code>server.listen()</code></a>.</p>
<h3><code>server.address()</code><span><a class="mark" href="#net_server_address" id="net_server_address">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
</ul>
<p>Returns the bound <code>address</code>, the address <code>family</code> name, and <code>port</code> of the server
as reported by the operating system if listening on an IP socket
(useful to find which port was assigned when getting an OS-assigned address):
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code>.</p>
<p>For a server listening on a pipe or Unix domain socket, the name is returned
as a string.</p>
<pre><code class="language-js">const server = net.createServer((socket) => {
  socket.end('goodbye\n');
}).on('error', (err) => {
  // Handle errors here.
  throw err;
});

// Grab an arbitrary unused port.
server.listen(() => {
  console.log('opened server on', server.address());
});
</code></pre>
<p><code>server.address()</code> returns <code>null</code> before the <code>'listening'</code> event has been
emitted or after calling <code>server.close()</code>.</p>
<h3><code>server.close([callback])</code><span><a class="mark" href="#net_server_close_callback" id="net_server_close_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called when the server is closed.</li>
<li>Returns: <a href="#net_class_net_server" class="type">&#x3C;net.Server></a></li>
</ul>
<p>Stops the server from accepting new connections and keeps existing
connections. This function is asynchronous, the server is finally closed
when all connections are ended and the server emits a <a href="#net_event_close"><code>'close'</code></a> event.
The optional <code>callback</code> will be called once the <code>'close'</code> event occurs. Unlike
that event, it will be called with an <code>Error</code> as its only argument if the server
was not open when it was closed.</p>
<h3><code>server.connections</code><span><a class="mark" href="#net_server_connections" id="net_server_connections">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.2.0</span><span>Deprecated since: v0.9.7</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#net_server_getconnections_callback"><code>server.getConnections()</code></a> instead.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
</ul>
<p>The number of concurrent connections on the server.</p>
<p>This becomes <code>null</code> when sending a socket to a child with
<a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>. To poll forks and get current number of active
connections, use asynchronous <a href="#net_server_getconnections_callback"><code>server.getConnections()</code></a> instead.</p>
<h3><code>server.getConnections(callback)</code><span><a class="mark" href="#net_server_getconnections_callback" id="net_server_getconnections_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.7</span>
</div>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#net_class_net_server" class="type">&#x3C;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><code>server.listen()</code><span><a class="mark" href="#net_server_listen" id="net_server_listen">#</a></span></h3>
<p>Start a server listening for connections. A <code>net.Server</code> can be a TCP or
an <a href="#net_ipc_support">IPC</a> server depending on what it listens to.</p>
<p>Possible signatures:</p>
<ul>
<li><a href="#net_server_listen_handle_backlog_callback"><code>server.listen(handle[, backlog][, callback])</code></a></li>
<li><a href="#net_server_listen_options_callback"><code>server.listen(options[, callback])</code></a></li>
<li><a href="#net_server_listen_path_backlog_callback"><code>server.listen(path[, backlog][, callback])</code></a>
for <a href="#net_ipc_support">IPC</a> servers</li>
<li>
<a href="#net_server_listen_port_host_backlog_callback">
<code>server.listen([port[, host[, backlog]]][, callback])</code></a>
for TCP servers
</li>
</ul>
<p>This function is asynchronous. When the server starts listening, the
<a href="#net_event_listening"><code>'listening'</code></a> event will be emitted. The last parameter <code>callback</code>
will be added as a listener for the <a href="#net_event_listening"><code>'listening'</code></a> event.</p>
<p>All <code>listen()</code> methods can take a <code>backlog</code> parameter to specify the maximum
length of the queue of pending connections. The actual length will be determined
by the OS through sysctl settings such as <code>tcp_max_syn_backlog</code> and <code>somaxconn</code>
on Linux. The default value of this parameter is 511 (not 512).</p>
<p>All <a href="#net_class_net_socket"><code>net.Socket</code></a> are set to <code>SO_REUSEADDR</code> (see <a href="http://man7.org/linux/man-pages/man7/socket.7.html"><code>socket(7)</code></a> for
details).</p>
<p>The <code>server.listen()</code> method can be called again if and only if there was an
error during the first <code>server.listen()</code> call or <code>server.close()</code> has been
called. Otherwise, an <code>ERR_SERVER_ALREADY_LISTEN</code> error will be thrown.</p>
<p>One of the most common errors raised when listening is <code>EADDRINUSE</code>.
This happens when another server is already listening on the requested
<code>port</code>/<code>path</code>/<code>handle</code>. One way to handle this would be to retry
after a certain amount of time:</p>
<pre><code class="language-js">server.on('error', (e) => {
  if (e.code === 'EADDRINUSE') {
    console.log('Address in use, retrying...');
    setTimeout(() => {
      server.close();
      server.listen(PORT, HOST);
    }, 1000);
  }
});
</code></pre>
<h4><code>server.listen(handle[, backlog][, callback])</code><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">&#x3C;Object></a></li>
<li><code>backlog</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a> functions</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#net_class_net_server" class="type">&#x3C;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><code>server.listen(options[, callback])</code><span><a class="mark" href="#net_server_listen_options_callback" id="net_server_listen_options_callback">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.4.0</td>
<td><p>The <code>ipv6Only</code> option is supported.</p></td></tr>
<tr><td>v0.11.14</td>
<td><p><span>Added in: v0.11.14</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Required. Supports the following properties:</p>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;number></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a>
functions.</li>
<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>readableAll</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> For IPC servers makes the pipe readable
for all users. <strong>Default:</strong> <code>false</code>.</li>
<li><code>writableAll</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> For IPC servers makes the pipe writable
for all users. <strong>Default:</strong> <code>false</code>.</li>
<li><code>ipv6Only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> For TCP servers, setting <code>ipv6Only</code> to <code>true</code> will
disable dual-stack support, i.e., binding to host <code>::</code> won't make
<code>0.0.0.0</code> be bound. <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">&#x3C;Function></a>
functions.</li>
<li>Returns: <a href="#net_class_net_server" class="type">&#x3C;net.Server></a></li>
</ul>
<p>If <code>port</code> is specified, it behaves the same as
<a href="#net_server_listen_port_host_backlog_callback">
<code>server.listen([port[, host[, backlog]]][, callback])</code></a>.
Otherwise, if <code>path</code> is specified, it behaves the same as
<a href="#net_server_listen_path_backlog_callback"><code>server.listen(path[, backlog][, callback])</code></a>.
If none of them is specified, an error will be thrown.</p>
<p>If <code>exclusive</code> is <code>false</code> (default), then cluster workers will use the same
underlying handle, allowing connection handling duties to be shared. When
<code>exclusive</code> is <code>true</code>, the handle is not shared, and attempted port sharing
results in an error. An example which listens on an exclusive port is
shown below.</p>
<pre><code class="language-js">server.listen({
  host: 'localhost',
  port: 80,
  exclusive: true
});
</code></pre>
<p>Starting an IPC server as root may cause the server path to be inaccessible for
unprivileged users. Using <code>readableAll</code> and <code>writableAll</code> will make the server
accessible for all users.</p>
<h4><code>server.listen(path[, backlog][, callback])</code><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">&#x3C;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">&#x3C;number></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a> functions.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>.</li>
<li>Returns: <a href="#net_class_net_server" class="type">&#x3C;net.Server></a></li>
</ul>
<p>Start an <a href="#net_ipc_support">IPC</a> server listening for connections on the given <code>path</code>.</p>
<h4><code>server.listen([port[, host[, backlog]]][, callback])</code><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">&#x3C;number></a></li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>backlog</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Common parameter of <a href="#net_server_listen"><code>server.listen()</code></a> functions.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>.</li>
<li>Returns: <a href="#net_class_net_server" class="type">&#x3C;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><code>server.listening</code><span><a class="mark" href="#net_server_listening" id="net_server_listening">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v5.7.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Indicates whether or not the server is listening for connections.</li>
</ul>
<h3><code>server.maxConnections</code><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>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Set this property to reject connections when the server's connection count gets
high.</p>
<p>It is not recommended to use this option once a socket has been sent to a child
with <a href="#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>.</p>
<h3><code>server.ref()</code><span><a class="mark" href="#net_server_ref" id="net_server_ref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#net_class_net_server" class="type">&#x3C;net.Server></a></li>
</ul>
<p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref</code>ed server will
<em>not</em> let the program exit if it's the only server left (the default behavior).
If the server is <code>ref</code>ed calling <code>ref()</code> again will have no effect.</p>
<h3><code>server.unref()</code><span><a class="mark" href="#net_server_unref" id="net_server_unref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#net_class_net_server" class="type">&#x3C;net.Server></a></li>
</ul>
<p>Calling <code>unref()</code> on a server will allow the program to exit if this is the only
active server in the event system. If the server is already <code>unref</code>ed calling
<code>unref()</code> again will have no effect.</p>
<h2>Class: <code>net.Socket</code><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>
<ul>
<li>Extends: <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<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). It is also
an <a href="#events_class_eventemitter"><code>EventEmitter</code></a>.</p>
<p>A <code>net.Socket</code> can be created by the user and used directly to interact with
a server. For example, it is returned by <a href="#net_net_createconnection"><code>net.createConnection()</code></a>,
so the user can use it to talk to the server.</p>
<p>It can also be created by Node.js and passed to the user when a connection
is received. For example, it is passed to the listeners of a
<a href="#net_event_connection"><code>'connection'</code></a> event emitted on a <a href="#net_class_net_server"><code>net.Server</code></a>, so the user can use
it to interact with the client.</p>
<h3><code>new net.Socket([options])</code><span><a class="mark" href="#net_new_net_socket_options" id="net_new_net_socket_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Available options are:</p>
<ul>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;boolean></a> Indicates whether half-opened TCP connections
are allowed. See <a href="#net_net_createserver_options_connectionlistener"><code>net.createServer()</code></a> and the <a href="#net_event_end"><code>'end'</code></a> event
for details. <strong>Default:</strong> <code>false</code>.</li>
<li><code>readable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;boolean></a> Allow writes on the socket when an <code>fd</code> is passed,
otherwise ignored. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Creates a new socket object.</p>
<p>The newly created socket can be either a TCP socket or a streaming <a href="#net_ipc_support">IPC</a>
endpoint, depending on what it <a href="#net_socket_connect"><code>connect()</code></a> to.</p>
<h3>Event: <code>'close'</code><span><a class="mark" href="#net_event_close_1" id="net_event_close_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>hadError</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if the socket had a transmission error.</li>
</ul>
<p>Emitted once the socket is fully closed. The argument <code>hadError</code> is a boolean
which says if the socket was closed due to a transmission error.</p>
<h3>Event: <code>'connect'</code><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: <code>'data'</code><span><a class="mark" href="#net_event_data" id="net_event_data">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Emitted when data is received. The argument <code>data</code> will be a <code>Buffer</code> or
<code>String</code>. Encoding of data is set by <a href="#net_socket_setencoding_encoding"><code>socket.setEncoding()</code></a>.</p>
<p>The data will be lost if there is no listener when a <code>Socket</code>
emits a <code>'data'</code> event.</p>
<h3>Event: <code>'drain'</code><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: <code>'end'</code><span><a class="mark" href="#net_event_end" id="net_event_end">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<p>Emitted when the other end of the socket sends a FIN packet, thus ending the
readable side of the socket.</p>
<p>By default (<code>allowHalfOpen</code> is <code>false</code>) the socket will send a FIN packet
back and destroy its file descriptor once it has written out its pending
write queue. However, if <code>allowHalfOpen</code> is set to <code>true</code>, the socket will
not automatically <a href="#net_socket_end_data_encoding_callback"><code>end()</code></a> its writable side, allowing the
user to write arbitrary amounts of data. The user must call
<a href="#net_socket_end_data_encoding_callback"><code>end()</code></a> explicitly to close the connection (i.e. sending a
FIN packet back).</p>
<h3>Event: <code>'error'</code><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">&#x3C;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: <code>'lookup'</code><span><a class="mark" href="#net_event_lookup" id="net_event_lookup">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.10.0</td>
<td><p>The <code>host</code> parameter is supported now.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p><span>Added in: v0.11.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Emitted after resolving the host name 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">&#x3C;Error></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> The error object. See <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> The address type. See <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The host name.</li>
</ul>
<h3>Event: <code>'ready'</code><span><a class="mark" href="#net_event_ready" id="net_event_ready">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.11.0</span>
</div>
<p>Emitted when a socket is ready to be used.</p>
<p>Triggered immediately after <code>'connect'</code>.</p>
<h3>Event: <code>'timeout'</code><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><code>socket.address()</code><span><a class="mark" href="#net_socket_address" id="net_socket_address">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns the bound <code>address</code>, the address <code>family</code> name and <code>port</code> of the
socket as reported by the operating system:
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code></p>
<h3><code>socket.bufferSize</code><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>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>This property shows the number of characters buffered for writing. The buffer
may contain strings whose length after encoding is not yet known. So this number
is only an approximation of the number of bytes in the buffer.</p>
<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.</p>
<p>The consequence of this internal buffering is that memory may grow.
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><code>socket.bytesRead</code><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>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>The amount of received bytes.</p>
<h3><code>socket.bytesWritten</code><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>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>The amount of bytes sent.</p>
<h3><code>socket.connect()</code><span><a class="mark" href="#net_socket_connect" id="net_socket_connect">#</a></span></h3>
<p>Initiate a connection on a given socket.</p>
<p>Possible signatures:</p>
<ul>
<li><a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a></li>
<li><a href="#net_socket_connect_path_connectlistener"><code>socket.connect(path[, connectListener])</code></a>
for <a href="#net_ipc_support">IPC</a> connections.</li>
<li><a href="#net_socket_connect_port_host_connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>
for TCP connections.</li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;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>
<p>This function should only be used for reconnecting a socket after
<code>'close'</code> has been emitted or otherwise it may lead to undefined
behavior.</p>
<h4><code>socket.connect(options[, connectListener])</code><span><a class="mark" href="#net_socket_connect_options_connectlistener" id="net_socket_connect_options_connectlistener">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.10.0</td>
<td><p>Added <code>onread</code> option.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>hints</code> option defaults to <code>0</code> in all cases now. Previously, in the absence of the <code>family</code> option it would default to <code>dns.ADDRCONFIG | dns.V4MAPPED</code>.</p></td></tr>
<tr><td>v5.11.0</td>
<td><p>The <code>hints</code> option is supported now.</p></td></tr>
<tr><td>v0.1.90</td>
<td><p><span>Added in: v0.1.90</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Common parameter of <a href="#net_socket_connect"><code>socket.connect()</code></a>
methods. Will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once.</li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;number></a>: Version of IP stack. Must be <code>4</code>, <code>6</code>, or <code>0</code>. The value
<code>0</code> indicates that both IPv4 and IPv6 addresses are allowed. <strong>Default:</strong> <code>0</code>.</li>
<li><code>hints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Optional <a href="#dns_supported_getaddrinfo_flags"><code>dns.lookup()</code> hints</a>.</li>
<li><code>lookup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Custom lookup function. <strong>Default:</strong> <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li>
</ul>
<p>For <a href="#net_ipc_support">IPC</a> connections, available <code>options</code> are:</p>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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>For both types, available <code>options</code> include:</p>
<ul>
<li>
<p><code>onread</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> If specified, incoming data is stored in a single <code>buffer</code>
and passed to the supplied <code>callback</code> when data arrives on the socket.
This will cause the streaming functionality to not provide any data.
The socket will emit events like <code>'error'</code>, <code>'end'</code>, and <code>'close'</code>
as usual. Methods like <code>pause()</code> and <code>resume()</code> will also behave as
expected.</p>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Either a reusable chunk of memory to
use for storing incoming data or a function that returns such.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> This function is called for every chunk of incoming
data. Two arguments are passed to it: the number of bytes written to
<code>buffer</code> and a reference to <code>buffer</code>. Return <code>false</code> from this function to
implicitly <code>pause()</code> the socket. This function will be executed in the
global context.</li>
</ul>
</li>
</ul>
<p>Following is an example of a client using the <code>onread</code> option:</p>
<pre><code class="language-js">const net = require('net');
net.connect({
  port: 80,
  onread: {
    // Reuses a 4KiB Buffer for every read from the socket.
    buffer: Buffer.alloc(4 * 1024),
    callback: function(nread, buf) {
      // Received data is available in `buf` from 0 to `nread`.
      console.log(buf.toString('utf8', 0, nread));
    }
  }
});
</code></pre>
<h4><code>socket.connect(path[, connectListener])</code><span><a class="mark" href="#net_socket_connect_path_connectlistener" id="net_socket_connect_path_connectlistener">#</a></span></h4>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Function></a> Common parameter of <a href="#net_socket_connect"><code>socket.connect()</code></a>
methods. Will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once.</li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Initiate an <a href="#net_ipc_support">IPC</a> connection on the given socket.</p>
<p>Alias to
<a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a>
called with <code>{ path: path }</code> as <code>options</code>.</p>
<h4><code>socket.connect(port[, host][, connectListener])</code><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">&#x3C;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">&#x3C;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">&#x3C;Function></a> Common parameter of <a href="#net_socket_connect"><code>socket.connect()</code></a>
methods. Will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event once.</li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Initiate a TCP connection on the given socket.</p>
<p>Alias to
<a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a>
called with <code>{port: port, host: host}</code> as <code>options</code>.</p>
<h3><code>socket.connecting</code><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>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>If <code>true</code>,
<a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a> was
called and has not yet finished. It will stay <code>true</code> until the socket becomes
connected, then it is set to <code>false</code> and the <code>'connect'</code> event is emitted. Note
that the
<a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options[, connectListener])</code></a>
callback is a listener for the <code>'connect'</code> event.</p>
<h3><code>socket.destroy([error])</code><span><a class="mark" href="#net_socket_destroy_error" id="net_socket_destroy_error">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Ensures that no more I/O activity happens on this socket.
Destroys the stream and closes the connection.</p>
<p>See <a href="#stream_writable_destroy_error"><code>writable.destroy()</code></a> for further details.</p>
<h3><code>socket.destroyed</code><span><a class="mark" href="#net_socket_destroyed" id="net_socket_destroyed">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Indicates if the connection is destroyed or not. Once a
connection is destroyed no further data can be transferred using it.</li>
</ul>
<p>See <a href="#stream_writable_destroyed"><code>writable.destroyed</code></a> for further details.</p>
<h3><code>socket.end([data[, encoding]][, callback])</code><span><a class="mark" href="#net_socket_end_data_encoding_callback" id="net_socket_end_data_encoding_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Only used when data is <code>string</code>. <strong>Default:</strong> <code>'utf8'</code>.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Optional callback for when the socket is finished.</li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;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>See <a href="#stream_writable_end_chunk_encoding_callback"><code>writable.end()</code></a> for further details.</p>
<h3><code>socket.localAddress</code><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>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<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><code>socket.localPort</code><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>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>The numeric representation of the local port. For example, <code>80</code> or <code>21</code>.</p>
<h3><code>socket.pause()</code><span><a class="mark" href="#net_socket_pause" id="net_socket_pause">#</a></span></h3>
<ul>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Pauses the reading of data. That is, <a href="#net_event_data"><code>'data'</code></a> events will not be emitted.
Useful to throttle back an upload.</p>
<h3><code>socket.pending</code><span><a class="mark" href="#net_socket_pending" id="net_socket_pending">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.2.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>This is <code>true</code> if the socket is not connected yet, either because <code>.connect()</code>
has not yet been called or because it is still in the process of connecting
(see <a href="#net_socket_connecting"><code>socket.connecting</code></a>).</p>
<h3><code>socket.ref()</code><span><a class="mark" href="#net_socket_ref" id="net_socket_ref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref</code>ed socket will
<em>not</em> let the program exit if it's the only socket left (the default behavior).
If the socket is <code>ref</code>ed calling <code>ref</code> again will have no effect.</p>
<h3><code>socket.remoteAddress</code><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>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<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><code>socket.remoteFamily</code><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>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The string representation of the remote IP family. <code>'IPv4'</code> or <code>'IPv6'</code>.</p>
<h3><code>socket.remotePort</code><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>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>The numeric representation of the remote port. For example, <code>80</code> or <code>21</code>.</p>
<h3><code>socket.resume()</code><span><a class="mark" href="#net_socket_resume" id="net_socket_resume">#</a></span></h3>
<ul>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Resumes reading after a call to <a href="#net_socket_pause"><code>socket.pause()</code></a>.</p>
<h3><code>socket.setEncoding([encoding])</code><span><a class="mark" href="#net_socket_setencoding_encoding" id="net_socket_setencoding_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Set the encoding for the socket as a <a href="#stream_class_stream_readable">Readable Stream</a>. See
<a href="#stream_readable_setencoding_encoding"><code>readable.setEncoding()</code></a> for more information.</p>
<h3><code>socket.setKeepAlive([enable][, initialDelay])</code><span><a class="mark" href="#net_socket_setkeepalive_enable_initialdelay" id="net_socket_setkeepalive_enable_initialdelay">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div>
<ul>
<li><code>enable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
<li><code>initialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> <strong>Default:</strong> <code>0</code></li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Enable/disable keep-alive functionality, and optionally set the initial
delay before the first keepalive probe is sent on an idle socket.</p>
<p>Set <code>initialDelay</code> (in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting <code>0</code> for
<code>initialDelay</code> will leave the value unchanged from the default
(or previous) setting.</p>
<h3><code>socket.setNoDelay([noDelay])</code><span><a class="mark" href="#net_socket_setnodelay_nodelay" id="net_socket_setnodelay_nodelay">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>noDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>true</code></li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Enable/disable the use of Nagle's algorithm.</p>
<p>When a TCP connection is created, it will have Nagle's algorithm enabled.</p>
<p>Nagle's algorithm delays data before it is sent via the network. It attempts
to optimize throughput at the expense of latency.</p>
<p>Passing <code>true</code> for <code>noDelay</code> or not passing an argument will disable Nagle's
algorithm for the socket. Passing <code>false</code> for <code>noDelay</code> will enable Nagle's
algorithm.</p>
<h3><code>socket.setTimeout(timeout[, callback])</code><span><a class="mark" href="#net_socket_settimeout_timeout_callback" id="net_socket_settimeout_timeout_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Sets the socket to timeout after <code>timeout</code> milliseconds of inactivity on
the socket. By default <code>net.Socket</code> do not have a timeout.</p>
<p>When an idle timeout is triggered the socket will receive a <a href="#net_event_timeout"><code>'timeout'</code></a>
event but the connection will not be severed. The user must manually call
<a href="#net_socket_end_data_encoding_callback"><code>socket.end()</code></a> or <a href="#net_socket_destroy_error"><code>socket.destroy()</code></a> to end the connection.</p>
<pre><code class="language-js">socket.setTimeout(3000);
socket.on('timeout', () => {
  console.log('socket timeout');
  socket.end();
});
</code></pre>
<p>If <code>timeout</code> is 0, then the existing idle timeout is disabled.</p>
<p>The optional <code>callback</code> parameter will be added as a one-time listener for the
<a href="#net_event_timeout"><code>'timeout'</code></a> event.</p>
<h3><code>socket.unref()</code><span><a class="mark" href="#net_socket_unref" id="net_socket_unref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Calling <code>unref()</code> on a socket will allow the program to exit if this is the only
active socket in the event system. If the socket is already <code>unref</code>ed calling
<code>unref()</code> again will have no effect.</p>
<h3><code>socket.write(data[, encoding][, callback])</code><span><a class="mark" href="#net_socket_write_data_encoding_callback" id="net_socket_write_data_encoding_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Only used when data is <code>string</code>. <strong>Default:</strong> <code>utf8</code>.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Sends data on the socket. The second parameter specifies the encoding in the
case of a string. It defaults to UTF8 encoding.</p>
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
buffer. Returns <code>false</code> if all or part of the data was queued in user memory.
<a href="#net_event_drain"><code>'drain'</code></a> will be emitted when the buffer is again free.</p>
<p>The optional <code>callback</code> parameter will be executed when the data is finally
written out, which may not be immediately.</p>
<p>See <code>Writable</code> stream <a href="#stream_writable_write_chunk_encoding_callback"><code>write()</code></a> method for more
information.</p>
<h2><code>net.connect()</code><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><code>net.connect(options[, connectListener])</code><span><a class="mark" href="#net_net_connect_options_connectlistener" id="net_net_connect_options_connectlistener">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Alias to
<a href="#net_net_createconnection_options_connectlistener"><code>net.createConnection(options[, connectListener])</code></a>.</p>
<h3><code>net.connect(path[, connectListener])</code><span><a class="mark" href="#net_net_connect_path_connectlistener" id="net_net_connect_path_connectlistener">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Alias to
<a href="#net_net_createconnection_path_connectlistener"><code>net.createConnection(path[, connectListener])</code></a>.</p>
<h3><code>net.connect(port[, host][, connectListener])</code><span><a class="mark" href="#net_net_connect_port_host_connectlistener" id="net_net_connect_port_host_connectlistener">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>connectListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Alias to
<a href="#net_net_createconnection_port_host_connectlistener"><code>net.createConnection(port[, host][, connectListener])</code></a>.</p>
<h2><code>net.createConnection()</code><span><a class="mark" href="#net_net_createconnection" id="net_net_createconnection">#</a></span></h2>
<p>A factory function, which creates a new <a href="#net_class_net_socket"><code>net.Socket</code></a>,
immediately initiates connection with <a href="#net_socket_connect"><code>socket.connect()</code></a>,
then returns the <code>net.Socket</code> that starts the connection.</p>
<p>When the connection is established, a <a href="#net_event_connect"><code>'connect'</code></a> event will be emitted
on the returned socket. The last parameter <code>connectListener</code>, if supplied,
will be added as a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event <strong>once</strong>.</p>
<p>Possible signatures:</p>
<ul>
<li><a href="#net_net_createconnection_options_connectlistener"><code>net.createConnection(options[, connectListener])</code></a></li>
<li><a href="#net_net_createconnection_path_connectlistener"><code>net.createConnection(path[, connectListener])</code></a>
for <a href="#net_ipc_support">IPC</a> connections.</li>
<li><a href="#net_net_createconnection_port_host_connectlistener"><code>net.createConnection(port[, host][, connectListener])</code></a>
for TCP connections.</li>
</ul>
<p>The <a href="#net_net_connect"><code>net.connect()</code></a> function is an alias to this function.</p>
<h3><code>net.createConnection(options[, connectListener])</code><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">&#x3C;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">&#x3C;Function></a> Common parameter of the
<a href="#net_net_createconnection"><code>net.createConnection()</code></a> functions. If supplied, will be added as
a listener for the <a href="#net_event_connect"><code>'connect'</code></a> event on the returned socket once.</li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;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">&#x3C;number></a> If set, will be used to call
<a href="#net_socket_settimeout_timeout_callback"><code>socket.setTimeout(timeout)</code></a> after the socket is created, but before
it starts the connection.</li>
</ul>
<p>Following is an example of a client of the echo server described
in the <a href="#net_net_createserver_options_connectionlistener"><code>net.createServer()</code></a> section:</p>
<pre><code class="language-js">const net = require('net');
const client = net.createConnection({ port: 8124 }, () => {
  // 'connect' listener.
  console.log('connected to server!');
  client.write('world!\r\n');
});
client.on('data', (data) => {
  console.log(data.toString());
  client.end();
});
client.on('end', () => {
  console.log('disconnected from server');
});
</code></pre>
<p>To connect on the socket <code>/tmp/echo.sock</code>:</p>
<pre><code class="language-js">const client = net.createConnection({ path: '/tmp/echo.sock' });
</code></pre>
<h3><code>net.createConnection(path[, connectListener])</code><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">&#x3C;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">&#x3C;Function></a> Common parameter of the
<a href="#net_net_createconnection"><code>net.createConnection()</code></a> functions, an "once" listener for the
<code>'connect'</code> event on the initiating socket. Will be passed to
<a href="#net_socket_connect_path_connectlistener"><code>socket.connect(path[, connectListener])</code></a>.</li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The newly created socket used to start the connection.</li>
</ul>
<p>Initiates an <a href="#net_ipc_support">IPC</a> connection.</p>
<p>This function creates a new <a href="#net_class_net_socket"><code>net.Socket</code></a> with all options set to default,
immediately initiates connection with
<a href="#net_socket_connect_path_connectlistener"><code>socket.connect(path[, connectListener])</code></a>,
then returns the <code>net.Socket</code> that starts the connection.</p>
<h3><code>net.createConnection(port[, host][, connectListener])</code><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">&#x3C;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">&#x3C;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">&#x3C;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(port[, host][, connectListener])</code></a>.</li>
<li>Returns: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> The newly created socket used to start the connection.</li>
</ul>
<p>Initiates a TCP connection.</p>
<p>This function creates a new <a href="#net_class_net_socket"><code>net.Socket</code></a> with all options set to default,
immediately initiates connection with
<a href="#net_socket_connect_port_host_connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>,
then returns the <code>net.Socket</code> that starts the connection.</p>
<h2><code>net.createServer([options][, connectionListener])</code><span><a class="mark" href="#net_net_createserver_options_connectionlistener" id="net_net_createserver_options_connectionlistener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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">&#x3C;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">&#x3C;Function></a> Automatically set as a listener for the
<a href="#net_event_connection"><code>'connection'</code></a> event.</li>
<li>Returns: <a href="#net_class_net_server" class="type">&#x3C;net.Server></a></li>
</ul>
<p>Creates a new TCP or <a href="#net_ipc_support">IPC</a> server.</p>
<p>If <code>allowHalfOpen</code> is set to <code>true</code>, when the other end of the socket
sends a FIN packet, the server will only send a FIN packet back when
<a href="#net_socket_end_data_encoding_callback"><code>socket.end()</code></a> is explicitly called, until then the connection is
half-closed (non-readable but still writable). See <a href="#net_event_end"><code>'end'</code></a> event
and <a href="https://tools.ietf.org/html/rfc1122">RFC 1122</a> (section 4.2.2.13) for more information.</p>
<p>If <code>pauseOnConnect</code> is set to <code>true</code>, then the socket associated with each
incoming connection will be paused, and no data will be read from its handle.
This allows connections to be passed between processes without any data being
read by the original process. To begin reading data from a paused socket, call
<a href="#net_socket_resume"><code>socket.resume()</code></a>.</p>
<p>The server can be a TCP server or an <a href="#net_ipc_support">IPC</a> server, depending on what it
<a href="#net_server_listen"><code>listen()</code></a> to.</p>
<p>Here is an example of an TCP echo server which listens for connections
on port 8124:</p>
<pre><code class="language-js">const net = require('net');
const server = net.createServer((c) => {
  // 'connection' listener.
  console.log('client connected');
  c.on('end', () => {
    console.log('client disconnected');
  });
  c.write('hello\r\n');
  c.pipe(c);
});
server.on('error', (err) => {
  throw err;
});
server.listen(8124, () => {
  console.log('server bound');
});
</code></pre>
<p>Test this by using <code>telnet</code>:</p>
<pre><code class="language-console">$ telnet localhost 8124
</code></pre>
<p>To listen on the socket <code>/tmp/echo.sock</code>:</p>
<pre><code class="language-js">server.listen('/tmp/echo.sock', () => {
  console.log('server bound');
});
</code></pre>
<p>Use <code>nc</code> to connect to a Unix domain socket server:</p>
<pre><code class="language-console">$ nc -U /tmp/echo.sock
</code></pre>
<h2><code>net.isIP(input)</code><span><a class="mark" href="#net_net_isip_input" id="net_net_isip_input">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Tests if input is an IP address. Returns <code>0</code> for invalid strings,
returns <code>4</code> for IP version 4 addresses, and returns <code>6</code> for IP version 6
addresses.</p>
<h2><code>net.isIPv4(input)</code><span><a class="mark" href="#net_net_isipv4_input" id="net_net_isipv4_input">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if input is a version 4 IP address, otherwise returns <code>false</code>.</p>
<h2><code>net.isIPv6(input)</code><span><a class="mark" href="#net_net_isipv6_input" id="net_net_isipv6_input">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if input is a version 6 IP address, otherwise returns <code>false</code>.</p>
<h1>OS<span><a class="mark" href="#os_os" id="os_os">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>os</code> module provides operating system-related utility methods and
properties. It can be accessed using:</p>
<pre><code class="language-js">const os = require('os');
</code></pre>
<h2><code>os.EOL</code><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">&#x3C;string></a></li>
</ul>
<p>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><code>os.arch()</code><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">&#x3C;string></a></li>
</ul>
<p>Returns the operating system CPU architecture for which the Node.js binary was
compiled. 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>The return value is equivalent to <a href="#process_process_arch"><code>process.arch</code></a>.</p>
<h2><code>os.constants</code><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">&#x3C;Object></a></li>
</ul>
<p>Contains commonly used operating system-specific constants for error codes,
process signals, and so on. The specific constants defined are described in
<a href="#os_os_constants_1">OS constants</a>.</p>
<h2><code>os.cpus()</code><span><a class="mark" href="#os_os_cpus" id="os_os_cpus">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
<p>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">&#x3C;string></a></li>
<li><code>speed</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> (in MHz)</li>
<li>
<p><code>times</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>user</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;number></a> The number of milliseconds the CPU has spent in irq mode.</li>
</ul>
</li>
</ul>
<!-- eslint-disable semi -->
<pre><code class="language-js">[
  {
    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
    speed: 2926,
    times: {
      user: 252020,
      nice: 0,
      sys: 30340,
      idle: 1070356870,
      irq: 0
    }
  },
  {
    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
    speed: 2926,
    times: {
      user: 306960,
      nice: 0,
      sys: 26980,
      idle: 1071569080,
      irq: 0
    }
  },
  {
    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
    speed: 2926,
    times: {
      user: 248450,
      nice: 0,
      sys: 21750,
      idle: 1070919370,
      irq: 0
    }
  },
  {
    model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',
    speed: 2926,
    times: {
      user: 256880,
      nice: 0,
      sys: 19430,
      idle: 1070905480,
      irq: 20
    }
  }
]
</code></pre>
<p><code>nice</code> values are POSIX-only. On Windows, the <code>nice</code> values of all processors
are always 0.</p>
<h2><code>os.endianness()</code><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">&#x3C;string></a></li>
</ul>
<p>Returns a string identifying the endianness of the CPU for which the Node.js
binary was compiled.</p>
<p>Possible values are <code>'BE'</code> for big endian and <code>'LE'</code> for little endian.</p>
<h2><code>os.freemem()</code><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">&#x3C;integer></a></li>
</ul>
<p>Returns the amount of free system memory in bytes as an integer.</p>
<h2><code>os.getPriority([pid])</code><span><a class="mark" href="#os_os_getpriority_pid" id="os_os_getpriority_pid">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The process ID to retrieve scheduling priority for.
<strong>Default</strong> <code>0</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Returns the scheduling priority for the process specified by <code>pid</code>. If <code>pid</code> is
not provided or is <code>0</code>, the priority of the current process is returned.</p>
<h2><code>os.homedir()</code><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">&#x3C;string></a></li>
</ul>
<p>Returns the string path of the current user's home directory.</p>
<p>On POSIX, it uses the <code>$HOME</code> environment variable if defined. Otherwise it
uses the <a href="https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID">effective UID</a> to look up the user's home directory.</p>
<p>On Windows, it uses the <code>USERPROFILE</code> environment variable if defined.
Otherwise it uses the path to the profile directory of the current user.</p>
<h2><code>os.hostname()</code><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">&#x3C;string></a></li>
</ul>
<p>Returns the host name of the operating system as a string.</p>
<h2><code>os.loadavg()</code><span><a class="mark" href="#os_os_loadavg" id="os_os_loadavg">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number[]></a></li>
</ul>
<p>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.</p>
<p>The load average is a Unix-specific concept. On Windows, the return value is
always <code>[0, 0, 0]</code>.</p>
<h2><code>os.networkInterfaces()</code><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">&#x3C;Object></a></li>
</ul>
<p>Returns an object containing 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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;string></a> The assigned IPv4 or IPv6 address with the routing prefix
in CIDR notation. If the <code>netmask</code> is invalid, this property is set
to <code>null</code>.</li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
  lo: [
    {
      address: '127.0.0.1',
      netmask: '255.0.0.0',
      family: 'IPv4',
      mac: '00:00:00:00:00:00',
      internal: true,
      cidr: '127.0.0.1/8'
    },
    {
      address: '::1',
      netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
      family: 'IPv6',
      mac: '00:00:00:00:00:00',
      scopeid: 0,
      internal: true,
      cidr: '::1/128'
    }
  ],
  eth0: [
    {
      address: '192.168.1.108',
      netmask: '255.255.255.0',
      family: 'IPv4',
      mac: '01:02:03:0a:0b:0c',
      internal: false,
      cidr: '192.168.1.108/24'
    },
    {
      address: 'fe80::a00:27ff:fe4e:66a1',
      netmask: 'ffff:ffff:ffff:ffff::',
      family: 'IPv6',
      mac: '01:02:03:0a:0b:0c',
      scopeid: 1,
      internal: false,
      cidr: 'fe80::a00:27ff:fe4e:66a1/64'
    }
  ]
}
</code></pre>
<h2><code>os.platform()</code><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">&#x3C;string></a></li>
</ul>
<p>Returns a string identifying the operating system platform. The value is set
at compile time. Possible values are <code>'aix'</code>, <code>'darwin'</code>, <code>'freebsd'</code>,
<code>'linux'</code>, <code>'openbsd'</code>, <code>'sunos'</code>, and <code>'win32'</code>.</p>
<p>The return value is equivalent to <a href="#process_process_platform"><code>process.platform</code></a>.</p>
<p>The value <code>'android'</code> may also be returned if Node.js is built on the Android
operating system. <a href="https://github.com/nodejs/node/blob/master/BUILDING.md#androidandroid-based-devices-eg-firefox-os">Android support is experimental</a>.</p>
<h2><code>os.release()</code><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">&#x3C;string></a></li>
</ul>
<p>Returns the operating system as a string.</p>
<p>On POSIX systems, the operating system release is determined by calling
<a href="https://linux.die.net/man/3/uname"></a><a href="https://linux.die.net/man/3/uname"><code>uname(3)</code></a>. On Windows, <code>GetVersionExW()</code> is used. See
<a href="https://en.wikipedia.org/wiki/Uname#Examples">https://en.wikipedia.org/wiki/Uname#Examples</a> for more information.</p>
<h2><code>os.setPriority([pid, ]priority)</code><span><a class="mark" href="#os_os_setpriority_pid_priority" id="os_os_setpriority_pid_priority">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li><code>pid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The process ID to set scheduling priority for.
<strong>Default</strong> <code>0</code>.</li>
<li><code>priority</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The scheduling priority to assign to the process.</li>
</ul>
<p>Attempts to set the scheduling priority for the process specified by <code>pid</code>. If
<code>pid</code> is not provided or is <code>0</code>, the process ID of the current process is used.</p>
<p>The <code>priority</code> input must be an integer between <code>-20</code> (high priority) and <code>19</code>
(low priority). Due to differences between Unix priority levels and Windows
priority classes, <code>priority</code> is mapped to one of six priority constants in
<code>os.constants.priority</code>. When retrieving a process priority level, this range
mapping may cause the return value to be slightly different on Windows. To avoid
confusion, set <code>priority</code> to one of the priority constants.</p>
<p>On Windows, setting priority to <code>PRIORITY_HIGHEST</code> requires elevated user
privileges. Otherwise the set priority will be silently reduced to
<code>PRIORITY_HIGH</code>.</p>
<h2><code>os.tmpdir()</code><span><a class="mark" href="#os_os_tmpdir" id="os_os_tmpdir">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v2.0.0</td>
<td><p>This function is now cross-platform consistent and no longer returns a path with a trailing slash on any platform</p></td></tr>
<tr><td>v0.9.9</td>
<td><p><span>Added in: v0.9.9</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the operating system's default directory for temporary files as a
string.</p>
<h2><code>os.totalmem()</code><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">&#x3C;integer></a></li>
</ul>
<p>Returns the total amount of system memory in bytes as an integer.</p>
<h2><code>os.type()</code><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">&#x3C;string></a></li>
</ul>
<p>Returns the operating system name as returned by <a href="https://linux.die.net/man/3/uname"></a><a href="https://linux.die.net/man/3/uname"><code>uname(3)</code></a>. For example, it
returns <code>'Linux'</code> on Linux, <code>'Darwin'</code> on macOS, and <code>'Windows_NT'</code> on Windows.</p>
<p>See <a href="https://en.wikipedia.org/wiki/Uname#Examples">https://en.wikipedia.org/wiki/Uname#Examples</a> for additional information
about the output of running <a href="https://linux.die.net/man/3/uname"></a><a href="https://linux.die.net/man/3/uname"><code>uname(3)</code></a> on various operating systems.</p>
<h2><code>os.uptime()</code><span><a class="mark" href="#os_os_uptime" id="os_os_uptime">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The result of this function no longer contains a fraction component on Windows.</p></td></tr>
<tr><td>v0.3.3</td>
<td><p><span>Added in: v0.3.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Returns the system uptime in number of seconds.</p>
<h2><code>os.userInfo([options])</code><span><a class="mark" href="#os_os_userinfo_options" id="os_os_userinfo_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Object></a></li>
</ul>
<p>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
environment variables for the home directory before falling back to the
operating system response.</p>
<p>Throws a <a href="#errors_class_systemerror"><code>SystemError</code></a> if a user has no <code>username</code> or <code>homedir</code>.</p>
<h2><code>os.version()</code><span><a class="mark" href="#os_os_version" id="os_os_version">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li>Returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns a string identifying the kernel version.</p>
<p>On POSIX systems, the operating system release is determined by calling
<a href="https://linux.die.net/man/3/uname"></a><a href="https://linux.die.net/man/3/uname"><code>uname(3)</code></a>. On Windows, <code>RtlGetVersion()</code> is used, and if it is not available,
<code>GetVersionExW()</code> will be used. See
<a href="https://en.wikipedia.org/wiki/Uname#Examples">https://en.wikipedia.org/wiki/Uname#Examples</a> for more information.</p>
<h2>OS constants<span><a class="mark" href="#os_os_constants_1" id="os_os_constants_1">#</a></span></h2>
<p>The following constants are exported by <code>os.constants</code>.</p>
<p>Not all constants will be available on every operating system.</p>
<h3>Signal constants<span><a class="mark" href="#os_signal_constants" id="os_signal_constants">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.11.0</td>
<td><p>Added support for <code>SIGINFO</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The following signal constants are exported by <code>os.constants.signals</code>.</p>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>SIGHUP</code></td>
    <td>Sent to indicate when a controlling terminal is closed or a parent
    process exits.</td>
  </tr>
  <tr>
    <td><code>SIGINT</code></td>
    <td>Sent to indicate when a user wishes to interrupt a process
    (<code>(Ctrl+C)</code>).</td>
  </tr>
  <tr>
    <td><code>SIGQUIT</code></td>
    <td>Sent to indicate when a user wishes to terminate a process and perform a
    core dump.</td>
  </tr>
  <tr>
    <td><code>SIGILL</code></td>
    <td>Sent to a process to notify that it has attempted to perform an illegal,
    malformed, unknown, or privileged instruction.</td>
  </tr>
  <tr>
    <td><code>SIGTRAP</code></td>
    <td>Sent to a process when an exception has occurred.</td>
  </tr>
  <tr>
    <td><code>SIGABRT</code></td>
    <td>Sent to a process to request that it abort.</td>
  </tr>
  <tr>
    <td><code>SIGIOT</code></td>
    <td>Synonym for <code>SIGABRT</code></td>
  </tr>
  <tr>
    <td><code>SIGBUS</code></td>
    <td>Sent to a process to notify that it has caused a bus error.</td>
  </tr>
  <tr>
    <td><code>SIGFPE</code></td>
    <td>Sent to a process to notify that it has performed an illegal arithmetic
    operation.</td>
  </tr>
  <tr>
    <td><code>SIGKILL</code></td>
    <td>Sent to a process to terminate it immediately.</td>
  </tr>
  <tr>
    <td><code>SIGUSR1</code> <code>SIGUSR2</code></td>
    <td>Sent to a process to identify user-defined conditions.</td>
  </tr>
  <tr>
    <td><code>SIGSEGV</code></td>
    <td>Sent to a process to notify of a segmentation fault.</td>
  </tr>
  <tr>
    <td><code>SIGPIPE</code></td>
    <td>Sent to a process when it has attempted to write to a disconnected
    pipe.</td>
  </tr>
  <tr>
    <td><code>SIGALRM</code></td>
    <td>Sent to a process when a system timer elapses.</td>
  </tr>
  <tr>
    <td><code>SIGTERM</code></td>
    <td>Sent to a process to request termination.</td>
  </tr>
  <tr>
    <td><code>SIGCHLD</code></td>
    <td>Sent to a process when a child process terminates.</td>
  </tr>
  <tr>
    <td><code>SIGSTKFLT</code></td>
    <td>Sent to a process to indicate a stack fault on a coprocessor.</td>
  </tr>
  <tr>
    <td><code>SIGCONT</code></td>
    <td>Sent to instruct the operating system to continue a paused process.</td>
  </tr>
  <tr>
    <td><code>SIGSTOP</code></td>
    <td>Sent to instruct the operating system to halt a process.</td>
  </tr>
  <tr>
    <td><code>SIGTSTP</code></td>
    <td>Sent to a process to request it to stop.</td>
  </tr>
  <tr>
    <td><code>SIGBREAK</code></td>
    <td>Sent to indicate when a user wishes to interrupt a process.</td>
  </tr>
  <tr>
    <td><code>SIGTTIN</code></td>
    <td>Sent to a process when it reads from the TTY while in the
    background.</td>
  </tr>
  <tr>
    <td><code>SIGTTOU</code></td>
    <td>Sent to a process when it writes to the TTY while in the
    background.</td>
  </tr>
  <tr>
    <td><code>SIGURG</code></td>
    <td>Sent to a process when a socket has urgent data to read.</td>
  </tr>
  <tr>
    <td><code>SIGXCPU</code></td>
    <td>Sent to a process when it has exceeded its limit on CPU usage.</td>
  </tr>
  <tr>
    <td><code>SIGXFSZ</code></td>
    <td>Sent to a process when it grows a file larger than the maximum
    allowed.</td>
  </tr>
  <tr>
    <td><code>SIGVTALRM</code></td>
    <td>Sent to a process when a virtual timer has elapsed.</td>
  </tr>
  <tr>
    <td><code>SIGPROF</code></td>
    <td>Sent to a process when a system timer has elapsed.</td>
  </tr>
  <tr>
    <td><code>SIGWINCH</code></td>
    <td>Sent to a process when the controlling terminal has changed its
    size.</td>
  </tr>
  <tr>
    <td><code>SIGIO</code></td>
    <td>Sent to a process when I/O is available.</td>
  </tr>
  <tr>
    <td><code>SIGPOLL</code></td>
    <td>Synonym for <code>SIGIO</code></td>
  </tr>
  <tr>
    <td><code>SIGLOST</code></td>
    <td>Sent to a process when a file lock has been lost.</td>
  </tr>
  <tr>
    <td><code>SIGPWR</code></td>
    <td>Sent to a process to notify of a power failure.</td>
  </tr>
  <tr>
    <td><code>SIGINFO</code></td>
    <td>Synonym for <code>SIGPWR</code></td>
  </tr>
  <tr>
    <td><code>SIGSYS</code></td>
    <td>Sent to a process to notify of a bad argument.</td>
  </tr>
  <tr>
    <td><code>SIGUNUSED</code></td>
    <td>Synonym for <code>SIGSYS</code></td>
  </tr>
</tbody></table>
<h3>Error constants<span><a class="mark" href="#os_error_constants" id="os_error_constants">#</a></span></h3>
<p>The following error constants are exported by <code>os.constants.errno</code>.</p>
<h4>POSIX error constants<span><a class="mark" href="#os_posix_error_constants" id="os_posix_error_constants">#</a></span></h4>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>E2BIG</code></td>
    <td>Indicates that the list of arguments is longer than expected.</td>
  </tr>
  <tr>
    <td><code>EACCES</code></td>
    <td>Indicates that the operation did not have sufficient permissions.</td>
  </tr>
  <tr>
    <td><code>EADDRINUSE</code></td>
    <td>Indicates that the network address is already in use.</td>
  </tr>
  <tr>
    <td><code>EADDRNOTAVAIL</code></td>
    <td>Indicates that the network address is currently unavailable for
    use.</td>
  </tr>
  <tr>
    <td><code>EAFNOSUPPORT</code></td>
    <td>Indicates that the network address family is not supported.</td>
  </tr>
  <tr>
    <td><code>EAGAIN</code></td>
    <td>Indicates that there is 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. Although
    <code>ENOTSUP</code> and <code>EOPNOTSUPP</code> have the same value
    on Linux, according to POSIX.1 these error values should be distinct.)</td>
  </tr>
  <tr>
    <td><code>EOVERFLOW</code></td>
    <td>Indicates that a value is too large to be stored in a given data
    type.</td>
  </tr>
  <tr>
    <td><code>EPERM</code></td>
    <td>Indicates that the operation is not permitted.</td>
  </tr>
  <tr>
    <td><code>EPIPE</code></td>
    <td>Indicates a broken pipe.</td>
  </tr>
  <tr>
    <td><code>EPROTO</code></td>
    <td>Indicates a protocol error.</td>
  </tr>
  <tr>
    <td><code>EPROTONOSUPPORT</code></td>
    <td>Indicates that a protocol is not supported.</td>
  </tr>
  <tr>
    <td><code>EPROTOTYPE</code></td>
    <td>Indicates the wrong type of protocol for a socket.</td>
  </tr>
  <tr>
    <td><code>ERANGE</code></td>
    <td>Indicates that the results are too large.</td>
  </tr>
  <tr>
    <td><code>EROFS</code></td>
    <td>Indicates that the file system is read only.</td>
  </tr>
  <tr>
    <td><code>ESPIPE</code></td>
    <td>Indicates an invalid seek operation.</td>
  </tr>
  <tr>
    <td><code>ESRCH</code></td>
    <td>Indicates that there is no such process.</td>
  </tr>
  <tr>
    <td><code>ESTALE</code></td>
    <td>Indicates that the file handle is stale.</td>
  </tr>
  <tr>
    <td><code>ETIME</code></td>
    <td>Indicates an expired timer.</td>
  </tr>
  <tr>
    <td><code>ETIMEDOUT</code></td>
    <td>Indicates that the connection timed out.</td>
  </tr>
  <tr>
    <td><code>ETXTBSY</code></td>
    <td>Indicates that a text file is busy.</td>
  </tr>
  <tr>
    <td><code>EWOULDBLOCK</code></td>
    <td>Indicates that the operation would block.</td>
  </tr>
  <tr>
    <td><code>EXDEV</code></td>
    <td>Indicates an improper link.
  </td></tr>
</tbody></table>
<h4>Windows-specific error constants<span><a class="mark" href="#os_windows_specific_error_constants" id="os_windows_specific_error_constants">#</a></span></h4>
<p>The following error codes are specific to the Windows operating system.</p>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>WSAEINTR</code></td>
    <td>Indicates an interrupted function call.</td>
  </tr>
  <tr>
    <td><code>WSAEBADF</code></td>
    <td>Indicates an invalid file handle.</td>
  </tr>
  <tr>
    <td><code>WSAEACCES</code></td>
    <td>Indicates insufficient permissions to complete the operation.</td>
  </tr>
  <tr>
    <td><code>WSAEFAULT</code></td>
    <td>Indicates an invalid pointer address.</td>
  </tr>
  <tr>
    <td><code>WSAEINVAL</code></td>
    <td>Indicates that an invalid argument was passed.</td>
  </tr>
  <tr>
    <td><code>WSAEMFILE</code></td>
    <td>Indicates that there are too many open files.</td>
  </tr>
  <tr>
    <td><code>WSAEWOULDBLOCK</code></td>
    <td>Indicates that a resource is temporarily unavailable.</td>
  </tr>
  <tr>
    <td><code>WSAEINPROGRESS</code></td>
    <td>Indicates that an operation is currently in progress.</td>
  </tr>
  <tr>
    <td><code>WSAEALREADY</code></td>
    <td>Indicates that an operation is already in progress.</td>
  </tr>
  <tr>
    <td><code>WSAENOTSOCK</code></td>
    <td>Indicates that the resource is not a socket.</td>
  </tr>
  <tr>
    <td><code>WSAEDESTADDRREQ</code></td>
    <td>Indicates that a destination address is required.</td>
  </tr>
  <tr>
    <td><code>WSAEMSGSIZE</code></td>
    <td>Indicates that the message size is too long.</td>
  </tr>
  <tr>
    <td><code>WSAEPROTOTYPE</code></td>
    <td>Indicates the wrong protocol type for the socket.</td>
  </tr>
  <tr>
    <td><code>WSAENOPROTOOPT</code></td>
    <td>Indicates a bad protocol option.</td>
  </tr>
  <tr>
    <td><code>WSAEPROTONOSUPPORT</code></td>
    <td>Indicates that the protocol is not supported.</td>
  </tr>
  <tr>
    <td><code>WSAESOCKTNOSUPPORT</code></td>
    <td>Indicates that the socket type is not supported.</td>
  </tr>
  <tr>
    <td><code>WSAEOPNOTSUPP</code></td>
    <td>Indicates that the operation is not supported.</td>
  </tr>
  <tr>
    <td><code>WSAEPFNOSUPPORT</code></td>
    <td>Indicates that the protocol family is not supported.</td>
  </tr>
  <tr>
    <td><code>WSAEAFNOSUPPORT</code></td>
    <td>Indicates that the address family is not supported.</td>
  </tr>
  <tr>
    <td><code>WSAEADDRINUSE</code></td>
    <td>Indicates that the network address is already in use.</td>
  </tr>
  <tr>
    <td><code>WSAEADDRNOTAVAIL</code></td>
    <td>Indicates that the network address is not available.</td>
  </tr>
  <tr>
    <td><code>WSAENETDOWN</code></td>
    <td>Indicates that the network is down.</td>
  </tr>
  <tr>
    <td><code>WSAENETUNREACH</code></td>
    <td>Indicates that the network is unreachable.</td>
  </tr>
  <tr>
    <td><code>WSAENETRESET</code></td>
    <td>Indicates that the network connection has been reset.</td>
  </tr>
  <tr>
    <td><code>WSAECONNABORTED</code></td>
    <td>Indicates that the connection has been aborted.</td>
  </tr>
  <tr>
    <td><code>WSAECONNRESET</code></td>
    <td>Indicates that the connection has been reset by the peer.</td>
  </tr>
  <tr>
    <td><code>WSAENOBUFS</code></td>
    <td>Indicates that there is no buffer space available.</td>
  </tr>
  <tr>
    <td><code>WSAEISCONN</code></td>
    <td>Indicates that the socket is already connected.</td>
  </tr>
  <tr>
    <td><code>WSAENOTCONN</code></td>
    <td>Indicates that the socket is not connected.</td>
  </tr>
  <tr>
    <td><code>WSAESHUTDOWN</code></td>
    <td>Indicates that data cannot be sent after the socket has been
    shutdown.</td>
  </tr>
  <tr>
    <td><code>WSAETOOMANYREFS</code></td>
    <td>Indicates that there are too many references.</td>
  </tr>
  <tr>
    <td><code>WSAETIMEDOUT</code></td>
    <td>Indicates that the connection has timed out.</td>
  </tr>
  <tr>
    <td><code>WSAECONNREFUSED</code></td>
    <td>Indicates that the connection has been refused.</td>
  </tr>
  <tr>
    <td><code>WSAELOOP</code></td>
    <td>Indicates that a name cannot be translated.</td>
  </tr>
  <tr>
    <td><code>WSAENAMETOOLONG</code></td>
    <td>Indicates that a name was too long.</td>
  </tr>
  <tr>
    <td><code>WSAEHOSTDOWN</code></td>
    <td>Indicates that a network host is down.</td>
  </tr>
  <tr>
    <td><code>WSAEHOSTUNREACH</code></td>
    <td>Indicates that there is no route to a network host.</td>
  </tr>
  <tr>
    <td><code>WSAENOTEMPTY</code></td>
    <td>Indicates that the directory is not empty.</td>
  </tr>
  <tr>
    <td><code>WSAEPROCLIM</code></td>
    <td>Indicates that there are too many processes.</td>
  </tr>
  <tr>
    <td><code>WSAEUSERS</code></td>
    <td>Indicates that the user quota has been exceeded.</td>
  </tr>
  <tr>
    <td><code>WSAEDQUOT</code></td>
    <td>Indicates that the disk quota has been exceeded.</td>
  </tr>
  <tr>
    <td><code>WSAESTALE</code></td>
    <td>Indicates a stale file handle reference.</td>
  </tr>
  <tr>
    <td><code>WSAEREMOTE</code></td>
    <td>Indicates that the item is remote.</td>
  </tr>
  <tr>
    <td><code>WSASYSNOTREADY</code></td>
    <td>Indicates that the network subsystem is not ready.</td>
  </tr>
  <tr>
    <td><code>WSAVERNOTSUPPORTED</code></td>
    <td>Indicates that the <code>winsock.dll</code> version is out of
    range.</td>
  </tr>
  <tr>
    <td><code>WSANOTINITIALISED</code></td>
    <td>Indicates that successful WSAStartup has not yet been performed.</td>
  </tr>
  <tr>
    <td><code>WSAEDISCON</code></td>
    <td>Indicates that a graceful shutdown is in progress.</td>
  </tr>
  <tr>
    <td><code>WSAENOMORE</code></td>
    <td>Indicates that there are no more results.</td>
  </tr>
  <tr>
    <td><code>WSAECANCELLED</code></td>
    <td>Indicates that an operation has been canceled.</td>
  </tr>
  <tr>
    <td><code>WSAEINVALIDPROCTABLE</code></td>
    <td>Indicates that the procedure call table is invalid.</td>
  </tr>
  <tr>
    <td><code>WSAEINVALIDPROVIDER</code></td>
    <td>Indicates an invalid service provider.</td>
  </tr>
  <tr>
    <td><code>WSAEPROVIDERFAILEDINIT</code></td>
    <td>Indicates that the service provider failed to initialized.</td>
  </tr>
  <tr>
    <td><code>WSASYSCALLFAILURE</code></td>
    <td>Indicates a system call failure.</td>
  </tr>
  <tr>
    <td><code>WSASERVICE_NOT_FOUND</code></td>
    <td>Indicates that a service was not found.</td>
  </tr>
  <tr>
    <td><code>WSATYPE_NOT_FOUND</code></td>
    <td>Indicates that a class type was not found.</td>
  </tr>
  <tr>
    <td><code>WSA_E_NO_MORE</code></td>
    <td>Indicates that there are no more results.</td>
  </tr>
  <tr>
    <td><code>WSA_E_CANCELLED</code></td>
    <td>Indicates that the call was canceled.</td>
  </tr>
  <tr>
    <td><code>WSAEREFUSED</code></td>
    <td>Indicates that a database query was refused.</td>
  </tr>
</tbody></table>
<h3>dlopen constants<span><a class="mark" href="#os_dlopen_constants" id="os_dlopen_constants">#</a></span></h3>
<p>If available on the operating system, the following constants
are exported in <code>os.constants.dlopen</code>. See <a href="http://man7.org/linux/man-pages/man3/dlopen.3.html"><code>dlopen(3)</code></a> for detailed
information.</p>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>RTLD_LAZY</code></td>
    <td>Perform lazy binding. Node.js sets this flag by default.</td>
  </tr>
  <tr>
    <td><code>RTLD_NOW</code></td>
    <td>Resolve all undefined symbols in the library before dlopen(3)
    returns.</td>
  </tr>
  <tr>
    <td><code>RTLD_GLOBAL</code></td>
    <td>Symbols defined by the library will be made available for symbol
    resolution of subsequently loaded libraries.</td>
  </tr>
  <tr>
    <td><code>RTLD_LOCAL</code></td>
    <td>The converse of <code>RTLD_GLOBAL</code>. This is the default behavior
    if neither flag is specified.</td>
  </tr>
  <tr>
    <td><code>RTLD_DEEPBIND</code></td>
    <td>Make a self-contained library use its own symbols in preference to
    symbols from previously loaded libraries.</td>
  </tr>
</tbody></table>
<h3>Priority constants<span><a class="mark" href="#os_priority_constants" id="os_priority_constants">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<p>The following process scheduling constants are exported by
<code>os.constants.priority</code>.</p>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>PRIORITY_LOW</code></td>
    <td>The lowest process scheduling priority. This corresponds to
    <code>IDLE_PRIORITY_CLASS</code> on Windows, and a nice value of
    <code>19</code> on all other platforms.</td>
  </tr>
  <tr>
    <td><code>PRIORITY_BELOW_NORMAL</code></td>
    <td>The process scheduling priority above <code>PRIORITY_LOW</code> and
    below <code>PRIORITY_NORMAL</code>. This corresponds to
    <code>BELOW_NORMAL_PRIORITY_CLASS</code> on Windows, and a nice value of
    <code>10</code> on all other platforms.</td>
  </tr>
  <tr>
    <td><code>PRIORITY_NORMAL</code></td>
    <td>The default process scheduling priority. This corresponds to
    <code>NORMAL_PRIORITY_CLASS</code> on Windows, and a nice value of
    <code>0</code> on all other platforms.</td>
  </tr>
  <tr>
    <td><code>PRIORITY_ABOVE_NORMAL</code></td>
    <td>The process scheduling priority above <code>PRIORITY_NORMAL</code> and
    below <code>PRIORITY_HIGH</code>. This corresponds to
    <code>ABOVE_NORMAL_PRIORITY_CLASS</code> on Windows, and a nice value of
    <code>-7</code> on all other platforms.</td>
  </tr>
  <tr>
    <td><code>PRIORITY_HIGH</code></td>
    <td>The process scheduling priority above <code>PRIORITY_ABOVE_NORMAL</code>
    and below <code>PRIORITY_HIGHEST</code>. This corresponds to
    <code>HIGH_PRIORITY_CLASS</code> on Windows, and a nice value of
    <code>-14</code> on all other platforms.</td>
  </tr>
  <tr>
    <td><code>PRIORITY_HIGHEST</code></td>
    <td>The highest process scheduling priority. This corresponds to
    <code>REALTIME_PRIORITY_CLASS</code> on Windows, and a nice value of
    <code>-20</code> on all other platforms.</td>
  </tr>
</tbody></table>
<h3>libuv constants<span><a class="mark" href="#os_libuv_constants" id="os_libuv_constants">#</a></span></h3>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>UV_UDP_REUSEADDR</code></td>
    <td></td>
  </tr>
</tbody></table>
<h1>Path<span><a class="mark" href="#path_path" id="path_path">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>path</code> module provides utilities for working with file and directory paths.
It can be accessed using:</p>
<pre><code class="language-js">const path = require('path');
</code></pre>
<h2>Windows vs. POSIX<span><a class="mark" href="#path_windows_vs_posix" id="path_windows_vs_posix">#</a></span></h2>
<p>The default operation of the <code>path</code> module varies based on the operating system
on which a Node.js application is running. Specifically, when running on a
Windows operating system, the <code>path</code> module will assume that Windows-style
paths are being used.</p>
<p>So using <code>path.basename()</code> might yield different results on POSIX and Windows:</p>
<p>On POSIX:</p>
<pre><code class="language-js">path.basename('C:\\temp\\myfile.html');
// Returns: 'C:\\temp\\myfile.html'
</code></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.basename('C:\\temp\\myfile.html');
// Returns: 'myfile.html'
</code></pre>
<p>To achieve consistent results when working with Windows file paths on any
operating system, use <a href="#path_path_win32"><code>path.win32</code></a>:</p>
<p>On POSIX and Windows:</p>
<pre><code class="language-js">path.win32.basename('C:\\temp\\myfile.html');
// Returns: 'myfile.html'
</code></pre>
<p>To achieve consistent results when working with POSIX file paths on any
operating system, use <a href="#path_path_posix"><code>path.posix</code></a>:</p>
<p>On POSIX and Windows:</p>
<pre><code class="language-js">path.posix.basename('/tmp/myfile.html');
// Returns: 'myfile.html'
</code></pre>
<p>On Windows Node.js follows the concept of per-drive working directory.
This behavior can be observed when using a drive path without a backslash. For
example, <code>path.resolve('C:\\')</code> can potentially return a different result than
<code>path.resolve('C:')</code>. For more information, see
<a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths">this MSDN page</a>.</p>
<h2><code>path.basename(path[, ext])</code><span><a class="mark" href="#path_path_basename_path_ext" id="path_path_basename_path_ext">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>Passing a non-string as the <code>path</code> argument will throw now.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>ext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a></li>
</ul>
<p>The <code>path.basename()</code> method returns the last portion of a <code>path</code>, similar to
the Unix <code>basename</code> command. Trailing directory separators are ignored, see
<a href="#path_path_sep"><code>path.sep</code></a>.</p>
<pre><code class="language-js">path.basename('/foo/bar/baz/asdf/quux.html');
// Returns: 'quux.html'

path.basename('/foo/bar/baz/asdf/quux.html', '.html');
// Returns: 'quux'
</code></pre>
<p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string or if <code>ext</code> is given
and is not a string.</p>
<h2><code>path.delimiter</code><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">&#x3C;string></a></li>
</ul>
<p>Provides the platform-specific path delimiter:</p>
<ul>
<li><code>;</code> for Windows</li>
<li><code>:</code> for POSIX</li>
</ul>
<p>For example, on POSIX:</p>
<pre><code class="language-js">console.log(process.env.PATH);
// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'

process.env.PATH.split(path.delimiter);
// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
</code></pre>
<p>On Windows:</p>
<pre><code class="language-js">console.log(process.env.PATH);
// Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'

process.env.PATH.split(path.delimiter);
// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
</code></pre>
<h2><code>path.dirname(path)</code><span><a class="mark" href="#path_path_dirname_path" id="path_path_dirname_path">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>Passing a non-string as the <code>path</code> argument will throw now.</p></td></tr>
<tr><td>v0.1.16</td>
<td><p><span>Added in: v0.1.16</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>path.dirname()</code> method returns the directory name of a <code>path</code>, similar to
the Unix <code>dirname</code> command. Trailing directory separators are ignored, see
<a href="#path_path_sep"><code>path.sep</code></a>.</p>
<pre><code class="language-js">path.dirname('/foo/bar/baz/asdf/quux');
// Returns: '/foo/bar/baz/asdf'
</code></pre>
<p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
<h2><code>path.extname(path)</code><span><a class="mark" href="#path_path_extname_path" id="path_path_extname_path">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>Passing a non-string as the <code>path</code> argument will throw now.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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
there are no <code>.</code> characters other than the first character of
the basename of <code>path</code> (see <code>path.basename()</code>) , an empty string is returned.</p>
<pre><code class="language-js">path.extname('index.html');
// Returns: '.html'

path.extname('index.coffee.md');
// Returns: '.md'

path.extname('index.');
// Returns: '.'

path.extname('index');
// Returns: ''

path.extname('.index');
// Returns: ''

path.extname('.index.md');
// Returns: '.md'
</code></pre>
<p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
<h2><code>path.format(pathObject)</code><span><a class="mark" href="#path_path_format_pathobject" id="path_path_format_pathobject">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div>
<ul>
<li>
<p><code>pathObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>root</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>ext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>path.format()</code> method returns a path string from an object. This is the
opposite of <a href="#path_path_parse_path"><code>path.parse()</code></a>.</p>
<p>When providing properties to the <code>pathObject</code> remember that there are
combinations where one property has priority over another:</p>
<ul>
<li><code>pathObject.root</code> is ignored if <code>pathObject.dir</code> is provided</li>
<li><code>pathObject.ext</code> and <code>pathObject.name</code> are ignored if <code>pathObject.base</code> exists</li>
</ul>
<p>For example, on POSIX:</p>
<pre><code class="language-js">// If `dir`, `root` and `base` are provided,
// `${dir}${path.sep}${base}`
// will be returned. `root` is ignored.
path.format({
  root: '/ignored',
  dir: '/home/user/dir',
  base: 'file.txt'
});
// Returns: '/home/user/dir/file.txt'

// `root` will be used if `dir` is not specified.
// If only `root` is provided or `dir` is equal to `root` then the
// platform separator will not be included. `ext` will be ignored.
path.format({
  root: '/',
  base: 'file.txt',
  ext: 'ignored'
});
// Returns: '/file.txt'

// `name` + `ext` will be used if `base` is not specified.
path.format({
  root: '/',
  name: 'file',
  ext: '.txt'
});
// Returns: '/file.txt'
</code></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.format({
  dir: 'C:\\path\\dir',
  base: 'file.txt'
});
// Returns: 'C:\\path\\dir\\file.txt'
</code></pre>
<h2><code>path.isAbsolute(path)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <code>path.isAbsolute()</code> method determines if <code>path</code> is an absolute path.</p>
<p>If the given <code>path</code> is a zero-length string, <code>false</code> will be returned.</p>
<p>For example, on POSIX:</p>
<pre><code class="language-js">path.isAbsolute('/foo/bar'); // true
path.isAbsolute('/baz/..');  // true
path.isAbsolute('qux/');     // false
path.isAbsolute('.');        // false
</code></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.isAbsolute('//server');    // true
path.isAbsolute('\\\\server');  // true
path.isAbsolute('C:/foo/..');   // true
path.isAbsolute('C:\\foo\\..'); // true
path.isAbsolute('bar\\baz');    // false
path.isAbsolute('bar/baz');     // false
path.isAbsolute('.');           // false
</code></pre>
<p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
<h2><code>path.join([...paths])</code><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">&#x3C;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">&#x3C;string></a></li>
</ul>
<p>The <code>path.join()</code> method joins all given <code>path</code> segments together using the
platform-specific separator as a delimiter, then normalizes the resulting path.</p>
<p>Zero-length <code>path</code> segments are ignored. If the joined path string is a
zero-length string then <code>'.'</code> will be returned, representing the current
working directory.</p>
<pre><code class="language-js">path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'

path.join('foo', {}, 'bar');
// Throws 'TypeError: Path must be a string. Received {}'
</code></pre>
<p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if any of the path segments is not a string.</p>
<h2><code>path.normalize(path)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>path.normalize()</code> method normalizes the given <code>path</code>, resolving <code>'..'</code> and
<code>'.'</code> segments.</p>
<p>When multiple, sequential path segment separation characters are found (e.g.
<code>/</code> on POSIX and either <code>\</code> or <code>/</code> on Windows), they are replaced by a single
instance of the platform-specific path segment separator (<code>/</code> on POSIX and
<code>\</code> on Windows). Trailing separators are preserved.</p>
<p>If the <code>path</code> is a zero-length string, <code>'.'</code> is returned, representing the
current working directory.</p>
<p>For example, on POSIX:</p>
<pre><code class="language-js">path.normalize('/foo/bar//baz/asdf/quux/..');
// Returns: '/foo/bar/baz/asdf'
</code></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.normalize('C:\\temp\\\\foo\\bar\\..\\');
// Returns: 'C:\\temp\\foo\\'
</code></pre>
<p>Since Windows recognizes multiple path separators, both separators will be
replaced by instances of the Windows preferred separator (<code>\</code>):</p>
<pre><code class="language-js">path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar');
// Returns: 'C:\\temp\\foo\\bar'
</code></pre>
<p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
<h2><code>path.parse(path)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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">&#x3C;string></a></li>
<li><code>root</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>ext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>For example, on POSIX:</p>
<pre><code class="language-js">path.parse('/home/user/dir/file.txt');
// Returns:
// { root: '/',
//   dir: '/home/user/dir',
//   base: 'file.txt',
//   ext: '.txt',
//   name: 'file' }
</code></pre>
<pre><code class="language-text">┌─────────────────────┬────────────┐
│          dir        │    base    │
├──────┬              ├──────┬─────┤
│ root │              │ name │ ext │
"  /    home/user/dir / file  .txt "
└──────┴──────────────┴──────┴─────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)
</code></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.parse('C:\\path\\dir\\file.txt');
// Returns:
// { root: 'C:\\',
//   dir: 'C:\\path\\dir',
//   base: 'file.txt',
//   ext: '.txt',
//   name: 'file' }
</code></pre>
<pre><code class="language-text">┌─────────────────────┬────────────┐
│          dir        │    base    │
├──────┬              ├──────┬─────┤
│ root │              │ name │ ext │
" C:\      path\dir   \ file  .txt "
└──────┴──────────────┴──────┴─────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)
</code></pre>
<p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
<h2><code>path.posix</code><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">&#x3C;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><code>path.relative(from, to)</code><span><a class="mark" href="#path_path_relative_from_to" id="path_path_relative_from_to">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.8.0</td>
<td><p>On Windows, the leading slashes for UNC paths are now included in the return value.</p></td></tr>
<tr><td>v0.5.0</td>
<td><p><span>Added in: v0.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>from</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>to</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>path.relative()</code> method returns the relative path from <code>from</code> to <code>to</code> based
on the current working directory. If <code>from</code> and <code>to</code> each resolve to the same
path (after calling <code>path.resolve()</code> on each), a zero-length string is returned.</p>
<p>If a zero-length string is passed as <code>from</code> or <code>to</code>, the current working
directory will be used instead of the zero-length strings.</p>
<p>For example, on POSIX:</p>
<pre><code class="language-js">path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
// Returns: '../../impl/bbb'
</code></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb');
// Returns: '..\\..\\impl\\bbb'
</code></pre>
<p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if either <code>from</code> or <code>to</code> is not a string.</p>
<h2><code>path.resolve([...paths])</code><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">&#x3C;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">&#x3C;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>
because <code>'baz'</code> is not an absolute path but <code>'/bar' + '/' + 'baz'</code> is.</p>
<p>If after processing all given <code>path</code> segments an absolute path has not yet
been generated, the current working directory is used.</p>
<p>The resulting path is normalized and trailing slashes are removed unless the
path is resolved to the root directory.</p>
<p>Zero-length <code>path</code> segments are ignored.</p>
<p>If no <code>path</code> segments are passed, <code>path.resolve()</code> will return the absolute path
of the current working directory.</p>
<pre><code class="language-js">path.resolve('/foo/bar', './baz');
// Returns: '/foo/bar/baz'

path.resolve('/foo/bar', '/tmp/file/');
// Returns: '/tmp/file'

path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif');
// If the current working directory is /home/myself/node,
// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'
</code></pre>
<p>A <a href="#errors_class_typeerror"><code>TypeError</code></a> is thrown if any of the arguments is not a string.</p>
<h2><code>path.sep</code><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">&#x3C;string></a></li>
</ul>
<p>Provides the platform-specific path segment separator:</p>
<ul>
<li><code>\</code> on Windows</li>
<li><code>/</code> on POSIX</li>
</ul>
<p>For example, on POSIX:</p>
<pre><code class="language-js">'foo/bar/baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz']
</code></pre>
<p>On Windows:</p>
<pre><code class="language-js">'foo\\bar\\baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz']
</code></pre>
<p>On Windows, both the forward slash (<code>/</code>) and backward slash (<code>\</code>) are accepted
as path segment separators; however, the <code>path</code> methods only add backward
slashes (<code>\</code>).</p>
<h2><code>path.toNamespacedPath(path)</code><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">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>On Windows systems only, returns an equivalent <a href="https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#namespaces">namespace-prefixed path</a> for
the given <code>path</code>. If <code>path</code> is not a string, <code>path</code> will be returned without
modifications.</p>
<p>This method is meaningful only on Windows system. On POSIX systems, the
method is non-operational and always returns <code>path</code> without modifications.</p>
<h2><code>path.win32</code><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">&#x3C;Object></a></li>
</ul>
<p>The <code>path.win32</code> property provides access to Windows-specific implementations
of the <code>path</code> methods.</p>
<h1>Performance measurement APIs<span><a class="mark" href="#perf_hooks_performance_measurement_apis" id="perf_hooks_performance_measurement_apis">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>This module provides an implementation of a subset of the W3C
<a href="https://w3c.github.io/perf-timing-primer/">Web Performance APIs</a> as well as additional APIs for
Node.js-specific performance measurements.</p>
<p>Node.js supports the following <a href="https://w3c.github.io/perf-timing-primer/">Web Performance APIs</a>:</p>
<ul>
<li><a href="https://www.w3.org/TR/hr-time-2">High Resolution Time</a></li>
<li><a href="https://w3c.github.io/performance-timeline/">Performance Timeline</a></li>
<li><a href="https://www.w3.org/TR/user-timing/">User Timing</a></li>
</ul>
<pre><code class="language-js">const { PerformanceObserver, performance } = require('perf_hooks');

const obs = new PerformanceObserver((items) => {
  console.log(items.getEntries()[0].duration);
  performance.clearMarks();
});
obs.observe({ entryTypes: ['measure'] });
performance.measure('Start to Now');

performance.mark('A');
doSomeLongRunningProcess(() => {
  performance.measure('A to Now', 'A');

  performance.mark('B');
  performance.measure('A to B', 'A', 'B');
});
</code></pre>
<h2><code>perf_hooks.performance</code><span><a class="mark" href="#perf_hooks_perf_hooks_performance" id="perf_hooks_perf_hooks_performance">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>An object that can be used to collect performance metrics from the current
Node.js instance. It is similar to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/performance"><code>window.performance</code></a> in browsers.</p>
<h3><code>performance.clearMarks([name])</code><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">&#x3C;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><code>performance.mark([name])</code><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">&#x3C;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><code>performance.measure(name[, startMark[, endMark]])</code><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">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.3</td>
<td><p>Make <code>startMark</code> and <code>endMark</code> parameters optional.</p></td></tr>
<tr><td>v8.5.0</td>
<td><p><span>Added in: v8.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>startMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Optional.</li>
<li><code>endMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Optional.</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 optional <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. <code>endMark</code> will be <code>performance.now()</code>
if no parameter is passed, otherwise if the named <code>endMark</code> does not exist, an
error will be thrown.</p>
<h3><code>performance.nodeTiming</code><span><a class="mark" href="#perf_hooks_performance_nodetiming" id="perf_hooks_performance_nodetiming">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><a href="#perf_hooks_class_performancenodetiming_extends_performanceentry" class="type">&#x3C;PerformanceNodeTiming></a></li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>An instance of the <code>PerformanceNodeTiming</code> class that provides performance
metrics for specific Node.js operational milestones.</p>
<h3><code>performance.now()</code><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">&#x3C;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><code>performance.timeOrigin</code><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">&#x3C;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><code>performance.timerify(fn)</code><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">&#x3C;Function></a></li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>Wraps a function within a new function that measures the running time of the
wrapped function. A <code>PerformanceObserver</code> must be subscribed to the <code>'function'</code>
event type in order for the timing details to be accessed.</p>
<pre><code class="language-js">const {
  performance,
  PerformanceObserver
} = require('perf_hooks');

function someFunction() {
  console.log('hello world');
}

const wrapped = performance.timerify(someFunction);

const obs = new PerformanceObserver((list) => {
  console.log(list.getEntries()[0].duration);
  obs.disconnect();
});
obs.observe({ entryTypes: ['function'] });

// A performance timeline entry will be created
wrapped();
</code></pre>
<h2>Class: <code>PerformanceEntry</code><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><code>performanceEntry.duration</code><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">&#x3C;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><code>performanceEntry.name</code><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">&#x3C;string></a></li>
</ul>
<p>The name of the performance entry.</p>
<h3><code>performanceEntry.startTime</code><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">&#x3C;number></a></li>
</ul>
<p>The high resolution millisecond timestamp marking the starting time of the
Performance Entry.</p>
<h3><code>performanceEntry.entryType</code><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">&#x3C;string></a></li>
</ul>
<p>The type of the performance entry. It may be one of:</p>
<ul>
<li><code>'node'</code> (Node.js only)</li>
<li><code>'mark'</code> (available on the Web)</li>
<li><code>'measure'</code> (available on the Web)</li>
<li><code>'gc'</code> (Node.js only)</li>
<li><code>'function'</code> (Node.js only)</li>
<li><code>'http2'</code> (Node.js only)</li>
<li><code>'http'</code> (Node.js only)</li>
</ul>
<h3><code>performanceEntry.kind</code><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">&#x3C;number></a></li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<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>
<h3>performanceEntry.flags<span><a class="mark" href="#perf_hooks_performanceentry_flags" id="perf_hooks_performanceentry_flags">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>When <code>performanceEntry.entryType</code> is equal to <code>'gc'</code>, the <code>performance.flags</code>
property contains additional information about garbage collection operation.
The value may be one of:</p>
<ul>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_NO</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_FORCED</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY</code></li>
<li><code>perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE</code></li>
</ul>
<h2>Class: <code>PerformanceNodeTiming extends PerformanceEntry</code><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><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>Provides timing details for Node.js itself. The constructor of this class
is not exposed to users.</p>
<h3><code>performanceNodeTiming.bootstrapComplete</code><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">&#x3C;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><code>performanceNodeTiming.environment</code><span><a class="mark" href="#perf_hooks_performancenodetiming_environment" id="perf_hooks_performancenodetiming_environment">#</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">&#x3C;number></a></li>
</ul>
<p>The high resolution millisecond timestamp at which the Node.js environment was
initialized.</p>
<h3><code>performanceNodeTiming.loopExit</code><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">&#x3C;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><code>performanceNodeTiming.loopStart</code><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">&#x3C;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><code>performanceNodeTiming.nodeStart</code><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">&#x3C;number></a></li>
</ul>
<p>The high resolution millisecond timestamp at which the Node.js process was
initialized.</p>
<h3><code>performanceNodeTiming.v8Start</code><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">&#x3C;number></a></li>
</ul>
<p>The high resolution millisecond timestamp at which the V8 platform was
initialized.</p>
<h2>Class: <code>perf_hooks.PerformanceObserver</code><span><a class="mark" href="#perf_hooks_class_perf_hooks_performanceobserver" id="perf_hooks_class_perf_hooks_performanceobserver">#</a></span></h2>
<h3><code>new PerformanceObserver(callback)</code><span><a class="mark" href="#perf_hooks_new_performanceobserver_callback" id="perf_hooks_new_performanceobserver_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li><code>list</code> <a href="#perf_hooks_class_performanceobserverentrylist" class="type">&#x3C;PerformanceObserverEntryList></a></li>
<li><code>observer</code> <a href="#perf_hooks_class_perf_hooks_performanceobserver" class="type">&#x3C;PerformanceObserver></a></li>
</ul>
</li>
</ul>
<p><code>PerformanceObserver</code> objects provide notifications when new
<code>PerformanceEntry</code> instances have been added to the Performance Timeline.</p>
<pre><code class="language-js">const {
  performance,
  PerformanceObserver
} = require('perf_hooks');

const obs = new PerformanceObserver((list, observer) => {
  console.log(list.getEntries());
  observer.disconnect();
});
obs.observe({ entryTypes: ['mark'], buffered: true });

performance.mark('test');
</code></pre>
<p>Because <code>PerformanceObserver</code> instances introduce their own additional
performance overhead, instances should not be left subscribed to notifications
indefinitely. Users should disconnect observers as soon as they are no
longer needed.</p>
<p>The <code>callback</code> is invoked when a <code>PerformanceObserver</code> is
notified about new <code>PerformanceEntry</code> instances. The callback receives a
<code>PerformanceObserverEntryList</code> instance and a reference to the
<code>PerformanceObserver</code>.</p>
<h3><code>performanceObserver.disconnect()</code><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><code>performanceObserver.observe(options)</code><span><a class="mark" href="#perf_hooks_performanceobserver_observe_options" id="perf_hooks_performanceobserver_observe_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>entryTypes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> An array of strings identifying the types of
<code>PerformanceEntry</code> instances the observer is interested in. If not
provided an error will be thrown.</li>
<li><code>buffered</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If true, the notification callback will be
called using <code>setImmediate()</code> and multiple <code>PerformanceEntry</code> instance
notifications will be buffered internally. If <code>false</code>, notifications will
be immediate and synchronous. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Subscribes the <code>PerformanceObserver</code> instance to notifications of new
<code>PerformanceEntry</code> instances identified by <code>options.entryTypes</code>.</p>
<p>When <code>options.buffered</code> is <code>false</code>, the <code>callback</code> will be invoked once for
every <code>PerformanceEntry</code> instance:</p>
<pre><code class="language-js">const {
  performance,
  PerformanceObserver
} = require('perf_hooks');

const obs = new PerformanceObserver((list, observer) => {
  // Called three times synchronously. `list` contains one item.
});
obs.observe({ entryTypes: ['mark'] });

for (let n = 0; n &#x3C; 3; n++)
  performance.mark(`test${n}`);
</code></pre>
<pre><code class="language-js">const {
  performance,
  PerformanceObserver
} = require('perf_hooks');

const obs = new PerformanceObserver((list, observer) => {
  // Called once. `list` contains three items.
});
obs.observe({ entryTypes: ['mark'], buffered: true });

for (let n = 0; n &#x3C; 3; n++)
  performance.mark(`test${n}`);
</code></pre>
<h2>Class: <code>PerformanceObserverEntryList</code><span><a class="mark" href="#perf_hooks_class_performanceobserverentrylist" id="perf_hooks_class_performanceobserverentrylist">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>The <code>PerformanceObserverEntryList</code> class is used to provide access to the
<code>PerformanceEntry</code> instances passed to a <code>PerformanceObserver</code>.
The constructor of this class is not exposed to users.</p>
<h3><code>performanceObserverEntryList.getEntries()</code><span><a class="mark" href="#perf_hooks_performanceobserverentrylist_getentries" id="perf_hooks_performanceobserverentrylist_getentries">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li>Returns: <a href="#perf_hooks_class_performanceentry" class="type">&#x3C;PerformanceEntry[]></a></li>
</ul>
<p>Returns a list of <code>PerformanceEntry</code> objects in chronological order
with respect to <code>performanceEntry.startTime</code>.</p>
<h3><code>performanceObserverEntryList.getEntriesByName(name[, type])</code><span><a class="mark" href="#perf_hooks_performanceobserverentrylist_getentriesbyname_name_type" id="perf_hooks_performanceobserverentrylist_getentriesbyname_name_type">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="#perf_hooks_class_performanceentry" class="type">&#x3C;PerformanceEntry[]></a></li>
</ul>
<p>Returns a list of <code>PerformanceEntry</code> objects in chronological order
with respect to <code>performanceEntry.startTime</code> whose <code>performanceEntry.name</code> is
equal to <code>name</code>, and optionally, whose <code>performanceEntry.entryType</code> is equal to
<code>type</code>.</p>
<h3><code>performanceObserverEntryList.getEntriesByType(type)</code><span><a class="mark" href="#perf_hooks_performanceobserverentrylist_getentriesbytype_type" id="perf_hooks_performanceobserverentrylist_getentriesbytype_type">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="#perf_hooks_class_performanceentry" class="type">&#x3C;PerformanceEntry[]></a></li>
</ul>
<p>Returns a list of <code>PerformanceEntry</code> objects in chronological order
with respect to <code>performanceEntry.startTime</code> whose <code>performanceEntry.entryType</code>
is equal to <code>type</code>.</p>
<h2><code>perf_hooks.monitorEventLoopDelay([options])</code><span><a class="mark" href="#perf_hooks_perf_hooks_monitoreventloopdelay_options" id="perf_hooks_perf_hooks_monitoreventloopdelay_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>resolution</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The sampling rate in milliseconds. Must be greater
than zero. <strong>Default:</strong> <code>10</code>.</li>
</ul>
</li>
<li>Returns: <a href="#perf_hooks_class_histogram" class="type">&#x3C;Histogram></a></li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>Creates a <code>Histogram</code> object that samples and reports the event loop delay
over time. The delays will be reported in nanoseconds.</p>
<p>Using a timer to detect approximate event loop delay works because the
execution of timers is tied specifically to the lifecycle of the libuv
event loop. That is, a delay in the loop will cause a delay in the execution
of the timer, and those delays are specifically what this API is intended to
detect.</p>
<pre><code class="language-js">const { monitorEventLoopDelay } = require('perf_hooks');
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
// Do something.
h.disable();
console.log(h.min);
console.log(h.max);
console.log(h.mean);
console.log(h.stddev);
console.log(h.percentiles);
console.log(h.percentile(50));
console.log(h.percentile(99));
</code></pre>
<h3>Class: <code>Histogram</code><span><a class="mark" href="#perf_hooks_class_histogram" id="perf_hooks_class_histogram">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<p>Tracks the event loop delay at a given sampling rate. The constructor of
this class not exposed to users.</p>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<h4><code>histogram.disable()</code><span><a class="mark" href="#perf_hooks_histogram_disable" id="perf_hooks_histogram_disable">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Disables the event loop delay sample timer. Returns <code>true</code> if the timer was
stopped, <code>false</code> if it was already stopped.</p>
<h4><code>histogram.enable()</code><span><a class="mark" href="#perf_hooks_histogram_enable" id="perf_hooks_histogram_enable">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Enables the event loop delay sample timer. Returns <code>true</code> if the timer was
started, <code>false</code> if it was already started.</p>
<h4><code>histogram.exceeds</code><span><a class="mark" href="#perf_hooks_histogram_exceeds" id="perf_hooks_histogram_exceeds">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The number of times the event loop delay exceeded the maximum 1 hour event
loop delay threshold.</p>
<h4><code>histogram.max</code><span><a class="mark" href="#perf_hooks_histogram_max" id="perf_hooks_histogram_max">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The maximum recorded event loop delay.</p>
<h4><code>histogram.mean</code><span><a class="mark" href="#perf_hooks_histogram_mean" id="perf_hooks_histogram_mean">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The mean of the recorded event loop delays.</p>
<h4><code>histogram.min</code><span><a class="mark" href="#perf_hooks_histogram_min" id="perf_hooks_histogram_min">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The minimum recorded event loop delay.</p>
<h4><code>histogram.percentile(percentile)</code><span><a class="mark" href="#perf_hooks_histogram_percentile_percentile" id="perf_hooks_histogram_percentile_percentile">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><code>percentile</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> A percentile value between 1 and 100.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Returns the value at the given percentile.</p>
<h4><code>histogram.percentiles</code><span><a class="mark" href="#perf_hooks_histogram_percentiles" id="perf_hooks_histogram_percentiles">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type">&#x3C;Map></a></li>
</ul>
<p>Returns a <code>Map</code> object detailing the accumulated percentile distribution.</p>
<h4><code>histogram.reset()</code><span><a class="mark" href="#perf_hooks_histogram_reset" id="perf_hooks_histogram_reset">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<p>Resets the collected histogram data.</p>
<h4><code>histogram.stddev</code><span><a class="mark" href="#perf_hooks_histogram_stddev" id="perf_hooks_histogram_stddev">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The standard deviation of the recorded event loop delays.</p>
<h2>Examples<span><a class="mark" href="#perf_hooks_examples" id="perf_hooks_examples">#</a></span></h2>
<h3>Measuring the duration of async operations<span><a class="mark" href="#perf_hooks_measuring_the_duration_of_async_operations" id="perf_hooks_measuring_the_duration_of_async_operations">#</a></span></h3>
<p>The following example uses the <a href="async_hooks.html">Async Hooks</a> and Performance APIs to measure
the actual duration of a Timeout operation (including the amount of time it took
to execute the callback).</p>
<pre><code class="language-js">'use strict';
const async_hooks = require('async_hooks');
const {
  performance,
  PerformanceObserver
} = require('perf_hooks');

const set = new Set();
const hook = async_hooks.createHook({
  init(id, type) {
    if (type === 'Timeout') {
      performance.mark(`Timeout-${id}-Init`);
      set.add(id);
    }
  },
  destroy(id) {
    if (set.has(id)) {
      set.delete(id);
      performance.mark(`Timeout-${id}-Destroy`);
      performance.measure(`Timeout-${id}`,
                          `Timeout-${id}-Init`,
                          `Timeout-${id}-Destroy`);
    }
  }
});
hook.enable();

const obs = new PerformanceObserver((list, observer) => {
  console.log(list.getEntries()[0]);
  performance.clearMarks();
  observer.disconnect();
});
obs.observe({ entryTypes: ['measure'], buffered: true });

setTimeout(() => {}, 1000);
</code></pre>
<h3>Measuring how long it takes to load dependencies<span><a class="mark" href="#perf_hooks_measuring_how_long_it_takes_to_load_dependencies" id="perf_hooks_measuring_how_long_it_takes_to_load_dependencies">#</a></span></h3>
<p>The following example measures the duration of <code>require()</code> operations to load
dependencies:</p>
<!-- eslint-disable no-global-assign -->
<pre><code class="language-js">'use strict';
const {
  performance,
  PerformanceObserver
} = require('perf_hooks');
const mod = require('module');

// Monkey patch the require function
mod.Module.prototype.require =
  performance.timerify(mod.Module.prototype.require);
require = performance.timerify(require);

// Activate the observer
const obs = new PerformanceObserver((list) => {
  const entries = list.getEntries();
  entries.forEach((entry) => {
    console.log(`require('${entry[0]}')`, entry.duration);
  });
  obs.disconnect();
});
obs.observe({ entryTypes: ['function'], buffered: true });

require('some-module');
</code></pre>
<h1>Policies<span><a class="mark" href="#policy_policies" id="policy_policies">#</a></span></h1>


<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>

<p>Node.js contains experimental support for creating policies on loading code.</p>
<p>Policies are a security feature intended to allow guarantees
about what code Node.js is able to load. The use of policies assumes
safe practices for the policy files such as ensuring that policy
files cannot be overwritten by the Node.js application by using
file permissions.</p>
<p>A best practice would be to ensure that the policy manifest is read only for
the running Node.js application, and that the file cannot be changed
by the running Node.js application in any way. A typical setup would be to
create the policy file as a different user id than the one running Node.js
and granting read permissions to the user id running Node.js.</p>
<h2>Enabling<span><a class="mark" href="#policy_enabling" id="policy_enabling">#</a></span></h2>

<p>The <code>--experimental-policy</code> flag can be used to enable features for policies
when loading modules.</p>
<p>Once this has been set, all modules must conform to a policy manifest file
passed to the flag:</p>
<pre><code class="language-bash">node --experimental-policy=policy.json app.js
</code></pre>
<p>The policy manifest will be used to enforce constraints on code loaded by
Node.js.</p>
<p>To mitigate tampering with policy files on disk, an integrity for
the policy file itself may be provided via <code>--policy-integrity</code>.
This allows running <code>node</code> and asserting the policy file contents
even if the file is changed on disk.</p>
<pre><code class="language-bash">node --experimental-policy=policy.json --policy-integrity="sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0" app.js
</code></pre>
<h2>Features<span><a class="mark" href="#policy_features" id="policy_features">#</a></span></h2>
<h3>Error behavior<span><a class="mark" href="#policy_error_behavior" id="policy_error_behavior">#</a></span></h3>
<p>When a policy check fails, Node.js by default will throw an error.
It is possible to change the error behavior to one of a few possibilities
by defining an "onerror" field in a policy manifest. The following values are
available to change the behavior:</p>
<ul>
<li><code>"exit"</code>: will exit the process immediately.
No cleanup code will be allowed to run.</li>
<li><code>"log"</code>: will log the error at the site of the failure.</li>
<li><code>"throw"</code>: will throw a JS error at the site of the failure. This is the
default.</li>
</ul>
<pre><code class="language-json">{
  "onerror": "log",
  "resources": {
    "./app/checked.js": {
      "integrity": "sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"
    }
  }
}
</code></pre>
<h3>Integrity checks<span><a class="mark" href="#policy_integrity_checks" id="policy_integrity_checks">#</a></span></h3>
<p>Policy files must use integrity checks with Subresource Integrity strings
compatible with the browser
<a href="https://www.w3.org/TR/SRI/#the-integrity-attribute">integrity attribute</a>
associated with absolute URLs.</p>
<p>When using <code>require()</code> all resources involved in loading are checked for
integrity if a policy manifest has been specified. If a resource does not match
the integrity listed in the manifest, an error will be thrown.</p>
<p>An example policy file that would allow loading a file <code>checked.js</code>:</p>
<pre><code class="language-json">{
  "resources": {
    "./app/checked.js": {
      "integrity": "sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"
    }
  }
}
</code></pre>
<p>Each resource listed in the policy manifest can be of one the following
formats to determine its location:</p>
<ol>
<li>A <a href="https://url.spec.whatwg.org/#relative-url-with-fragment-string">relative url string</a> to a resource from the manifest such as <code>./resource.js</code>, <code>../resource.js</code>, or <code>/resource.js</code>.</li>
<li>A complete url string to a resource such as <code>file:///resource.js</code>.</li>
</ol>
<p>When loading resources the entire URL must match including search parameters
and hash fragment. <code>./a.js?b</code> will not be used when attempting to load
<code>./a.js</code> and vice versa.</p>
<p>To generate integrity strings, a script such as
<code>printf "sha384-$(cat checked.js | openssl dgst -sha384 -binary | base64)"</code>
can be used.</p>
<p>Integrity can be specified as the boolean value <code>true</code> to accept any
body for the resource which can be useful for local development. It is not
recommended in production since it would allow unexpected alteration of
resources to be considered valid.</p>
<h3>Dependency redirection<span><a class="mark" href="#policy_dependency_redirection" id="policy_dependency_redirection">#</a></span></h3>
<p>An application may need to ship patched versions of modules or to prevent
modules from allowing all modules access to all other modules. Redirection
can be used by intercepting attempts to load the modules wishing to be
replaced.</p>
<pre><code class="language-json">{
  "builtins": [],
  "resources": {
    "./app/checked.js": {
      "dependencies": {
        "fs": true,
        "os": "./app/node_modules/alt-os"
      }
    }
  }
}
</code></pre>
<p>The dependencies are keyed by the requested string specifier and have values
of either <code>true</code> or a string pointing to a module that will be resolved.</p>
<p>The specifier string does not perform any searching and must match exactly
what is provided to the <code>require()</code>. Therefore, multiple specifiers may be
needed in the policy if <code>require()</code> uses multiple different strings to point
to the same module (such as excluding the extension).</p>
<p>If the value of the redirection is <code>true</code> the default searching algorithms will
be used to find the module.</p>
<p>If the value of the redirection is a string, it will be resolved relative to
the manifest and then immediately be used without searching.</p>
<p>Any specifier string that is <code>require()</code>ed and not listed in the dependencies
will result in an error according to the policy.</p>
<p>Redirection will not prevent access to APIs through means such as direct access
to <code>require.cache</code> and/or through <code>module.constructor</code> which allow access to
loading modules. Policy redirection only affect specifiers to <code>require()</code>.
Other means such as to prevent undesired access to APIs through variables are
necessary to lock down that path of loading modules.</p>
<p>A boolean value of <code>true</code> for the dependencies map can be specified to allow a
module to load any specifier without redirection. This can be useful for local
development and may have some valid usage in production, but should be used
only with care after auditing a module to ensure its behavior is valid.</p>
<h4>Example: Patched dependency<span><a class="mark" href="#policy_example_patched_dependency" id="policy_example_patched_dependency">#</a></span></h4>
<p>Redirected dependencies can provide attenuated or modified functionality as fits
the application. For example, log data about timing of function durations by
wrapping the original:</p>
<pre><code class="language-js">const original = require('fn');
module.exports = function fn(...args) {
  console.time();
  try {
    return new.target ?
      Reflect.construct(original, args) :
      Reflect.apply(original, this, args);
  } finally {
    console.timeEnd();
  }
};
</code></pre>
<h1>Process<span><a class="mark" href="#process_process" id="process_process">#</a></span></h1>


<p>The <code>process</code> object is a <code>global</code> that provides information about, and control
over, the current Node.js process. As a global, it is always available to
Node.js applications without using <code>require()</code>. It can also be explicitly
accessed using <code>require()</code>:</p>
<pre><code class="language-js">const process = require('process');
</code></pre>
<h2>Process events<span><a class="mark" href="#process_process_events" id="process_process_events">#</a></span></h2>
<p>The <code>process</code> object is an instance of <a href="#events_class_eventemitter"><code>EventEmitter</code></a>.</p>
<h3>Event: <code>'beforeExit'</code><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>
<pre><code class="language-js">process.on('beforeExit', (code) => {
  console.log('Process beforeExit event with code: ', code);
});

process.on('exit', (code) => {
  console.log('Process exit event with code: ', code);
});

console.log('This message is displayed first.');

// Prints:
// This message is displayed first.
// Process beforeExit event with code: 0
// Process exit event with code: 0
</code></pre>
<h3>Event: <code>'disconnect'</code><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: <code>'exit'</code><span><a class="mark" href="#process_event_exit" id="process_event_exit">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.7</span>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>The <code>'exit'</code> event is emitted when the Node.js process is about to exit as a
result of either:</p>
<ul>
<li>The <code>process.exit()</code> method being called explicitly;</li>
<li>The Node.js event loop no longer having any additional work to perform.</li>
</ul>
<p>There is no way to prevent the exiting of the event loop at this point, and once
all <code>'exit'</code> listeners have finished running the Node.js process will terminate.</p>
<p>The listener callback function is invoked with the exit code specified either
by the <a href="#process_process_exitcode"><code>process.exitCode</code></a> property, or the <code>exitCode</code> argument passed to the
<a href="#process_process_exit_code"><code>process.exit()</code></a> method.</p>
<pre><code class="language-js">process.on('exit', (code) => {
  console.log(`About to exit with code: ${code}`);
});
</code></pre>
<p>Listener functions <strong>must</strong> only perform <strong>synchronous</strong> operations. The Node.js
process will exit immediately after calling the <code>'exit'</code> event listeners
causing any additional work still queued in the event loop to be abandoned.
In the following example, for instance, the timeout will never occur:</p>
<pre><code class="language-js">process.on('exit', (code) => {
  setTimeout(() => {
    console.log('This will not run');
  }, 0);
});
</code></pre>
<h3>Event: <code>'message'</code><span><a class="mark" href="#process_event_message" id="process_event_message">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.10</span>
</div>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> a parsed JSON object
or a serializable primitive value.</li>
<li><code>sendHandle</code> <a href="#net_class_net_server" class="type">&#x3C;net.Server></a> | <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> a <a href="#net_class_net_server"><code>net.Server</code></a> or <a href="#net_class_net_socket"><code>net.Socket</code></a>
object, or undefined.</li>
</ul>
<p>If the Node.js process is spawned with an IPC channel (see the <a href="child_process.html">Child Process</a>
and <a href="cluster.html">Cluster</a> documentation), the <code>'message'</code> event is emitted whenever a
message sent by a parent process using <a href="#child_process_subprocess_send_message_sendhandle_options_callback"><code>childprocess.send()</code></a> is received by
the child process.</p>
<p>The message goes through serialization and parsing. The resulting message might
not be the same as what is originally sent.</p>
<p>If the <code>serialization</code> option was set to <code>advanced</code> used when spawning the
process, the <code>message</code> argument can contain data that JSON is not able
to represent.
See <a href="#child_process_advanced_serialization">Advanced serialization for <code>child_process</code></a> for more details.</p>
<h3>Event: <code>'multipleResolves'</code><span><a class="mark" href="#process_event_multipleresolves" id="process_event_multipleresolves">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The resolution type. One of <code>'resolve'</code> or <code>'reject'</code>.</li>
<li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> The promise that resolved or rejected more than once.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The value with which the promise was either resolved or
rejected after the original resolve.</li>
</ul>
<p>The <code>'multipleResolves'</code> event is emitted whenever a <code>Promise</code> has been either:</p>
<ul>
<li>Resolved more than once.</li>
<li>Rejected more than once.</li>
<li>Rejected after resolve.</li>
<li>Resolved after reject.</li>
</ul>
<p>This is useful for tracking potential errors in an application while using the
<code>Promise</code> constructor, as multiple resolutions are silently swallowed. However,
the occurrence of this event does not necessarily indicate an error. For
example, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race"><code>Promise.race()</code></a> can trigger a <code>'multipleResolves'</code> event.</p>
<pre><code class="language-js">process.on('multipleResolves', (type, promise, reason) => {
  console.error(type, promise, reason);
  setImmediate(() => process.exit(1));
});

async function main() {
  try {
    return await new Promise((resolve, reject) => {
      resolve('First call');
      resolve('Swallowed resolve');
      reject(new Error('Swallowed reject'));
    });
  } catch {
    throw new Error('Failed');
  }
}

main().then(console.log);
// resolve: Promise { 'First call' } 'Swallowed resolve'
// reject: Promise { 'First call' } Error: Swallowed reject
//     at Promise (*)
//     at new Promise (&#x3C;anonymous>)
//     at main (*)
// First call
</code></pre>
<h3>Event: <code>'rejectionHandled'</code><span><a class="mark" href="#process_event_rejectionhandled" id="process_event_rejectionhandled">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.4.1</span>
</div>
<ul>
<li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> The late handled promise.</li>
</ul>
<p>The <code>'rejectionHandled'</code> event is emitted whenever a <code>Promise</code> has been rejected
and an error handler was attached to it (using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch"><code>promise.catch()</code></a>, for
example) later than one turn of the Node.js event loop.</p>
<p>The <code>Promise</code> object would have previously been emitted in an
<code>'unhandledRejection'</code> event, but during the course of processing gained a
rejection handler.</p>
<p>There is no notion of a top level for a <code>Promise</code> chain at which rejections can
always be handled. Being inherently asynchronous in nature, a <code>Promise</code>
rejection can be handled at a future point in time, possibly much later than
the event loop turn it takes for the <code>'unhandledRejection'</code> event to be emitted.</p>
<p>Another way of stating this is that, unlike in synchronous code where there is
an ever-growing list of unhandled exceptions, with Promises there can be a
growing-and-shrinking list of unhandled rejections.</p>
<p>In synchronous code, the <code>'uncaughtException'</code> event is emitted when the list of
unhandled exceptions grows.</p>
<p>In asynchronous code, the <code>'unhandledRejection'</code> event is emitted when the list
of unhandled rejections grows, and the <code>'rejectionHandled'</code> event is emitted
when the list of unhandled rejections shrinks.</p>
<pre><code class="language-js">const unhandledRejections = new Map();
process.on('unhandledRejection', (reason, promise) => {
  unhandledRejections.set(promise, reason);
});
process.on('rejectionHandled', (promise) => {
  unhandledRejections.delete(promise);
});
</code></pre>
<p>In this example, the <code>unhandledRejections</code> <code>Map</code> will grow and shrink over time,
reflecting rejections that start unhandled and then become handled. It is
possible to record such errors in an error log, either periodically (which is
likely best for long-running application) or upon process exit (which is likely
most convenient for scripts).</p>
<h3>Event: <code>'uncaughtException'</code><span><a class="mark" href="#process_event_uncaughtexception" id="process_event_uncaughtexception">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Added the <code>origin</code> argument.</p></td></tr>
<tr><td>v0.1.18</td>
<td><p><span>Added in: v0.1.18</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> The uncaught exception.</li>
<li><code>origin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Indicates if the exception originates from an unhandled
rejection or from an synchronous error. Can either be <code>'uncaughtException'</code> or
<code>'unhandledRejection'</code>. The latter is only used in conjunction with the
<a href="#cli_unhandled_rejections_mode"><code>--unhandled-rejections</code></a> flag set to <code>strict</code> and an unhandled rejection.</li>
</ul>
<p>The <code>'uncaughtException'</code> event is emitted when an uncaught JavaScript
exception bubbles all the way back to the event loop. By default, Node.js
handles such exceptions by printing the stack trace to <code>stderr</code> and exiting
with code 1, overriding any previously set <a href="#process_process_exitcode"><code>process.exitCode</code></a>.
Adding a handler for the <code>'uncaughtException'</code> event overrides this default
behavior. Alternatively, change the <a href="#process_process_exitcode"><code>process.exitCode</code></a> in the
<code>'uncaughtException'</code> handler which will result in the process exiting with the
provided exit code. Otherwise, in the presence of such handler the process will
exit with 0.</p>
<pre><code class="language-js">process.on('uncaughtException', (err, origin) => {
  fs.writeSync(
    process.stderr.fd,
    `Caught exception: ${err}\n` +
    `Exception origin: ${origin}`
  );
});

setTimeout(() => {
  console.log('This will still run.');
}, 500);

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
</code></pre>
<p>It is possible to monitor <code>'uncaughtException'</code> events without overriding the
default behavior to exit the process by installing a
<code>'uncaughtExceptionMonitor'</code> listener.</p>
<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><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 the power cord when upgrading a computer. Nine out of ten
times, nothing happens. But the tenth 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: <code>'uncaughtExceptionMonitor'</code><span><a class="mark" href="#process_event_uncaughtexceptionmonitor" id="process_event_uncaughtexceptionmonitor">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.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">&#x3C;Error></a> The uncaught exception.</li>
<li><code>origin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Indicates if the exception originates from an unhandled
rejection or from synchronous errors. Can either be <code>'uncaughtException'</code> or
<code>'unhandledRejection'</code>.</li>
</ul>
<p>The <code>'uncaughtExceptionMonitor'</code> event is emitted before an
<code>'uncaughtException'</code> event is emitted or a hook installed via
<a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> is called.</p>
<p>Installing an <code>'uncaughtExceptionMonitor'</code> listener does not change the behavior
once an <code>'uncaughtException'</code> event is emitted. The process will
still crash if no <code>'uncaughtException'</code> listener is installed.</p>
<pre><code class="language-js">process.on('uncaughtExceptionMonitor', (err, origin) => {
  MyMonitoringTool.logSync(err, origin);
});

// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
// Still crashes Node.js
</code></pre>
<h3>Event: <code>'unhandledRejection'</code><span><a class="mark" href="#process_event_unhandledrejection" id="process_event_unhandledrejection">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>Not handling <code>Promise</code> rejections is deprecated.</p></td></tr>
<tr><td>v6.6.0</td>
<td><p>Unhandled <code>Promise</code> rejections will now emit a process warning.</p></td></tr>
<tr><td>v1.4.1</td>
<td><p><span>Added in: v1.4.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The object with which the promise was rejected
(typically an <a href="#errors_class_error"><code>Error</code></a> object).</li>
<li><code>promise</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> The rejected promise.</li>
</ul>
<p>The <code>'unhandledRejection'</code> event is emitted whenever a <code>Promise</code> is rejected and
no error handler is attached to the promise within a turn of the event loop.
When programming with Promises, exceptions are encapsulated as "rejected
promises". Rejections can be caught and handled using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch"><code>promise.catch()</code></a> and
are propagated through a <code>Promise</code> chain. The <code>'unhandledRejection'</code> event is
useful for detecting and keeping track of promises that were rejected whose
rejections have not yet been handled.</p>
<pre><code class="language-js">process.on('unhandledRejection', (reason, promise) => {
  console.log('Unhandled Rejection at:', promise, 'reason:', reason);
  // Application specific logging, throwing an error, or other logic here
});

somePromise.then((res) => {
  return reportToUser(JSON.pasre(res)); // Note the typo (`pasre`)
}); // No `.catch()` or `.then()`
</code></pre>
<p>The following will also trigger the <code>'unhandledRejection'</code> event to be
emitted:</p>
<pre><code class="language-js">function SomeResource() {
  // Initially set the loaded status to a rejected promise
  this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
}

const resource = new SomeResource();
// no .catch or .then on resource.loaded for at least a turn
</code></pre>
<p>In this example case, it is possible to track the rejection as a developer error
as would typically be the case for other <code>'unhandledRejection'</code> events. To
address such failures, a non-operational
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch"><code>.catch(() => { })</code></a> handler may be attached to
<code>resource.loaded</code>, which would prevent the <code>'unhandledRejection'</code> event from
being emitted.</p>
<h3>Event: <code>'warning'</code><span><a class="mark" href="#process_event_warning" id="process_event_warning">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<ul>
<li>
<p><code>warning</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> Key properties of the warning are:</p>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The name of the warning. <strong>Default:</strong> <code>'Warning'</code>.</li>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> A stack trace to the location in the code where the warning
was issued.</li>
</ul>
</li>
</ul>
<p>The <code>'warning'</code> event is emitted whenever Node.js emits a process warning.</p>
<p>A process warning is similar to an error in that it describes exceptional
conditions that are being brought to the user's attention. However, warnings
are not part of the normal Node.js and JavaScript error handling flow.
Node.js can emit warnings whenever it detects bad coding practices that could
lead to sub-optimal application performance, bugs, or security vulnerabilities.</p>
<pre><code class="language-js">process.on('warning', (warning) => {
  console.warn(warning.name);    // Print the warning name
  console.warn(warning.message); // Print the warning message
  console.warn(warning.stack);   // Print the stack trace
});
</code></pre>
<p>By default, Node.js will print process warnings to <code>stderr</code>. The <code>--no-warnings</code>
command-line option can be used to suppress the default console output but the
<code>'warning'</code> event will still be emitted by the <code>process</code> object.</p>
<p>The following example illustrates the warning that is printed to <code>stderr</code> when
too many listeners have been added to an event:</p>
<pre><code class="language-console">$ node
> events.defaultMaxListeners = 1;
> process.on('foo', () => {});
> process.on('foo', () => {});
> (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak
detected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit
</code></pre>
<p>In contrast, the following example turns off the default warning output and
adds a custom handler to the <code>'warning'</code> event:</p>
<pre><code class="language-console">$ node --no-warnings
> const p = process.on('warning', (warning) => console.warn('Do not do that!'));
> events.defaultMaxListeners = 1;
> process.on('foo', () => {});
> process.on('foo', () => {});
> Do not do that!
</code></pre>
<p>The <code>--trace-warnings</code> command-line option can be used to have the default
console output for warnings include the full stack trace of the warning.</p>
<p>Launching Node.js using the <code>--throw-deprecation</code> command line flag will
cause custom deprecation warnings to be thrown as exceptions.</p>
<p>Using the <code>--trace-deprecation</code> command line flag will cause the custom
deprecation to be printed to <code>stderr</code> along with the stack trace.</p>
<p>Using the <code>--no-deprecation</code> command line flag will suppress all reporting
of the custom deprecation.</p>
<p>The <code>*-deprecation</code> command line flags only affect warnings that use the name
<code>'DeprecationWarning'</code>.</p>
<h4>Emitting custom warnings<span><a class="mark" href="#process_emitting_custom_warnings" id="process_emitting_custom_warnings">#</a></span></h4>
<p>See the <a href="#process_process_emitwarning_warning_type_code_ctor"><code>process.emitWarning()</code></a> method for issuing
custom or application-specific warnings.</p>
<h3>Signal events<span><a class="mark" href="#process_signal_events" id="process_signal_events">#</a></span></h3>


<p>Signal events will be emitted when the Node.js process receives a signal. Please
refer to <a href="http://man7.org/linux/man-pages/man7/signal.7.html"><code>signal(7)</code></a> for a listing of standard POSIX signal names such as
<code>'SIGINT'</code>, <code>'SIGHUP'</code>, etc.</p>
<p>Signals are not available on <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p>
<p>The signal handler will receive the signal's name (<code>'SIGINT'</code>,
<code>'SIGTERM'</code>, etc.) as the first argument.</p>
<p>The name of each event will be the uppercase common name for the signal (e.g.
<code>'SIGINT'</code> for <code>SIGINT</code> signals).</p>
<pre><code class="language-js">// Begin reading from stdin so the process does not exit.
process.stdin.resume();

process.on('SIGINT', () => {
  console.log('Received SIGINT. Press Control-D to exit.');
});

// Using a single function to handle multiple signals
function handle(signal) {
  console.log(`Received ${signal}`);
}

process.on('SIGINT', handle);
process.on('SIGTERM', handle);
</code></pre>
<ul>
<li><code>'SIGUSR1'</code> is reserved by Node.js to start the <a href="debugger.html">debugger</a>. It's possible to
install a listener but doing so might interfere with the debugger.</li>
<li><code>'SIGTERM'</code> and <code>'SIGINT'</code> have default handlers on non-Windows platforms that
reset the terminal mode before exiting with code <code>128 + signal number</code>. If one
of these signals has a listener installed, its default behavior will be
removed (Node.js will no longer exit).</li>
<li><code>'SIGPIPE'</code> is ignored by default. It can have a listener installed.</li>
<li><code>'SIGHUP'</code> is generated on Windows when the console window is closed, and on
other platforms under various similar conditions. See <a href="http://man7.org/linux/man-pages/man7/signal.7.html"><code>signal(7)</code></a>. It can have a
listener installed, however Node.js will be unconditionally terminated by
Windows about 10 seconds later. On non-Windows platforms, the default
behavior of <code>SIGHUP</code> is to terminate Node.js, but once a listener has been
installed its default behavior will be removed.</li>
<li><code>'SIGTERM'</code> is not supported on Windows, it can be listened on.</li>
<li><code>'SIGINT'</code> from the terminal is supported on all platforms, and can usually be
generated with <code>&#x3C;Ctrl>+C</code> (though this may be configurable). It is not
generated when <a href="#tty_readstream_setrawmode_mode">terminal raw mode</a> is enabled and <code>&#x3C;Ctrl>+C</code> is used.</li>
<li><code>'SIGBREAK'</code> is delivered on Windows when <code>&#x3C;Ctrl>+&#x3C;Break></code> is pressed, on
non-Windows platforms it can be listened on, but there is no way to send or
generate it.</li>
<li><code>'SIGWINCH'</code> is delivered when the console has been resized. On Windows, this
will only happen on write to the console when the cursor is being moved, or
when a readable tty is used in raw mode.</li>
<li><code>'SIGKILL'</code> cannot have a listener installed, it will unconditionally
terminate Node.js on all platforms.</li>
<li><code>'SIGSTOP'</code> cannot have a listener installed.</li>
<li><code>'SIGBUS'</code>, <code>'SIGFPE'</code>, <code>'SIGSEGV'</code> and <code>'SIGILL'</code>, when not raised
 artificially using <a href="http://man7.org/linux/man-pages/man2/kill.2.html"><code>kill(2)</code></a>, inherently leave the process in a state from
 which it is not safe to attempt to call JS listeners. Doing so might lead to
 the process hanging in an endless loop, since listeners attached using
 <code>process.on()</code> are called asynchronously and therefore unable to correct the
underlying problem.</li>
<li><code>0</code> can be sent to test for the existence of a process, it has no effect if
the process exists, but will throw an error if the process does not exist.</li>
</ul>
<p>Windows does not support signals so has no equivalent to termination by signal,
but Node.js offers some emulation with <a href="#process_process_kill_pid_signal"><code>process.kill()</code></a>, and
<a href="#child_process_subprocess_kill_signal"><code>subprocess.kill()</code></a>:</p>
<ul>
<li>Sending <code>SIGINT</code>, <code>SIGTERM</code>, and <code>SIGKILL</code> will cause the unconditional
termination of the target process, and afterwards, subprocess will report that
the process was terminated by signal.</li>
<li>Sending signal <code>0</code> can be used as a platform independent way to test for the
existence of a process.</li>
</ul>
<h2><code>process.abort()</code><span><a class="mark" href="#process_process_abort" id="process_process_abort">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<p>The <code>process.abort()</code> method causes the Node.js process to exit immediately and
generate a core file.</p>
<p>This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p>
<h2><code>process.allowedNodeEnvironmentFlags</code><span><a class="mark" href="#process_process_allowednodeenvironmentflags" id="process_process_allowednodeenvironmentflags">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set" class="type">&#x3C;Set></a></li>
</ul>
<p>The <code>process.allowedNodeEnvironmentFlags</code> property is a special,
read-only <code>Set</code> of flags allowable within the <a href="#cli_node_options_options"><code>NODE_OPTIONS</code></a>
environment variable.</p>
<p><code>process.allowedNodeEnvironmentFlags</code> extends <code>Set</code>, but overrides
<code>Set.prototype.has</code> to recognize several different possible flag
representations. <code>process.allowedNodeEnvironmentFlags.has()</code> will
return <code>true</code> in the following cases:</p>
<ul>
<li>Flags may omit leading single (<code>-</code>) or double (<code>--</code>) dashes; e.g.,
<code>inspect-brk</code> for <code>--inspect-brk</code>, or <code>r</code> for <code>-r</code>.</li>
<li>Flags passed through to V8 (as listed in <code>--v8-options</code>) may replace
one or more <em>non-leading</em> dashes for an underscore, or vice-versa;
e.g., <code>--perf_basic_prof</code>, <code>--perf-basic-prof</code>, <code>--perf_basic-prof</code>,
etc.</li>
<li>Flags may contain one or more equals (<code>=</code>) characters; all
characters after and including the first equals will be ignored;
e.g., <code>--stack-trace-limit=100</code>.</li>
<li>Flags <em>must</em> be allowable within <a href="#cli_node_options_options"><code>NODE_OPTIONS</code></a>.</li>
</ul>
<p>When iterating over <code>process.allowedNodeEnvironmentFlags</code>, flags will
appear only <em>once</em>; each will begin with one or more dashes. Flags
passed through to V8 will contain underscores instead of non-leading
dashes:</p>
<pre><code class="language-js">process.allowedNodeEnvironmentFlags.forEach((flag) => {
  // -r
  // --inspect-brk
  // --abort_on_uncaught_exception
  // ...
});
</code></pre>
<p>The methods <code>add()</code>, <code>clear()</code>, and <code>delete()</code> of
<code>process.allowedNodeEnvironmentFlags</code> do nothing, and will fail
silently.</p>
<p>If Node.js was compiled <em>without</em> <a href="#cli_node_options_options"><code>NODE_OPTIONS</code></a> support (shown in
<a href="#process_process_config"><code>process.config</code></a>), <code>process.allowedNodeEnvironmentFlags</code> will
contain what <em>would have</em> been allowable.</p>
<h2><code>process.arch</code><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">&#x3C;string></a></li>
</ul>
<p>The operating system CPU architecture for which the Node.js binary was compiled.
Possible values are: <code>'arm'</code>, <code>'arm64'</code>, <code>'ia32'</code>, <code>'mips'</code>,<code>'mipsel'</code>, <code>'ppc'</code>,
<code>'ppc64'</code>, <code>'s390'</code>, <code>'s390x'</code>, <code>'x32'</code>, and <code>'x64'</code>.</p>
<pre><code class="language-js">console.log(`This processor architecture is ${process.arch}`);
</code></pre>
<h2><code>process.argv</code><span><a class="mark" href="#process_process_argv" id="process_process_argv">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>The <code>process.argv</code> property returns an array containing the command line
arguments passed when the Node.js process was launched. The first element will
be <a href="#process_process_execpath"><code>process.execPath</code></a>. See <code>process.argv0</code> if access to the original value
of <code>argv[0]</code> is needed. The second element will be the path to the JavaScript
file being executed. The remaining elements will be any additional command line
arguments.</p>
<p>For example, assuming the following script for <code>process-args.js</code>:</p>
<pre><code class="language-js">// print process.argv
process.argv.forEach((val, index) => {
  console.log(`${index}: ${val}`);
});
</code></pre>
<p>Launching the Node.js process as:</p>
<pre><code class="language-console">$ node process-args.js one two=three four
</code></pre>
<p>Would generate the output:</p>
<pre><code class="language-text">0: /usr/local/bin/node
1: /Users/mjr/work/node/process-args.js
2: one
3: two=three
4: four
</code></pre>
<h2><code>process.argv0</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>process.argv0</code> property stores a read-only copy of the original value of
<code>argv[0]</code> passed when Node.js starts.</p>
<pre><code class="language-console">$ bash -c 'exec -a customArgv0 ./node'
> process.argv[0]
'/Volumes/code/external/node/out/Release/node'
> process.argv0
'customArgv0'
</code></pre>
<h2><code>process.channel</code><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">&#x3C;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><code>process.chdir(directory)</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>process.chdir()</code> method changes the current working directory of the
Node.js process or throws an exception if doing so fails (for instance, if
the specified <code>directory</code> does not exist).</p>
<pre><code class="language-js">console.log(`Starting directory: ${process.cwd()}`);
try {
  process.chdir('/tmp');
  console.log(`New directory: ${process.cwd()}`);
} catch (err) {
  console.error(`chdir: ${err}`);
}
</code></pre>
<p>This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p>
<h2><code>process.config</code><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">&#x3C;Object></a></li>
</ul>
<p>The <code>process.config</code> property returns an <code>Object</code> containing the JavaScript
representation of the configure options used to compile the current Node.js
executable. This is the same as the <code>config.gypi</code> file that was produced when
running the <code>./configure</code> script.</p>
<p>An example of the possible output looks like:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  target_defaults:
   { cflags: [],
     default_configuration: 'Release',
     defines: [],
     include_dirs: [],
     libraries: [] },
  variables:
   {
     host_arch: 'x64',
     napi_build_version: 5,
     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: 1
   }
}
</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><code>process.connected</code><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">&#x3C;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><code>process.cpuUsage([previousValue])</code><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">&#x3C;Object></a> A previous return value from calling
<code>process.cpuUsage()</code></li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>user</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>system</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
</li>
</ul>
<p>The <code>process.cpuUsage()</code> method returns the user and system CPU time usage of
the current process, in an object with properties <code>user</code> and <code>system</code>, whose
values are microsecond values (millionth of a second). These values measure time
spent in user and system code respectively, and may end up being greater than
actual elapsed time if multiple CPU cores are performing work for this process.</p>
<p>The result of a previous call to <code>process.cpuUsage()</code> can be passed as the
argument to the function, to get a diff reading.</p>
<pre><code class="language-js">const startUsage = process.cpuUsage();
// { user: 38579, system: 6986 }

// spin the CPU for 500 milliseconds
const now = Date.now();
while (Date.now() - now &#x3C; 500);

console.log(process.cpuUsage(startUsage));
// { user: 514883, system: 11226 }
</code></pre>
<h2><code>process.cwd()</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>process.cwd()</code> method returns the current working directory of the Node.js
process.</p>
<pre><code class="language-js">console.log(`Current directory: ${process.cwd()}`);
</code></pre>
<h2><code>process.debugPort</code><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">&#x3C;number></a></li>
</ul>
<p>The port used by the Node.js debugger when enabled.</p>
<pre><code class="language-js">process.debugPort = 5858;
</code></pre>
<h2><code>process.disconnect()</code><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 the same as calling
<a href="#child_process_subprocess_disconnect"><code>ChildProcess.disconnect()</code></a> from the parent process.</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><code>process.dlopen(module, filename[, flags])</code><span><a class="mark" href="#process_process_dlopen_module_filename_flags" id="process_process_dlopen_module_filename_flags">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>Added support for the <code>flags</code> argument.</p></td></tr>
<tr><td>v0.1.16</td>
<td><p><span>Added in: v0.1.16</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>module</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>flags</code> <a href="#os_dlopen_constants" class="type">&#x3C;os.constants.dlopen></a> <strong>Default:</strong> <code>os.constants.dlopen.RTLD_LAZY</code></li>
</ul>
<p>The <code>process.dlopen()</code> method allows to dynamically load shared
objects. It is primarily used by <code>require()</code> to load
C++ Addons, and should not be used directly, except in special
cases. In other words, <a href="#globals_require"><code>require()</code></a> should be preferred over
<code>process.dlopen()</code>, unless there are specific reasons.</p>
<p>The <code>flags</code> argument is an integer that allows to specify dlopen
behavior. See the <a href="#os_dlopen_constants"><code>os.constants.dlopen</code></a> documentation for details.</p>
<p>If there are specific reasons to use <code>process.dlopen()</code> (for instance,
to specify dlopen flags), it's often useful to use <a href="#modules_require_resolve_request_options"><code>require.resolve()</code></a>
to look up the module's path.</p>
<p>An important drawback when calling <code>process.dlopen()</code> is that the <code>module</code>
instance must be passed. Functions exported by the C++ Addon will be accessible
via <code>module.exports</code>.</p>
<p>The example below shows how to load a C++ Addon, named as <code>binding</code>,
that exports a <code>foo</code> function. All the symbols will be loaded before
the call returns, by passing the <code>RTLD_NOW</code> constant. In this example
the constant is assumed to be available.</p>
<pre><code class="language-js">const os = require('os');
process.dlopen(module, require.resolve('binding'),
               os.constants.dlopen.RTLD_NOW);
module.exports.foo();
</code></pre>
<h2><code>process.emitWarning(warning[, options])</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> The warning to emit.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> When <code>warning</code> is a <code>String</code>, <code>type</code> is the name to use
for the <em>type</em> of warning being emitted. <strong>Default:</strong> <code>'Warning'</code>.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Function></a> When <code>warning</code> is a <code>String</code>, <code>ctor</code> is an optional
function used to limit the generated stack trace. <strong>Default:</strong>
<code>process.emitWarning</code>.</li>
<li><code>detail</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Additional text to include with the error.</li>
</ul>
</li>
</ul>
<p>The <code>process.emitWarning()</code> method can be used to emit custom or application
specific process warnings. These can be listened for by adding a handler to the
<a href="#process_event_warning"><code>'warning'</code></a> event.</p>
<pre><code class="language-js">// Emit a warning with a code and additional detail.
process.emitWarning('Something happened!', {
  code: 'MY_WARNING',
  detail: 'This is some additional information'
});
// Emits:
// (node:56338) [MY_WARNING] Warning: Something happened!
// This is some additional information
</code></pre>
<p>In this example, an <code>Error</code> object is generated internally by
<code>process.emitWarning()</code> and passed through to the
<a href="#process_event_warning"><code>'warning'</code></a> handler.</p>
<pre><code class="language-js">process.on('warning', (warning) => {
  console.warn(warning.name);    // 'Warning'
  console.warn(warning.message); // 'Something happened!'
  console.warn(warning.code);    // 'MY_WARNING'
  console.warn(warning.stack);   // Stack trace
  console.warn(warning.detail);  // 'This is some additional information'
});
</code></pre>
<p>If <code>warning</code> is passed as an <code>Error</code> object, the <code>options</code> argument is ignored.</p>
<h2><code>process.emitWarning(warning[, type[, code]][, ctor])</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;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">&#x3C;string></a> When <code>warning</code> is a <code>String</code>, <code>type</code> is the name to use
for the <em>type</em> of warning being emitted. <strong>Default:</strong> <code>'Warning'</code>.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Function></a> When <code>warning</code> is a <code>String</code>, <code>ctor</code> is an optional
function used to limit the generated stack trace. <strong>Default:</strong>
<code>process.emitWarning</code>.</li>
</ul>
<p>The <code>process.emitWarning()</code> method can be used to emit custom or application
specific process warnings. These can be listened for by adding a handler to the
<a href="#process_event_warning"><code>'warning'</code></a> event.</p>
<pre><code class="language-js">// Emit a warning using a string.
process.emitWarning('Something happened!');
// Emits: (node: 56338) Warning: Something happened!
</code></pre>
<pre><code class="language-js">// Emit a warning using a string and a type.
process.emitWarning('Something Happened!', 'CustomWarning');
// Emits: (node:56338) CustomWarning: Something Happened!
</code></pre>
<pre><code class="language-js">process.emitWarning('Something happened!', 'CustomWarning', 'WARN001');
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
</code></pre>
<p>In each of the previous examples, an <code>Error</code> object is generated internally by
<code>process.emitWarning()</code> and passed through to the <a href="#process_event_warning"><code>'warning'</code></a>
handler.</p>
<pre><code class="language-js">process.on('warning', (warning) => {
  console.warn(warning.name);
  console.warn(warning.message);
  console.warn(warning.code);
  console.warn(warning.stack);
});
</code></pre>
<p>If <code>warning</code> is passed as an <code>Error</code> object, it will be passed through to the
<code>'warning'</code> event handler unmodified (and the optional <code>type</code>,
<code>code</code> and <code>ctor</code> arguments will be ignored):</p>
<pre><code class="language-js">// Emit a warning using an Error object.
const myWarning = new Error('Something happened!');
// Use the Error name property to specify the type name
myWarning.name = 'CustomWarning';
myWarning.code = 'WARN001';

process.emitWarning(myWarning);
// Emits: (node:56338) [WARN001] CustomWarning: Something happened!
</code></pre>
<p>A <code>TypeError</code> is thrown if <code>warning</code> is anything other than a string or <code>Error</code>
object.</p>
<p>While process warnings use <code>Error</code> objects, the process warning
mechanism is <strong>not</strong> a replacement for normal error handling mechanisms.</p>
<p>The following additional handling is implemented if the warning <code>type</code> is
<code>'DeprecationWarning'</code>:</p>
<ul>
<li>If the <code>--throw-deprecation</code> command-line flag is used, the deprecation
warning is thrown as an exception rather than being emitted as an event.</li>
<li>If the <code>--no-deprecation</code> command-line flag is used, the deprecation
warning is suppressed.</li>
<li>If the <code>--trace-deprecation</code> command-line flag is used, the deprecation
warning is printed to <code>stderr</code> along with the full stack trace.</li>
</ul>
<h3>Avoiding duplicate warnings<span><a class="mark" href="#process_avoiding_duplicate_warnings" id="process_avoiding_duplicate_warnings">#</a></span></h3>
<p>As a best practice, warnings should be emitted only once per process. To do
so, it is recommended to place the <code>emitWarning()</code> behind a simple boolean
flag as illustrated in the example below:</p>
<pre><code class="language-js">function emitMyWarning() {
  if (!emitMyWarning.warned) {
    emitMyWarning.warned = true;
    process.emitWarning('Only warn once!');
  }
}
emitMyWarning();
// Emits: (node: 56339) Warning: Only warn once!
emitMyWarning();
// Emits nothing
</code></pre>
<h2><code>process.env</code><span><a class="mark" href="#process_process_env" id="process_process_env">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.14.0</td>
<td><p>Worker threads will now use a copy of the parent thread’s <code>process.env</code> by default, configurable through the <code>env</code> option of the <code>Worker</code> constructor.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Implicit conversion of variable value to string is deprecated.</p></td></tr>
<tr><td>v0.1.27</td>
<td><p><span>Added in: v0.1.27</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>The <code>process.env</code> property returns an object containing the user environment.
See <a href="http://man7.org/linux/man-pages/man7/environ.7.html"><code>environ(7)</code></a>.</p>
<p>An example of this object looks like:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  TERM: 'xterm-256color',
  SHELL: '/usr/local/bin/bash',
  USER: 'maciej',
  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
  PWD: '/Users/maciej',
  EDITOR: 'vim',
  SHLVL: '1',
  HOME: '/Users/maciej',
  LOGNAME: 'maciej',
  _: '/usr/local/bin/node'
}
</code></pre>
<p>It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.
In other words, the following example would not work:</p>
<pre><code class="language-console">$ node -e 'process.env.foo = "bar"' &#x26;&#x26; echo $foo
</code></pre>
<p>While the following will:</p>
<pre><code class="language-js">process.env.foo = 'bar';
console.log(process.env.foo);
</code></pre>
<p>Assigning a property on <code>process.env</code> will implicitly convert the value
to a string. <strong>This behavior is deprecated.</strong> Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.</p>
<pre><code class="language-js">process.env.test = null;
console.log(process.env.test);
// => 'null'
process.env.test = undefined;
console.log(process.env.test);
// => 'undefined'
</code></pre>
<p>Use <code>delete</code> to delete a property from <code>process.env</code>.</p>
<pre><code class="language-js">process.env.TEST = 1;
delete process.env.TEST;
console.log(process.env.TEST);
// => undefined
</code></pre>
<p>On Windows operating systems, environment variables are case-insensitive.</p>
<pre><code class="language-js">process.env.TEST = 1;
console.log(process.env.test);
// => 1
</code></pre>
<p>Unless explicitly specified when creating a <a href="#worker_threads_class_worker"><code>Worker</code></a> instance,
each <a href="#worker_threads_class_worker"><code>Worker</code></a> thread has its own copy of <code>process.env</code>, based on its
parent thread’s <code>process.env</code>, or whatever was specified as the <code>env</code> option
to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor. Changes to <code>process.env</code> will not be visible
across <a href="#worker_threads_class_worker"><code>Worker</code></a> threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons.</p>
<h2><code>process.execArgv</code><span><a class="mark" href="#process_process_execargv" id="process_process_execargv">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>The <code>process.execArgv</code> property returns the set of Node.js-specific command-line
options passed when the Node.js process was launched. These options do not
appear in the array returned by the <a href="#process_process_argv"><code>process.argv</code></a> property, and do not
include the Node.js executable, the name of the script, or any options following
the script name. These options are useful in order to spawn child processes with
the same execution environment as the parent.</p>
<pre><code class="language-console">$ node --harmony script.js --version
</code></pre>
<p>Results in <code>process.execArgv</code>:</p>
<!-- eslint-disable semi -->
<pre><code class="language-js">['--harmony']
</code></pre>
<p>And <code>process.argv</code>:</p>
<!-- eslint-disable semi -->
<pre><code class="language-js">['/usr/local/bin/node', 'script.js', '--version']
</code></pre>
<h2><code>process.execPath</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>process.execPath</code> property returns the absolute pathname of the executable
that started the Node.js process.</p>
<!-- eslint-disable semi -->
<pre><code class="language-js">'/usr/local/bin/node'
</code></pre>
<h2><code>process.exit([code])</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">&#x3C;integer></a> The exit code. <strong>Default:</strong> <code>0</code>.</li>
</ul>
<p>The <code>process.exit()</code> method instructs Node.js to terminate the process
synchronously with an exit status of <code>code</code>. If <code>code</code> is omitted, exit uses
either the 'success' code <code>0</code> or the value of <code>process.exitCode</code> if it has been
set. Node.js will not terminate until all the <a href="#process_event_exit"><code>'exit'</code></a> event listeners are
called.</p>
<p>To exit with a 'failure' code:</p>
<pre><code class="language-js">process.exit(1);
</code></pre>
<p>The shell that executed Node.js should see the exit code as <code>1</code>.</p>
<p>Calling <code>process.exit()</code> will force the process to exit as quickly as possible
even if there are still asynchronous operations pending that have not yet
completed fully, including I/O operations to <code>process.stdout</code> and
<code>process.stderr</code>.</p>
<p>In most situations, it is not actually necessary to call <code>process.exit()</code>
explicitly. The Node.js process will exit on its own <em>if there is no additional
work pending</em> in the event loop. The <code>process.exitCode</code> property can be set to
tell the process which exit code to use when the process exits gracefully.</p>
<p>For instance, the following example illustrates a <em>misuse</em> of the
<code>process.exit()</code> method that could lead to data printed to stdout being
truncated and lost:</p>
<pre><code class="language-js">// This is an example of what *not* to do:
if (someConditionNotMet()) {
  printUsageToStdout();
  process.exit(1);
}
</code></pre>
<p>The reason this is problematic is because writes to <code>process.stdout</code> in Node.js
are sometimes <em>asynchronous</em> and may occur over multiple ticks of the Node.js
event loop. Calling <code>process.exit()</code>, however, forces the process to exit
<em>before</em> those additional writes to <code>stdout</code> can be performed.</p>
<p>Rather than calling <code>process.exit()</code> directly, the code <em>should</em> set the
<code>process.exitCode</code> and allow the process to exit naturally by avoiding
scheduling any additional work for the event loop:</p>
<pre><code class="language-js">// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
  printUsageToStdout();
  process.exitCode = 1;
}
</code></pre>
<p>If it is necessary to terminate the Node.js process due to an error condition,
throwing an <em>uncaught</em> error and allowing the process to terminate accordingly
is safer than calling <code>process.exit()</code>.</p>
<p>In <a href="#worker_threads_class_worker"><code>Worker</code></a> threads, this function stops the current thread rather
than the current process.</p>
<h2><code>process.exitCode</code><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">&#x3C;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><code>process.getegid()</code><span><a class="mark" href="#process_process_getegid" id="process_process_getegid">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div>
<p>The <code>process.getegid()</code> method returns the numerical effective group identity
of the Node.js process. (See <a href="http://man7.org/linux/man-pages/man2/getegid.2.html"><code>getegid(2)</code></a>.)</p>
<pre><code class="language-js">if (process.getegid) {
  console.log(`Current gid: ${process.getegid()}`);
}
</code></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
<h2><code>process.geteuid()</code><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">&#x3C;Object></a></li>
</ul>
<p>The <code>process.geteuid()</code> method returns the numerical effective user identity of
the process. (See <a href="http://man7.org/linux/man-pages/man2/geteuid.2.html"><code>geteuid(2)</code></a>.)</p>
<pre><code class="language-js">if (process.geteuid) {
  console.log(`Current uid: ${process.geteuid()}`);
}
</code></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
<h2><code>process.getgid()</code><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">&#x3C;Object></a></li>
</ul>
<p>The <code>process.getgid()</code> method returns the numerical group identity of the
process. (See <a href="http://man7.org/linux/man-pages/man2/getgid.2.html"><code>getgid(2)</code></a>.)</p>
<pre><code class="language-js">if (process.getgid) {
  console.log(`Current gid: ${process.getgid()}`);
}
</code></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
<h2><code>process.getgroups()</code><span><a class="mark" href="#process_process_getgroups" id="process_process_getgroups">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer[]></a></li>
</ul>
<p>The <code>process.getgroups()</code> method returns an array with the supplementary group
IDs. POSIX leaves it unspecified if the effective group ID is included but
Node.js ensures it always is.</p>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
<h2><code>process.getuid()</code><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">&#x3C;integer></a></li>
</ul>
<p>The <code>process.getuid()</code> method returns the numeric user identity of the process.
(See <a href="http://man7.org/linux/man-pages/man2/getuid.2.html"><code>getuid(2)</code></a>.)</p>
<pre><code class="language-js">if (process.getuid) {
  console.log(`Current uid: ${process.getuid()}`);
}
</code></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
<h2><code>process.hasUncaughtExceptionCaptureCallback()</code><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">&#x3C;boolean></a></li>
</ul>
<p>Indicates whether a callback has been set using
<a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a>.</p>
<h2><code>process.hrtime([time])</code><span><a class="mark" href="#process_process_hrtime_time" id="process_process_hrtime_time">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.6</span>
</div>
<ul>
<li><code>time</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer[]></a> The result of a previous call to <code>process.hrtime()</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer[]></a></li>
</ul>
<p>This is the legacy version of <a href="#process_process_hrtime_bigint"><code>process.hrtime.bigint()</code></a>
before <code>bigint</code> was introduced in JavaScript.</p>
<p>The <code>process.hrtime()</code> method returns the current high-resolution real time
in a <code>[seconds, nanoseconds]</code> tuple <code>Array</code>, where <code>nanoseconds</code> is the
remaining part of the real time that can't be represented in second precision.</p>
<p><code>time</code> is an optional parameter that must be the result of a previous
<code>process.hrtime()</code> call to diff with the current time. If the parameter
passed in is not a tuple <code>Array</code>, a <code>TypeError</code> will be thrown. Passing in a
user-defined array instead of the result of a previous call to
<code>process.hrtime()</code> will lead to undefined behavior.</p>
<p>These times are relative to an arbitrary time in the
past, and not related to the time of day and therefore not subject to clock
drift. The primary use is for measuring performance between intervals:</p>
<pre><code class="language-js">const NS_PER_SEC = 1e9;
const time = process.hrtime();
// [ 1800216, 25 ]

setTimeout(() => {
  const diff = process.hrtime(time);
  // [ 1, 552 ]

  console.log(`Benchmark took ${diff[0] * NS_PER_SEC + diff[1]} nanoseconds`);
  // Benchmark took 1000000552 nanoseconds
}, 1000);
</code></pre>
<h2><code>process.hrtime.bigint()</code><span><a class="mark" href="#process_process_hrtime_bigint" id="process_process_hrtime_bigint">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>The <code>bigint</code> version of the <a href="#process_process_hrtime_time"><code>process.hrtime()</code></a> method returning the
current high-resolution real time in nanoseconds as a <code>bigint</code>.</p>
<p>Unlike <a href="#process_process_hrtime_time"><code>process.hrtime()</code></a>, it does not support an additional <code>time</code>
argument since the difference can just be computed directly
by subtraction of the two <code>bigint</code>s.</p>
<pre><code class="language-js">const start = process.hrtime.bigint();
// 191051479007711n

setTimeout(() => {
  const end = process.hrtime.bigint();
  // 191052633396993n

  console.log(`Benchmark took ${end - start} nanoseconds`);
  // Benchmark took 1154389282 nanoseconds
}, 1000);
</code></pre>
<h2><code>process.initgroups(user, extraGroup)</code><span><a class="mark" href="#process_process_initgroups_user_extragroup" id="process_process_initgroups_user_extragroup">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>user</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The user name or numeric identifier.</li>
<li><code>extraGroup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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>Use care when dropping privileges:</p>
<pre><code class="language-js">console.log(process.getgroups());         // [ 0 ]
process.initgroups('bnoordhuis', 1000);   // switch user
console.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]
process.setgid(1000);                     // drop root gid
console.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
</code></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p>
<h2><code>process.kill(pid[, signal])</code><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">&#x3C;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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The signal to send, either as a string or number.
<strong>Default:</strong> <code>'SIGTERM'</code>.</li>
</ul>
<p>The <code>process.kill()</code> method sends the <code>signal</code> to the process identified by
<code>pid</code>.</p>
<p>Signal names are strings such as <code>'SIGINT'</code> or <code>'SIGHUP'</code>. See <a href="#process_signal_events">Signal Events</a>
and <a href="http://man7.org/linux/man-pages/man2/kill.2.html"><code>kill(2)</code></a> for more information.</p>
<p>This method will throw an error if the target <code>pid</code> does not exist. As a special
case, a signal of <code>0</code> can be used to test for the existence of a process.
Windows platforms will throw an error if the <code>pid</code> is used to kill a process
group.</p>
<p>Even though the name of this function is <code>process.kill()</code>, it is really just a
signal sender, like the <code>kill</code> system call. The signal sent may do something
other than kill the target process.</p>
<pre><code class="language-js">process.on('SIGHUP', () => {
  console.log('Got SIGHUP signal.');
});

setTimeout(() => {
  console.log('Exiting.');
  process.exit(0);
}, 100);

process.kill(process.pid, 'SIGHUP');
</code></pre>
<p>When <code>SIGUSR1</code> is received by a Node.js process, Node.js will start the
debugger. See <a href="#process_signal_events">Signal Events</a>.</p>
<h2><code>process.mainModule</code><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">&#x3C;Object></a></li>
</ul>
<p>The <code>process.mainModule</code> property provides an alternative way of retrieving
<a href="#modules_accessing_the_main_module"><code>require.main</code></a>. The difference is that if the main module changes at
runtime, <a href="#modules_accessing_the_main_module"><code>require.main</code></a> may still refer to the original main module in
modules that were required before the change occurred. Generally, it's
safe to assume that the two refer to the same module.</p>
<p>As with <a href="#modules_accessing_the_main_module"><code>require.main</code></a>, <code>process.mainModule</code> will be <code>undefined</code> if there
is no entry script.</p>
<h2><code>process.memoryUsage()</code><span><a class="mark" href="#process_process_memoryusage" id="process_process_memoryusage">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>Added <code>arrayBuffers</code> to the returned object.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>Added <code>external</code> to the returned object.</p></td></tr>
<tr><td>v0.1.16</td>
<td><p><span>Added in: v0.1.16</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>rss</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>heapTotal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>heapUsed</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>external</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>arrayBuffers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
</li>
</ul>
<p>The <code>process.memoryUsage()</code> method returns an object describing the memory usage
of the Node.js process measured in bytes.</p>
<p>For example, the code:</p>
<pre><code class="language-js">console.log(process.memoryUsage());
</code></pre>
<p>Will generate:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  rss: 4935680,
  heapTotal: 1826816,
  heapUsed: 650472,
  external: 49879,
  arrayBuffers: 9386
}
</code></pre>
<ul>
<li><code>heapTotal</code> and <code>heapUsed</code> refer to V8's memory usage.</li>
<li><code>external</code> refers to the memory usage of C++ objects bound to JavaScript
objects managed by V8.</li>
<li><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, including all C++ and JavaScript objects and code.</li>
<li><code>arrayBuffers</code> refers to memory allocated for <code>ArrayBuffer</code>s and
<code>SharedArrayBuffer</code>s, including all Node.js <a href="buffer.html"><code>Buffer</code></a>s.
This is also included in the <code>external</code> value. When Node.js is used as an
embedded library, this value may be <code>0</code> because allocations for <code>ArrayBuffer</code>s
may not be tracked in that case.</li>
</ul>
<p>When using <a href="#worker_threads_class_worker"><code>Worker</code></a> threads, <code>rss</code> will be a value that is valid for the
entire process, while the other fields will only refer to the current thread.</p>
<h2><code>process.nextTick(callback[, ...args])</code><span><a class="mark" href="#process_process_nexttick_callback_args" id="process_process_nexttick_callback_args">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v1.8.1</td>
<td><p>Additional arguments after <code>callback</code> are now supported.</p></td></tr>
<tr><td>v0.1.26</td>
<td><p><span>Added in: v0.1.26</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Additional arguments to pass when invoking the <code>callback</code></li>
</ul>
<p><code>process.nextTick()</code> adds <code>callback</code> to the "next tick queue". This queue is
fully drained after the current operation on the JavaScript stack runs to
completion and before the event loop is allowed to continue. It's possible to
create an infinite loop if one were to recursively call <code>process.nextTick()</code>.
See the <a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick">Event Loop</a> guide for more background.</p>
<pre><code class="language-js">console.log('start');
process.nextTick(() => {
  console.log('nextTick callback');
});
console.log('scheduled');
// Output:
// start
// scheduled
// nextTick callback
</code></pre>
<p>This is important when developing APIs in order to give users the opportunity
to assign event handlers <em>after</em> an object has been constructed but before any
I/O has occurred:</p>
<pre><code class="language-js">function MyThing(options) {
  this.setupOptions(options);

  process.nextTick(() => {
    this.startDoingStuff();
  });
}

const thing = new MyThing();
thing.getReadyForStuff();

// thing.startDoingStuff() gets called now, not before.
</code></pre>
<p>It is very important for APIs to be either 100% synchronous or 100%
asynchronous. Consider this example:</p>
<pre><code class="language-js">// WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!
function maybeSync(arg, cb) {
  if (arg) {
    cb();
    return;
  }

  fs.stat('file', cb);
}
</code></pre>
<p>This API is hazardous because in the following case:</p>
<pre><code class="language-js">const maybeTrue = Math.random() > 0.5;

maybeSync(maybeTrue, () => {
  foo();
});

bar();
</code></pre>
<p>It is not clear whether <code>foo()</code> or <code>bar()</code> will be called first.</p>
<p>The following approach is much better:</p>
<pre><code class="language-js">function definitelyAsync(arg, cb) {
  if (arg) {
    process.nextTick(cb);
    return;
  }

  fs.stat('file', cb);
}
</code></pre>
<h2><code>process.noDeprecation</code><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">&#x3C;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><code>process.pid</code><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">&#x3C;integer></a></li>
</ul>
<p>The <code>process.pid</code> property returns the PID of the process.</p>
<pre><code class="language-js">console.log(`This process is pid ${process.pid}`);
</code></pre>
<h2><code>process.platform</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>process.platform</code> property returns a string identifying the operating
system platform on which the Node.js process is running.</p>
<p>Currently possible values are:</p>
<ul>
<li><code>'aix'</code></li>
<li><code>'darwin'</code></li>
<li><code>'freebsd'</code></li>
<li><code>'linux'</code></li>
<li><code>'openbsd'</code></li>
<li><code>'sunos'</code></li>
<li><code>'win32'</code></li>
</ul>
<pre><code class="language-js">console.log(`This platform is ${process.platform}`);
</code></pre>
<p>The value <code>'android'</code> may also be returned if the Node.js is built on the
Android operating system. However, Android support in Node.js
<a href="https://github.com/nodejs/node/blob/master/BUILDING.md#androidandroid-based-devices-eg-firefox-os">is experimental</a>.</p>
<h2><code>process.ppid</code><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, v8.10.0, v6.13.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>The <code>process.ppid</code> property returns the PID of the current parent process.</p>
<pre><code class="language-js">console.log(`The parent process is pid ${process.ppid}`);
</code></pre>
<h2><code>process.release</code><span><a class="mark" href="#process_process_release" id="process_process_release">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v4.2.0</td>
<td><p>The <code>lts</code> property is now supported.</p></td></tr>
<tr><td>v3.0.0</td>
<td><p><span>Added in: v3.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>The <code>process.release</code> property returns an <code>Object</code> containing metadata related
to the current release, including URLs for the source tarball and headers-only
tarball.</p>
<p><code>process.release</code> contains the following properties:</p>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;string></a> an absolute URL pointing to a <em><code>node.lib</code></em> file matching the
architecture and version of the current release. This file is used for
compiling Node.js native add-ons. <em>This property is only present on Windows
builds of Node.js and will be missing on all other platforms.</em></li>
<li>
<p><code>lts</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> a string label identifying the <a href="https://github.com/nodejs/Release">LTS</a> label for this release.
This property only exists for LTS releases and is <code>undefined</code> for all other
release types, including <em>Current</em> releases. Currently the valid values are:</p>
<ul>
<li><code>'Argon'</code> for the 4.x LTS line beginning with 4.2.0.</li>
<li><code>'Boron'</code> for the 6.x LTS line beginning with 6.9.0.</li>
<li><code>'Carbon'</code> for the 8.x LTS line beginning with 8.9.1.</li>
</ul>
</li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
  name: 'node',
  lts: 'Argon',
  sourceUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5.tar.gz',
  headersUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5-headers.tar.gz',
  libUrl: 'https://nodejs.org/download/release/v4.4.5/win-x64/node.lib'
}
</code></pre>
<p>In custom builds from non-release versions of the source tree, only the
<code>name</code> property may be present. The additional properties should not be
relied upon to exist.</p>
<h2><code>process.report</code><span><a class="mark" href="#process_process_report" id="process_process_report">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This API is no longer considered experimental.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p><code>process.report</code> is an object whose methods are used to generate diagnostic
reports for the current process. Additional documentation is available in the
<a href="report.html">report documentation</a>.</p>
<h3><code>process.report.compact</code><span><a class="mark" href="#process_process_report_compact" id="process_process_report_compact">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Write reports in a compact format, single-line JSON, more easily consumable
by log processing systems than the default multi-line format designed for
human consumption.</p>
<pre><code class="language-js">console.log(`Reports are compact? ${process.report.compact}`);
</code></pre>
<h3><code>process.report.directory</code><span><a class="mark" href="#process_process_report_directory" id="process_process_report_directory">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This API is no longer considered experimental.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p><span>Added in: v11.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Directory where the report is written. The default value is the empty string,
indicating that reports are written to the current working directory of the
Node.js process.</p>
<pre><code class="language-js">console.log(`Report directory is ${process.report.directory}`);
</code></pre>
<h3><code>process.report.filename</code><span><a class="mark" href="#process_process_report_filename" id="process_process_report_filename">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This API is no longer considered experimental.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p><span>Added in: v11.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Filename where the report is written. If set to the empty string, the output
filename will be comprised of a timestamp, PID, and sequence number. The default
value is the empty string.</p>
<pre><code class="language-js">console.log(`Report filename is ${process.report.filename}`);
</code></pre>
<h3><code>process.report.getReport([err])</code><span><a class="mark" href="#process_process_report_getreport_err" id="process_process_report_getreport_err">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This API is no longer considered experimental.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> A custom error used for reporting the JavaScript stack.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns a JavaScript Object representation of a diagnostic report for the
running process. The report's JavaScript stack trace is taken from <code>err</code>, if
present.</p>
<pre><code class="language-js">const data = process.report.getReport();
console.log(data.header.nodeJsVersion);

// Similar to process.report.writeReport()
const fs = require('fs');
fs.writeFileSync(util.inspect(data), 'my-report.log', 'utf8');
</code></pre>
<p>Additional documentation is available in the <a href="report.html">report documentation</a>.</p>
<h3><code>process.report.reportOnFatalError</code><span><a class="mark" href="#process_process_report_reportonfatalerror" id="process_process_report_reportonfatalerror">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>If <code>true</code>, a diagnostic report is generated on fatal errors, such as out of
memory errors or failed C++ assertions.</p>
<pre><code class="language-js">console.log(`Report on fatal error: ${process.report.reportOnFatalError}`);
</code></pre>
<h3><code>process.report.reportOnSignal</code><span><a class="mark" href="#process_process_report_reportonsignal" id="process_process_report_reportonsignal">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This API is no longer considered experimental.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p><span>Added in: v11.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>If <code>true</code>, a diagnostic report is generated when the process receives the
signal specified by <code>process.report.signal</code>.</p>
<pre><code class="language-js">console.log(`Report on signal: ${process.report.reportOnSignal}`);
</code></pre>
<h3><code>process.report.reportOnUncaughtException</code><span><a class="mark" href="#process_process_report_reportonuncaughtexception" id="process_process_report_reportonuncaughtexception">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This API is no longer considered experimental.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p><span>Added in: v11.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>If <code>true</code>, a diagnostic report is generated on uncaught exception.</p>
<pre><code class="language-js">console.log(`Report on exception: ${process.report.reportOnUncaughtException}`);
</code></pre>
<h3><code>process.report.signal</code><span><a class="mark" href="#process_process_report_signal" id="process_process_report_signal">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This API is no longer considered experimental.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p><span>Added in: v11.12.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The signal used to trigger the creation of a diagnostic report. Defaults to
<code>'SIGUSR2'</code>.</p>
<pre><code class="language-js">console.log(`Report signal: ${process.report.signal}`);
</code></pre>
<h3><code>process.report.writeReport([filename][, err])</code><span><a class="mark" href="#process_process_report_writereport_filename_err" id="process_process_report_writereport_filename_err">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>This API is no longer considered experimental.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p><span>Added in: v11.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of the file where the report is written. This
should be a relative path, that will be appended to the directory specified in
<code>process.report.directory</code>, or the current working directory of the Node.js
process, if unspecified.</p>
</li>
<li>
<p><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> A custom error used for reporting the JavaScript stack.</p>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Returns the filename of the generated report.</p>
</li>
</ul>
<p>Writes a diagnostic report to a file. If <code>filename</code> is not provided, the default
filename includes the date, time, PID, and a sequence number. The report's
JavaScript stack trace is taken from <code>err</code>, if present.</p>
<pre><code class="language-js">process.report.writeReport();
</code></pre>
<p>Additional documentation is available in the <a href="report.html">report documentation</a>.</p>
<h2><code>process.resourceUsage()</code><span><a class="mark" href="#process_process_resourceusage" id="process_process_resourceusage">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.6.0</span>
</div>
<ul>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> the resource usage for the current process. All of these
values come from the <code>uv_getrusage</code> call which returns
a <a href="http://docs.libuv.org/en/v1.x/misc.html#c.uv_rusage_t"><code>uv_rusage_t</code> struct</a>.</p>
<ul>
<li><code>userCPUTime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_utime</code> computed in microseconds.
It is the same value as <a href="#process_process_cpuusage_previousvalue"><code>process.cpuUsage().user</code></a>.</li>
<li><code>systemCPUTime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_stime</code> computed in microseconds.
It is the same value as <a href="#process_process_cpuusage_previousvalue"><code>process.cpuUsage().system</code></a>.</li>
<li><code>maxRSS</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_maxrss</code> which is the maximum resident set
size used in kilobytes.</li>
<li><code>sharedMemorySize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_ixrss</code> but is not supported by
any platform.</li>
<li><code>unsharedDataSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_idrss</code> but is not supported by
any platform.</li>
<li><code>unsharedStackSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_isrss</code> but is not supported by
any platform.</li>
<li><code>minorPageFault</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_minflt</code> which is the number of
minor page faults for the process, see
<a href="https://en.wikipedia.org/wiki/Page_fault#Minor">this article for more details</a>.</li>
<li><code>majorPageFault</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_majflt</code> which is the number of
major page faults for the process, see
<a href="https://en.wikipedia.org/wiki/Page_fault#Major">this article for more details</a>. This field is not
supported on Windows.</li>
<li><code>swappedOut</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_nswap</code> but is not supported by any
platform.</li>
<li><code>fsRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_inblock</code> which is the number of times the
file system had to perform input.</li>
<li><code>fsWrite</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_oublock</code> which is the number of times the
file system had to perform output.</li>
<li><code>ipcSent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_msgsnd</code> but is not supported by any
platform.</li>
<li><code>ipcReceived</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_msgrcv</code> but is not supported by any
platform.</li>
<li><code>signalsCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_nsignals</code> but is not supported by any
platform.</li>
<li><code>voluntaryContextSwitches</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_nvcsw</code> which is the
number of times a CPU context switch resulted due to a process voluntarily
giving up the processor before its time slice was completed (usually to
await availability of a resource). This field is not supported on Windows.</li>
<li><code>involuntaryContextSwitches</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> maps to <code>ru_nivcsw</code> which is the
number of times a CPU context switch resulted due to a higher priority
process becoming runnable or because the current process exceeded its
time slice. This field is not supported on Windows.</li>
</ul>
</li>
</ul>
<pre><code class="language-js">console.log(process.resourceUsage());
/*
  Will output:
  {
    userCPUTime: 82872,
    systemCPUTime: 4143,
    maxRSS: 33164,
    sharedMemorySize: 0,
    unsharedDataSize: 0,
    unsharedStackSize: 0,
    minorPageFault: 2469,
    majorPageFault: 0,
    swappedOut: 0,
    fsRead: 0,
    fsWrite: 8,
    ipcSent: 0,
    ipcReceived: 0,
    signalsCount: 0,
    voluntaryContextSwitches: 79,
    involuntaryContextSwitches: 1
  }
*/
</code></pre>
<h2><code>process.send(message[, sendHandle[, options]][, callback])</code><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">&#x3C;Object></a></li>
<li><code>sendHandle</code> <a href="#net_class_net_server" class="type">&#x3C;net.Server></a> | <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a></li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> used to parameterize the sending of certain types of
handles.<code>options</code> supports the following properties:</p>
<ul>
<li><code>keepOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A value that can be used when passing instances of
<code>net.Socket</code>. When <code>true</code>, the socket is kept open in the sending process.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>If Node.js is spawned with an IPC channel, the <code>process.send()</code> method can be
used to send messages to the parent process. Messages will be received as a
<a href="#child_process_event_message"><code>'message'</code></a> event on the parent's <a href="#child_process_class_childprocess"><code>ChildProcess</code></a> object.</p>
<p>If Node.js was not spawned with an IPC channel, <code>process.send</code> will be
<code>undefined</code>.</p>
<p>The message goes through serialization and parsing. The resulting message might
not be the same as what is originally sent.</p>
<h2><code>process.setegid(id)</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> A group name or ID</li>
</ul>
<p>The <code>process.setegid()</code> method sets the effective group identity of the process.
(See <a href="http://man7.org/linux/man-pages/man2/setegid.2.html"><code>setegid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a group
name string. If a group name is specified, this method blocks while resolving
the associated a numeric ID.</p>
<pre><code class="language-js">if (process.getegid &#x26;&#x26; process.setegid) {
  console.log(`Current gid: ${process.getegid()}`);
  try {
    process.setegid(501);
    console.log(`New gid: ${process.getegid()}`);
  } catch (err) {
    console.log(`Failed to set gid: ${err}`);
  }
}
</code></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p>
<h2><code>process.seteuid(id)</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> A user name or ID</li>
</ul>
<p>The <code>process.seteuid()</code> method sets the effective user identity of the process.
(See <a href="http://man7.org/linux/man-pages/man2/seteuid.2.html"><code>seteuid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a username
string. If a username is specified, the method blocks while resolving the
associated numeric ID.</p>
<pre><code class="language-js">if (process.geteuid &#x26;&#x26; process.seteuid) {
  console.log(`Current uid: ${process.geteuid()}`);
  try {
    process.seteuid(501);
    console.log(`New uid: ${process.geteuid()}`);
  } catch (err) {
    console.log(`Failed to set uid: ${err}`);
  }
}
</code></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p>
<h2><code>process.setgid(id)</code><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">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The group name or ID</li>
</ul>
<p>The <code>process.setgid()</code> method sets the group identity of the process. (See
<a href="http://man7.org/linux/man-pages/man2/setgid.2.html"><code>setgid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a group name
string. If a group name is specified, this method blocks while resolving the
associated numeric ID.</p>
<pre><code class="language-js">if (process.getgid &#x26;&#x26; process.setgid) {
  console.log(`Current gid: ${process.getgid()}`);
  try {
    process.setgid(501);
    console.log(`New gid: ${process.getgid()}`);
  } catch (err) {
    console.log(`Failed to set gid: ${err}`);
  }
}
</code></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p>
<h2><code>process.setgroups(groups)</code><span><a class="mark" href="#process_process_setgroups_groups" id="process_process_setgroups_groups">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>groups</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer[]></a></li>
</ul>
<p>The <code>process.setgroups()</code> method sets the supplementary group IDs for the
Node.js process. This is a privileged operation that requires the Node.js
process to have <code>root</code> or the <code>CAP_SETGID</code> capability.</p>
<p>The <code>groups</code> array can contain numeric group IDs, group names or both.</p>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p>
<h2><code>process.setuid(id)</code><span><a class="mark" href="#process_process_setuid_id" id="process_process_setuid_id">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.28</span>
</div>
<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>process.setuid(id)</code> method sets the user identity of the process. (See
<a href="http://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>.) The <code>id</code> can be passed as either a numeric ID or a username string.
If a username is specified, the method blocks while resolving the associated
numeric ID.</p>
<pre><code class="language-js">if (process.getuid &#x26;&#x26; process.setuid) {
  console.log(`Current uid: ${process.getuid()}`);
  try {
    process.setuid(501);
    console.log(`New uid: ${process.getuid()}`);
  } catch (err) {
    console.log(`Failed to set uid: ${err}`);
  }
}
</code></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p>
<h2><code>process.setUncaughtExceptionCaptureCallback(fn)</code><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">&#x3C;Function></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
</ul>
<p>The <code>process.setUncaughtExceptionCaptureCallback()</code> function sets a function
that will be invoked when an uncaught exception occurs, which will receive the
exception value itself as its first argument.</p>
<p>If such a function is set, the <a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a> event will
not be emitted. If <code>--abort-on-uncaught-exception</code> was passed from the
command line or set through <a href="#v8_v8_setflagsfromstring_flags"><code>v8.setFlagsFromString()</code></a>, the process will
not abort.</p>
<p>To unset the capture function,
<code>process.setUncaughtExceptionCaptureCallback(null)</code> may be used. Calling this
method with a non-<code>null</code> argument while another capture function is set will
throw an error.</p>
<p>Using this function is mutually exclusive with using the deprecated
<a href="domain.html"><code>domain</code></a> built-in module.</p>
<h2><code>process.stderr</code><span><a class="mark" href="#process_process_stderr" id="process_process_stderr">#</a></span></h2>
<ul>
<li><a href="#stream_stream" class="type">&#x3C;Stream></a></li>
</ul>
<p>The <code>process.stderr</code> property returns a stream connected to
<code>stderr</code> (fd <code>2</code>). It is a <a href="#net_class_net_socket"><code>net.Socket</code></a> (which is a <a href="#stream_duplex_and_transform_streams">Duplex</a>
stream) unless fd <code>2</code> refers to a file, in which case it is
a <a href="#stream_writable_streams">Writable</a> stream.</p>
<p><code>process.stderr</code> differs from other Node.js streams in important ways. See
<a href="#process_a_note_on_process_i_o">note on process I/O</a> for more information.</p>
<h3><code>process.stderr.fd</code><span><a class="mark" href="#process_process_stderr_fd" id="process_process_stderr_fd">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>This property refers to the value of underlying file descriptor of
<code>process.stderr</code>. The value is fixed at <code>2</code>. In <a href="#worker_threads_class_worker"><code>Worker</code></a> threads,
this field does not exist.</p>
<h2><code>process.stdin</code><span><a class="mark" href="#process_process_stdin" id="process_process_stdin">#</a></span></h2>
<ul>
<li><a href="#stream_stream" class="type">&#x3C;Stream></a></li>
</ul>
<p>The <code>process.stdin</code> property returns a stream connected to
<code>stdin</code> (fd <code>0</code>). It is a <a href="#net_class_net_socket"><code>net.Socket</code></a> (which is a <a href="#stream_duplex_and_transform_streams">Duplex</a>
stream) unless fd <code>0</code> refers to a file, in which case it is
a <a href="#stream_readable_streams">Readable</a> stream.</p>
<pre><code class="language-js">process.stdin.setEncoding('utf8');

process.stdin.on('readable', () => {
  let chunk;
  // Use a loop to make sure we read all available data.
  while ((chunk = process.stdin.read()) !== null) {
    process.stdout.write(`data: ${chunk}`);
  }
});

process.stdin.on('end', () => {
  process.stdout.write('end');
});
</code></pre>
<p>As a <a href="#stream_duplex_and_transform_streams">Duplex</a> stream, <code>process.stdin</code> can also be used in "old" mode that
is compatible with scripts written for Node.js prior to v0.10.
For more information see <a href="#stream_compatibility_with_older_node_js_versions">Stream compatibility</a>.</p>
<p>In "old" streams mode the <code>stdin</code> stream is paused by default, so one
must call <code>process.stdin.resume()</code> to read from it. Note also that calling
<code>process.stdin.resume()</code> itself would switch stream to "old" mode.</p>
<h3><code>process.stdin.fd</code><span><a class="mark" href="#process_process_stdin_fd" id="process_process_stdin_fd">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>This property refers to the value of underlying file descriptor of
<code>process.stdin</code>. The value is fixed at <code>0</code>. In <a href="#worker_threads_class_worker"><code>Worker</code></a> threads,
this field does not exist.</p>
<h2><code>process.stdout</code><span><a class="mark" href="#process_process_stdout" id="process_process_stdout">#</a></span></h2>
<ul>
<li><a href="#stream_stream" class="type">&#x3C;Stream></a></li>
</ul>
<p>The <code>process.stdout</code> property returns a stream connected to
<code>stdout</code> (fd <code>1</code>). It is a <a href="#net_class_net_socket"><code>net.Socket</code></a> (which is a <a href="#stream_duplex_and_transform_streams">Duplex</a>
stream) unless fd <code>1</code> refers to a file, in which case it is
a <a href="#stream_writable_streams">Writable</a> stream.</p>
<p>For example, to copy <code>process.stdin</code> to <code>process.stdout</code>:</p>
<pre><code class="language-js">process.stdin.pipe(process.stdout);
</code></pre>
<p><code>process.stdout</code> differs from other Node.js streams in important ways. See
<a href="#process_a_note_on_process_i_o">note on process I/O</a> for more information.</p>
<h3><code>process.stdout.fd</code><span><a class="mark" href="#process_process_stdout_fd" id="process_process_stdout_fd">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>This property refers to the value of underlying file descriptor of
<code>process.stdout</code>. The value is fixed at <code>1</code>. In <a href="#worker_threads_class_worker"><code>Worker</code></a> threads,
this field does not exist.</p>
<h3>A note on process I/O<span><a class="mark" href="#process_a_note_on_process_i_o" id="process_a_note_on_process_i_o">#</a></span></h3>
<p><code>process.stdout</code> and <code>process.stderr</code> differ from other Node.js streams in
important ways:</p>
<ol>
<li>They are used internally by <a href="#console_console_log_data_args"><code>console.log()</code></a> and <a href="#console_console_error_data_args"><code>console.error()</code></a>,
respectively.</li>
<li>
<p>Writes may be synchronous depending on what the stream is connected to
and whether the system is Windows or POSIX:</p>
<ul>
<li>Files: <em>synchronous</em> on Windows and POSIX</li>
<li>TTYs (Terminals): <em>asynchronous</em> on Windows, <em>synchronous</em> on POSIX</li>
<li>Pipes (and sockets): <em>synchronous</em> on Windows, <em>asynchronous</em> on POSIX</li>
</ul>
</li>
</ol>
<p>These behaviors are partly for historical reasons, as changing them would
create backwards incompatibility, but they are also expected by some users.</p>
<p>Synchronous writes avoid problems such as output written with <code>console.log()</code> or
<code>console.error()</code> being unexpectedly interleaved, or not written at all if
<code>process.exit()</code> is called before an asynchronous write completes. See
<a href="#process_process_exit_code"><code>process.exit()</code></a> for more information.</p>
<p><strong><em>Warning</em></strong>: Synchronous writes block the event loop until the write has
completed. This can be near instantaneous in the case of output to a file, but
under high system load, pipes that are not being read at the receiving end, or
with slow terminals or file systems, its possible for the event loop to be
blocked often enough and long enough to have severe negative performance
impacts. This may not be a problem when writing to an interactive terminal
session, but consider this particularly careful when doing production logging to
the process output streams.</p>
<p>To check if a stream is connected to a <a href="#tty_tty">TTY</a> context, check the <code>isTTY</code>
property.</p>
<p>For instance:</p>
<pre><code class="language-console">$ node -p "Boolean(process.stdin.isTTY)"
true
$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
false
$ node -p "Boolean(process.stdout.isTTY)"
true
$ node -p "Boolean(process.stdout.isTTY)" | cat
false
</code></pre>
<p>See the <a href="#tty_tty">TTY</a> documentation for more information.</p>
<h2><code>process.throwDeprecation</code><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">&#x3C;boolean></a></li>
</ul>
<p>The initial value of <code>process.throwDeprecation</code> indicates whether the
<code>--throw-deprecation</code> flag is set on the current Node.js process.
<code>process.throwDeprecation</code> is mutable, so whether or not deprecation
warnings result in errors may be altered at runtime. 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.</p>
<pre><code class="language-console">$ node --throw-deprecation -p "process.throwDeprecation"
true
$ node -p "process.throwDeprecation"
undefined
$ node
> process.emitWarning('test', 'DeprecationWarning');
undefined
> (node:26598) DeprecationWarning: test
> process.throwDeprecation = true;
true
> process.emitWarning('test', 'DeprecationWarning');
Thrown:
[DeprecationWarning: test] { name: 'DeprecationWarning' }
</code></pre>
<h2><code>process.title</code><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">&#x3C;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><code>process.traceDeprecation</code><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">&#x3C;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><code>process.umask([mask])</code><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#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>The <code>process.umask()</code> method sets or returns the Node.js process's file mode
creation mask. Child processes inherit the mask from the parent process. Invoked
without an argument, the current mask is returned, otherwise the umask is set to
the argument value and the previous mask is returned.</p>
<pre><code class="language-js">const newmask = 0o022;
const oldmask = process.umask(newmask);
console.log(
  `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`
);
</code></pre>
<p><a href="#worker_threads_class_worker"><code>Worker</code></a> threads are able to read the umask, however attempting to set the
umask will result in a thrown exception.</p>
<h2><code>process.uptime()</code><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">&#x3C;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><code>process.version</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>process.version</code> property returns the Node.js version string.</p>
<pre><code class="language-js">console.log(`Version: ${process.version}`);
</code></pre>
<h2><code>process.versions</code><span><a class="mark" href="#process_process_versions" id="process_process_versions">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>v8</code> property now includes a Node.js specific suffix.</p></td></tr>
<tr><td>v4.2.0</td>
<td><p>The <code>icu</code> property is now supported.</p></td></tr>
<tr><td>v0.2.0</td>
<td><p><span>Added in: v0.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>The <code>process.versions</code> property returns an object listing the version strings of
Node.js and its dependencies. <code>process.versions.modules</code> indicates the current
ABI version, which is increased whenever a C++ API changes. Node.js will refuse
to load modules that were compiled against a different module ABI version.</p>
<pre><code class="language-js">console.log(process.versions);
</code></pre>
<p>Will generate an object similar to:</p>
<pre><code class="language-console">{ node: '11.13.0',
  v8: '7.0.276.38-node.18',
  uv: '1.27.0',
  zlib: '1.2.11',
  brotli: '1.0.7',
  ares: '1.15.0',
  modules: '67',
  nghttp2: '1.34.0',
  napi: '4',
  llhttp: '1.1.1',
  http_parser: '2.8.0',
  openssl: '1.1.1b',
  cldr: '34.0',
  icu: '63.1',
  tz: '2018e',
  unicode: '11.0' }
</code></pre>
<h2>Exit codes<span><a class="mark" href="#process_exit_codes" id="process_exit_codes">#</a></span></h2>
<p>Node.js will normally exit with a <code>0</code> status code when no more async
operations are pending. The following status codes are used in other
cases:</p>
<ul>
<li><code>1</code> <strong>Uncaught Fatal Exception</strong>: There was an uncaught exception,
and it was not handled by a domain or an <a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a> event
handler.</li>
<li><code>2</code>: Unused (reserved by Bash for builtin misuse)</li>
<li><code>3</code> <strong>Internal JavaScript Parse Error</strong>: The JavaScript source code
internal in the Node.js 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 the Node.js bootstrapping process failed to
return a function value when evaluated. This is extremely rare, and
generally can only happen during development of Node.js itself.</li>
<li><code>5</code> <strong>Fatal Error</strong>: There was a fatal unrecoverable error in V8.
Typically a message will be printed to stderr with the prefix <code>FATAL ERROR</code>.</li>
<li><code>6</code> <strong>Non-function Internal Exception Handler</strong>: There was an
uncaught exception, but the internal fatal exception handler
function was somehow set to a non-function, and could not be called.</li>
<li><code>7</code> <strong>Internal Exception Handler Run-Time Failure</strong>: There was an
uncaught exception, and the internal fatal exception handler
function itself threw an error while attempting to handle it. This
can happen, for example, if an <a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a> or
<code>domain.on('error')</code> handler throws an error.</li>
<li><code>8</code>: Unused. In previous versions of Node.js, exit code 8 sometimes
indicated an uncaught exception.</li>
<li><code>9</code> <strong>Invalid Argument</strong>: Either an unknown option was specified,
or an option requiring a value was provided without a value.</li>
<li><code>10</code> <strong>Internal JavaScript Run-Time Failure</strong>: The JavaScript
source code internal in the Node.js bootstrapping process threw an error
when the bootstrapping function was called. This is extremely rare,
and generally can only happen during development of Node.js itself.</li>
<li><code>12</code> <strong>Invalid Debug Argument</strong>: The <code>--inspect</code> and/or <code>--inspect-brk</code>
options were set, but the port number chosen was invalid or unavailable.</li>
<li><code>>128</code> <strong>Signal Exits</strong>: If Node.js receives a fatal signal such as
<code>SIGKILL</code> or <code>SIGHUP</code>, then its exit code will be <code>128</code> plus the
value of the signal code. This is a standard POSIX practice, since
exit codes are defined to be 7-bit integers, and signal exits set
the high-order bit, and then contain the value of the signal code.
For example, signal <code>SIGABRT</code> has value <code>6</code>, so the expected exit
code will be <code>128</code> + <code>6</code>, or <code>134</code>.</li>
</ul>
<h1>Punycode<span><a class="mark" href="#punycode_punycode" id="punycode_punycode">#</a></span></h1>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.0.0</td>
<td><p>Accessing this module will now emit a deprecation warning.</p></td></tr>
</tbody></table>
</details>
</div>

<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p>
<p><strong>The version of the punycode module bundled in Node.js is being deprecated</strong>.
In a future major version of Node.js this module will be removed. Users
currently depending on the <code>punycode</code> module should switch to using the
userland-provided <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> module instead.</p>
<p>The <code>punycode</code> module is a bundled version of the <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> module. It
can be accessed using:</p>
<pre><code class="language-js">const punycode = require('punycode');
</code></pre>
<p><a href="https://tools.ietf.org/html/rfc3492">Punycode</a> is a character encoding scheme defined by RFC 3492 that is
primarily intended for use in Internationalized Domain Names. Because host
names in URLs are limited to ASCII characters only, Domain Names that contain
non-ASCII characters must be converted into ASCII using the Punycode scheme.
For instance, the Japanese character that translates into the English word,
<code>'example'</code> is <code>'例'</code>. The Internationalized Domain Name, <code>'例.com'</code> (equivalent
to <code>'example.com'</code>) is represented by Punycode as the ASCII string
<code>'xn--fsq.com'</code>.</p>
<p>The <code>punycode</code> module provides a simple implementation of the Punycode standard.</p>
<p>The <code>punycode</code> module is a third-party dependency used by Node.js and
made available to developers as a convenience. Fixes or other modifications to
the module must be directed to the <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> project.</p>
<h2><code>punycode.decode(string)</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>punycode.decode()</code> method converts a <a href="https://tools.ietf.org/html/rfc3492">Punycode</a> string of ASCII-only
characters to the equivalent string of Unicode codepoints.</p>
<pre><code class="language-js">punycode.decode('maana-pta'); // 'mañana'
punycode.decode('--dqo34k'); // '☃-⌘'
</code></pre>
<h2><code>punycode.encode(string)</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>punycode.encode()</code> method converts a string of Unicode codepoints to a
<a href="https://tools.ietf.org/html/rfc3492">Punycode</a> string of ASCII-only characters.</p>
<pre><code class="language-js">punycode.encode('mañana'); // 'maana-pta'
punycode.encode('☃-⌘'); // '--dqo34k'
</code></pre>
<h2><code>punycode.toASCII(domain)</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>punycode.toASCII()</code> method converts a Unicode string representing an
Internationalized Domain Name to <a href="https://tools.ietf.org/html/rfc3492">Punycode</a>. Only the non-ASCII parts of the
domain name will be converted. Calling <code>punycode.toASCII()</code> on a string that
already only contains ASCII characters will have no effect.</p>
<pre><code class="language-js">// encode domain names
punycode.toASCII('mañana.com');  // 'xn--maana-pta.com'
punycode.toASCII('☃-⌘.com');   // 'xn----dqo34k.com'
punycode.toASCII('example.com'); // 'example.com'
</code></pre>
<h2><code>punycode.toUnicode(domain)</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>punycode.toUnicode()</code> method converts a string representing a domain name
containing <a href="https://tools.ietf.org/html/rfc3492">Punycode</a> encoded characters into Unicode. Only the <a href="https://tools.ietf.org/html/rfc3492">Punycode</a>
encoded parts of the domain name are be converted.</p>
<pre><code class="language-js">// decode domain names
punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
punycode.toUnicode('xn----dqo34k.com');  // '☃-⌘.com'
punycode.toUnicode('example.com');       // 'example.com'
</code></pre>
<h2><code>punycode.ucs2</code><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><code>punycode.ucs2.decode(string)</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>punycode.ucs2.decode()</code> method returns an array containing the numeric
codepoint values of each Unicode symbol in the string.</p>
<pre><code class="language-js">punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63]
// surrogate pair for U+1D306 tetragram for centre:
punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]
</code></pre>
<h3><code>punycode.ucs2.encode(codePoints)</code><span><a class="mark" href="#punycode_punycode_ucs2_encode_codepoints" id="punycode_punycode_ucs2_encode_codepoints">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>codePoints</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer[]></a></li>
</ul>
<p>The <code>punycode.ucs2.encode()</code> method returns a string based on an array of
numeric code point values.</p>
<pre><code class="language-js">punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc'
punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'
</code></pre>
<h2><code>punycode.version</code><span><a class="mark" href="#punycode_punycode_version" id="punycode_punycode_version">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.1</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns a string identifying the current <a href="https://github.com/bestiejs/punycode.js">Punycode.js</a> version number.</p>
<h1>Query string<span><a class="mark" href="#querystring_query_string" id="querystring_query_string">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>

<p>The <code>querystring</code> module provides utilities for parsing and formatting URL
query strings. It can be accessed using:</p>
<pre><code class="language-js">const querystring = require('querystring');
</code></pre>
<h2><code>querystring.decode()</code><span><a class="mark" href="#querystring_querystring_decode" id="querystring_querystring_decode">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<p>The <code>querystring.decode()</code> function is an alias for <code>querystring.parse()</code>.</p>
<h2><code>querystring.encode()</code><span><a class="mark" href="#querystring_querystring_encode" id="querystring_querystring_encode">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<p>The <code>querystring.encode()</code> function is an alias for <code>querystring.stringify()</code>.</p>
<h2><code>querystring.escape(str)</code><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">&#x3C;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><code>querystring.parse(str[, sep[, eq[, options]]])</code><span><a class="mark" href="#querystring_querystring_parse_str_sep_eq_options" id="querystring_querystring_parse_str_sep_eq_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Multiple empty entries are now parsed correctly (e.g. <code>&#x26;=&#x26;=</code>).</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The returned object no longer inherits from <code>Object.prototype</code>.</p></td></tr>
<tr><td>v6.0.0, v4.2.4</td>
<td><p>The <code>eq</code> parameter may now have a length of more than <code>1</code>.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>str</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> The substring used to delimit key and value pairs in the
query string. <strong>Default:</strong> <code>'&#x26;'</code>.</li>
<li><code>eq</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>. The substring used to delimit keys and values in the
query string. <strong>Default:</strong> <code>'='</code>.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>decodeURIComponent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to use when decoding
percent-encoded characters in the query string. <strong>Default:</strong>
<code>querystring.unescape()</code>.</li>
<li><code>maxKeys</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the maximum number of keys to parse.
Specify <code>0</code> to remove key counting limitations. <strong>Default:</strong> <code>1000</code>.</li>
</ul>
</li>
</ul>
<p>The <code>querystring.parse()</code> method parses a URL query string (<code>str</code>) into a
collection of key and value pairs.</p>
<p>For example, the query string <code>'foo=bar&#x26;abc=xyz&#x26;abc=123'</code> is parsed into:</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  foo: 'bar',
  abc: ['xyz', '123']
}
</code></pre>
<p>The object returned by the <code>querystring.parse()</code> method <em>does not</em>
prototypically inherit from the JavaScript <code>Object</code>. This means that typical
<code>Object</code> methods such as <code>obj.toString()</code>, <code>obj.hasOwnProperty()</code>, and others
are not defined and <em>will not work</em>.</p>
<p>By default, percent-encoded characters within the query string will be assumed
to use UTF-8 encoding. If an alternative character encoding is used, then an
alternative <code>decodeURIComponent</code> option will need to be specified:</p>
<pre><code class="language-js">// Assuming gbkDecodeURIComponent function already exists...

querystring.parse('w=%D6%D0%CE%C4&#x26;foo=bar', null, null,
                  { decodeURIComponent: gbkDecodeURIComponent });
</code></pre>
<h2><code>querystring.stringify(obj[, sep[, eq[, options]]])</code><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">&#x3C;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">&#x3C;string></a> The substring used to delimit key and value pairs in the
query string. <strong>Default:</strong> <code>'&#x26;'</code>.</li>
<li><code>eq</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>. The substring used to delimit keys and values in the
query string. <strong>Default:</strong> <code>'='</code>.</li>
<li>
<p><code>options</code></p>
<ul>
<li><code>encodeURIComponent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to use when converting
URL-unsafe characters to percent-encoding in the query string. <strong>Default:</strong>
<code>querystring.escape()</code>.</li>
</ul>
</li>
</ul>
<p>The <code>querystring.stringify()</code> method produces a URL query string from a
given <code>obj</code> by iterating through the object's "own properties".</p>
<p>It serializes the following types of values passed in <code>obj</code>:
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean[]></a>
Any other input values will be coerced to empty strings.</p>
<pre><code class="language-js">querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// Returns 'foo=bar&#x26;baz=qux&#x26;baz=quux&#x26;corge='

querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
// Returns 'foo:bar;baz:qux'
</code></pre>
<p>By default, characters requiring percent-encoding within the query string will
be encoded as UTF-8. If an alternative encoding is required, then an alternative
<code>encodeURIComponent</code> option will need to be specified:</p>
<pre><code class="language-js">// Assuming gbkEncodeURIComponent function already exists,

querystring.stringify({ w: '中文', foo: 'bar' }, null, null,
                      { encodeURIComponent: gbkEncodeURIComponent });
</code></pre>
<h2><code>querystring.unescape(str)</code><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">&#x3C;string></a></li>
</ul>
<p>The <code>querystring.unescape()</code> method performs decoding of URL percent-encoded
characters on the given <code>str</code>.</p>
<p>The <code>querystring.unescape()</code> method is used by <code>querystring.parse()</code> and is
generally not expected to be used directly. It is exported primarily to allow
application code to provide a replacement decoding implementation if
necessary by assigning <code>querystring.unescape</code> to an alternative function.</p>
<p>By default, the <code>querystring.unescape()</code> method will attempt to use the
JavaScript built-in <code>decodeURIComponent()</code> method to decode. If that fails,
a safer equivalent that does not throw on malformed URLs will be used.</p>
<h1>Readline<span><a class="mark" href="#readline_readline" id="readline_readline">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>readline</code> module provides an interface for reading data from a <a href="#stream_readable_streams">Readable</a>
stream (such as <a href="#process_process_stdin"><code>process.stdin</code></a>) one line at a time. It can be accessed
using:</p>
<pre><code class="language-js">const readline = require('readline');
</code></pre>
<p>The following simple example illustrates the basic use of the <code>readline</code> module.</p>
<pre><code class="language-js">const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  console.log(`Thank you for your valuable feedback: ${answer}`);

  rl.close();
});
</code></pre>
<p>Once this code is invoked, the Node.js application will not terminate until the
<code>readline.Interface</code> is closed because the interface waits for data to be
received on the <code>input</code> stream.</p>
<h2>Class: <code>Interface</code><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>
<ul>
<li>Extends: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Instances of the <code>readline.Interface</code> class are constructed using the
<code>readline.createInterface()</code> method. Every instance is associated with a
single <code>input</code> <a href="#stream_readable_streams">Readable</a> stream and a single <code>output</code> <a href="#stream_writable_streams">Writable</a> stream.
The <code>output</code> stream is used to print prompts for user input that arrives on,
and is read from, the <code>input</code> stream.</p>
<h3>Event: <code>'close'</code><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>&#x3C;ctrl>-D</code> to signal end-of-transmission (EOT);</li>
<li>The <code>input</code> stream receives <code>&#x3C;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: <code>'line'</code><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>&#x3C;Enter></code>, or <code>&#x3C;Return></code> keys.</p>
<p>The listener function is called with a string containing the single line of
received input.</p>
<pre><code class="language-js">rl.on('line', (input) => {
  console.log(`Received: ${input}`);
});
</code></pre>
<h3>Event: <code>'pause'</code><span><a class="mark" href="#readline_event_pause" id="readline_event_pause">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div>
<p>The <code>'pause'</code> event is emitted when one of the following occur:</p>
<ul>
<li>The <code>input</code> stream is paused.</li>
<li>The <code>input</code> stream is not paused and receives the <code>'SIGCONT'</code> event. (See
events <a href="#readline_event_sigtstp"><code>'SIGTSTP'</code></a> and <a href="#readline_event_sigcont"><code>'SIGCONT'</code></a>.)</li>
</ul>
<p>The listener function is called without passing any arguments.</p>
<pre><code class="language-js">rl.on('pause', () => {
  console.log('Readline paused.');
});
</code></pre>
<h3>Event: <code>'resume'</code><span><a class="mark" href="#readline_event_resume" id="readline_event_resume">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div>
<p>The <code>'resume'</code> event is emitted whenever the <code>input</code> stream is resumed.</p>
<p>The listener function is called without passing any arguments.</p>
<pre><code class="language-js">rl.on('resume', () => {
  console.log('Readline resumed.');
});
</code></pre>
<h3>Event: <code>'SIGCONT'</code><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>&#x3C;ctrl>-Z</code> (i.e. <code>SIGTSTP</code>) is then brought back to the
foreground using <a href="http://man7.org/linux/man-pages/man1/fg.1p.html"><code>fg(1p)</code></a>.</p>
<p>If the <code>input</code> stream was paused <em>before</em> the <code>SIGTSTP</code> request, this event will
not be emitted.</p>
<p>The listener function is invoked without passing any arguments.</p>
<pre><code class="language-js">rl.on('SIGCONT', () => {
  // `prompt` will automatically resume the stream
  rl.prompt();
});
</code></pre>
<p>The <code>'SIGCONT'</code> event is <em>not</em> supported on Windows.</p>
<h3>Event: <code>'SIGINT'</code><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>&#x3C;ctrl>-C</code> input, known typically as <code>SIGINT</code>. If there are no <code>'SIGINT'</code> event
listeners registered when the <code>input</code> stream receives a <code>SIGINT</code>, the <code>'pause'</code>
event will be emitted.</p>
<p>The listener function is invoked without passing any arguments.</p>
<pre><code class="language-js">rl.on('SIGINT', () => {
  rl.question('Are you sure you want to exit? ', (answer) => {
    if (answer.match(/^y(es)?$/i)) rl.pause();
  });
});
</code></pre>
<h3>Event: <code>'SIGTSTP'</code><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>&#x3C;ctrl>-Z</code>
input, typically known as <code>SIGTSTP</code>. If there are no <code>'SIGTSTP'</code> event listeners
registered when the <code>input</code> stream receives a <code>SIGTSTP</code>, the Node.js process
will be sent to the background.</p>
<p>When the program is resumed using <a href="http://man7.org/linux/man-pages/man1/fg.1p.html"><code>fg(1p)</code></a>, the <code>'pause'</code> and <code>'SIGCONT'</code> events
will be emitted. These can be used to resume the <code>input</code> stream.</p>
<p>The <code>'pause'</code> and <code>'SIGCONT'</code> events will not be emitted if the <code>input</code> was
paused before the process was sent to the background.</p>
<p>The listener function is invoked without passing any arguments.</p>
<pre><code class="language-js">rl.on('SIGTSTP', () => {
  // This will override SIGTSTP and prevent the program from going to the
  // background.
  console.log('Caught SIGTSTP.');
});
</code></pre>
<p>The <code>'SIGTSTP'</code> event is <em>not</em> supported on Windows.</p>
<h3><code>rl.close()</code><span><a class="mark" href="#readline_rl_close" id="readline_rl_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div>
<p>The <code>rl.close()</code> method closes the <code>readline.Interface</code> instance and
relinquishes control over the <code>input</code> and <code>output</code> streams. When called,
the <code>'close'</code> event will be emitted.</p>
<p>Calling <code>rl.close()</code> does not immediately stop other events (including <code>'line'</code>)
from being emitted by the <code>readline.Interface</code> instance.</p>
<h3><code>rl.pause()</code><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><code>rl.prompt([preserveCursor])</code><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">&#x3C;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><code>rl.question(query, callback)</code><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">&#x3C;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">&#x3C;Function></a> A callback function that is invoked with the user's
input in response to the <code>query</code>.</li>
</ul>
<p>The <code>rl.question()</code> method displays the <code>query</code> by writing it to the <code>output</code>,
waits for user input to be provided on <code>input</code>, then invokes the <code>callback</code>
function passing the provided input as the first argument.</p>
<p>When called, <code>rl.question()</code> will resume the <code>input</code> stream if it has been
paused.</p>
<p>If the <code>readline.Interface</code> was created with <code>output</code> set to <code>null</code> or
<code>undefined</code> the <code>query</code> is not written.</p>
<p>Example usage:</p>
<pre><code class="language-js">rl.question('What is your favorite food? ', (answer) => {
  console.log(`Oh, so your favorite food is ${answer}`);
});
</code></pre>
<p>The <code>callback</code> function passed to <code>rl.question()</code> does not follow the typical
pattern of accepting an <code>Error</code> object or <code>null</code> as the first argument.
The <code>callback</code> is called with the provided answer as the only argument.</p>
<h3><code>rl.resume()</code><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><code>rl.setPrompt(prompt)</code><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">&#x3C;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><code>rl.write(data[, key])</code><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">&#x3C;string></a></li>
<li>
<p><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>ctrl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> to indicate the <code>&#x3C;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">&#x3C;boolean></a> <code>true</code> to indicate the <code>&#x3C;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">&#x3C;boolean></a> <code>true</code> to indicate the <code>&#x3C;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">&#x3C;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. See <a href="#readline_tty_keybindings">TTY keybindings</a> for a list of key
combinations.</p>
<p>If <code>key</code> is specified, <code>data</code> is ignored.</p>
<p>When called, <code>rl.write()</code> will resume the <code>input</code> stream if it has been
paused.</p>
<p>If the <code>readline.Interface</code> was created with <code>output</code> set to <code>null</code> or
<code>undefined</code> the <code>data</code> and <code>key</code> are not written.</p>
<pre><code class="language-js">rl.write('Delete this!');
// Simulate Ctrl+u to delete the line written previously
rl.write(null, { ctrl: true, name: 'u' });
</code></pre>
<p>The <code>rl.write()</code> method will write the data to the <code>readline</code> <code>Interface</code>'s
<code>input</code> <em>as if it were provided by the user</em>.</p>
<h3><code>rl[Symbol.asyncIterator]()</code><span><a class="mark" href="#readline_rl_symbol_asynciterator" id="readline_rl_symbol_asynciterator">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.14.0</td>
<td><p>Symbol.asyncIterator support is no longer experimental.</p></td></tr>
<tr><td>v11.4.0</td>
<td><p><span>Added in: v11.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type">&#x3C;AsyncIterator></a></li>
</ul>
<p>Create an <code>AsyncIterator</code> object that iterates through each line in the input
stream as a string. This method allows asynchronous iteration of
<code>readline.Interface</code> objects through <code>for await...of</code> loops.</p>
<p>Errors in the input stream are not forwarded.</p>
<p>If the loop is terminated with <code>break</code>, <code>throw</code>, or <code>return</code>,
<a href="#readline_rl_close"><code>rl.close()</code></a> will be called. In other words, iterating over a
<code>readline.Interface</code> will always consume the input stream fully.</p>
<p>Performance is not on par with the traditional <code>'line'</code> event API. Use <code>'line'</code>
instead for performance-sensitive applications.</p>
<pre><code class="language-js">async function processLineByLine() {
  const rl = readline.createInterface({
    // ...
  });

  for await (const line of rl) {
    // Each line in the readline input will be successively available here as
    // `line`.
  }
}
</code></pre>
<h3>rl.line<span><a class="mark" href="#readline_rl_line" id="readline_rl_line">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>The current input data being processed by node.</p>
<p>This can be used when collecting input from a TTY stream to retrieve the
current value that has been processed thus far, prior to the <code>line</code> event
being emitted. Once the <code>line</code> event has been emitted, this property will
be an empty string.</p>
<p>Be aware that modifying the value during the instance runtime may have
unintended consequences if <code>rl.cursor</code> is not also controlled.</p>
<p><strong>If not using a TTY stream for input, use the <a href="#readline_event_line"><code>'line'</code></a> event.</strong></p>
<p>One possible use case would be as follows:</p>
<pre><code class="language-js">const values = ['lorem ipsum', 'dolor sit amet'];
const rl = readline.createInterface(process.stdin);
const showResults = debounce(() => {
  console.log(
    '\n',
    values.filter((val) => val.startsWith(rl.line)).join(' ')
  );
}, 300);
process.stdin.on('keypress', (c, k) => {
  showResults();
});
</code></pre>
<h3>rl.cursor<span><a class="mark" href="#readline_rl_cursor" id="readline_rl_cursor">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>The cursor position relative to <code>rl.line</code>.</p>
<p>This will track where the current cursor lands in the input string, when
reading input from a TTY stream. The position of cursor determines the
portion of the input string that will be modified as input is processed,
as well as the column where the terminal caret will be rendered.</p>
<h3><code>rl.getCursorPos()</code><span><a class="mark" href="#readline_rl_getcursorpos" id="readline_rl_getcursorpos">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>rows</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the row of the prompt the cursor currently lands on</li>
<li><code>cols</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the screen column the cursor currently lands on</li>
</ul>
</li>
</ul>
<p>Returns the real position of the cursor in relation to the input
prompt + string. Long input (wrapping) strings, as well as multiple
line prompts are included in the calculations.</p>
<h2><code>readline.clearLine(stream, dir[, callback])</code><span><a class="mark" href="#readline_readline_clearline_stream_dir_callback" id="readline_readline_clearline_stream_dir_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>stream</code> <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a></li>
<li>
<p><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></p>
<ul>
<li><code>-1</code>: to the left from cursor</li>
<li><code>1</code>: to the right from cursor</li>
<li><code>0</code>: the entire line</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked once the operation completes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>false</code> if <code>stream</code> 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>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><code>readline.clearScreenDown(stream[, callback])</code><span><a class="mark" href="#readline_readline_clearscreendown_stream_callback" id="readline_readline_clearscreendown_stream_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>stream</code> <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked once the operation completes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>false</code> if <code>stream</code> 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>readline.clearScreenDown()</code> method clears the given <a href="tty.html">TTY</a> stream from
the current position of the cursor down.</p>
<h2><code>readline.createInterface(options)</code><span><a class="mark" href="#readline_readline_createinterface_options" id="readline_readline_createinterface_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.3.0, 6.11.4</td>
<td><p>Remove max limit of <code>crlfDelay</code> option.</p></td></tr>
<tr><td>v6.6.0</td>
<td><p>The <code>crlfDelay</code> option is supported now.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>prompt</code> option is supported now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>historySize</code> option can be <code>0</code> now.</p></td></tr>
<tr><td>v0.1.98</td>
<td><p><span>Added in: v0.1.98</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>input</code> <a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a> The <a href="#stream_readable_streams">Readable</a> stream to listen to. This option
is <em>required</em>.</li>
<li><code>output</code> <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a> The <a href="#stream_writable_streams">Writable</a> stream to write readline data
to.</li>
<li><code>completer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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">&#x3C;boolean></a> <code>true</code> if the <code>input</code> and <code>output</code> streams should be
treated like a TTY, and have ANSI/VT100 escape codes written to it.
<strong>Default:</strong> checking <code>isTTY</code> on the <code>output</code> stream upon instantiation.</li>
<li><code>historySize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;boolean></a> If <code>true</code>, when a new input line added
to the history list duplicates an older one, this removes the older line
from the list. <strong>Default:</strong> <code>false</code>.</li>
<li><code>escapeCodeTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The duration <code>readline</code> will wait for a
character (when reading an ambiguous key sequence in milliseconds one that
can both form a complete key sequence using the input read so far and can
take additional input to complete a longer key sequence).
<strong>Default:</strong> <code>500</code>.</li>
</ul>
</li>
</ul>
<p>The <code>readline.createInterface()</code> method creates a new <code>readline.Interface</code>
instance.</p>
<pre><code class="language-js">const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
</code></pre>
<p>Once the <code>readline.Interface</code> instance is created, the most common case is to
listen for the <code>'line'</code> event:</p>
<pre><code class="language-js">rl.on('line', (line) => {
  console.log(`Received: ${line}`);
});
</code></pre>
<p>If <code>terminal</code> is <code>true</code> for this instance then the <code>output</code> stream will get
the best compatibility if it defines an <code>output.columns</code> property and emits
a <code>'resize'</code> event on the <code>output</code> if or when the columns ever change
(<a href="#process_process_stdout"><code>process.stdout</code></a> does this automatically when it is a TTY).</p>
<h3>Use of the <code>completer</code> function<span><a class="mark" href="#readline_use_of_the_completer_function" id="readline_use_of_the_completer_function">#</a></span></h3>
<p>The <code>completer</code> function takes the current line entered by the user
as an argument, and returns an <code>Array</code> with 2 entries:</p>
<ul>
<li>An <code>Array</code> with matching entries for the completion.</li>
<li>The substring that was used for the matching.</li>
</ul>
<p>For instance: <code>[[substr1, substr2, ...], originalsubstring]</code>.</p>
<pre><code class="language-js">function completer(line) {
  const completions = '.help .error .exit .quit .q'.split(' ');
  const hits = completions.filter((c) => c.startsWith(line));
  // Show all completions if none found
  return [hits.length ? hits : completions, line];
}
</code></pre>
<p>The <code>completer</code> function can be called asynchronously if it accepts two
arguments:</p>
<pre><code class="language-js">function completer(linePartial, callback) {
  callback(null, [['123'], linePartial]);
}
</code></pre>
<h2><code>readline.cursorTo(stream, x[, y][, callback])</code><span><a class="mark" href="#readline_readline_cursorto_stream_x_y_callback" id="readline_readline_cursorto_stream_x_y_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>stream</code> <a href="#stream_class_stream_writable" class="type">&#x3C;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">&#x3C;number></a></li>
<li><code>y</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked once the operation completes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>false</code> if <code>stream</code> 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>readline.cursorTo()</code> method moves cursor to the specified position in a
given <a href="tty.html">TTY</a> <code>stream</code>.</p>
<h2><code>readline.emitKeypressEvents(stream[, interface])</code><span><a class="mark" href="#readline_readline_emitkeypressevents_stream_interface" id="readline_readline_emitkeypressevents_stream_interface">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<ul>
<li><code>stream</code> <a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a></li>
<li><code>interface</code> <a href="#readline_class_interface" class="type">&#x3C;readline.Interface></a></li>
</ul>
<p>The <code>readline.emitKeypressEvents()</code> method causes the given <a href="#stream_readable_streams">Readable</a>
stream to begin emitting <code>'keypress'</code> events corresponding to received input.</p>
<p>Optionally, <code>interface</code> specifies a <code>readline.Interface</code> instance for which
autocompletion is disabled when copy-pasted input is detected.</p>
<p>If the <code>stream</code> is a <a href="tty.html">TTY</a>, then it must be in raw mode.</p>
<p>This is automatically called by any readline instance on its <code>input</code> if the
<code>input</code> is a terminal. Closing the <code>readline</code> instance does not stop
the <code>input</code> from emitting <code>'keypress'</code> events.</p>
<pre><code class="language-js">readline.emitKeypressEvents(process.stdin);
if (process.stdin.isTTY)
  process.stdin.setRawMode(true);
</code></pre>
<h2><code>readline.moveCursor(stream, dx, dy[, callback])</code><span><a class="mark" href="#readline_readline_movecursor_stream_dx_dy_callback" id="readline_readline_movecursor_stream_dx_dy_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>stream</code> <a href="#stream_class_stream_writable" class="type">&#x3C;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">&#x3C;number></a></li>
<li><code>dy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked once the operation completes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>false</code> if <code>stream</code> 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>readline.moveCursor()</code> method moves the cursor <em>relative</em> to its current
position in a given <a href="tty.html">TTY</a> <code>stream</code>.</p>
<h2>Example: Tiny CLI<span><a class="mark" href="#readline_example_tiny_cli" id="readline_example_tiny_cli">#</a></span></h2>
<p>The following example illustrates the use of <code>readline.Interface</code> class to
implement a small command-line interface:</p>
<pre><code class="language-js">const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'OHAI> '
});

rl.prompt();

rl.on('line', (line) => {
  switch (line.trim()) {
    case 'hello':
      console.log('world!');
      break;
    default:
      console.log(`Say what? I might have heard '${line.trim()}'`);
      break;
  }
  rl.prompt();
}).on('close', () => {
  console.log('Have a great day!');
  process.exit(0);
});
</code></pre>
<h2>Example: Read file stream line-by-Line<span><a class="mark" href="#readline_example_read_file_stream_line_by_line" id="readline_example_read_file_stream_line_by_line">#</a></span></h2>
<p>A common use case for <code>readline</code> is to consume an input file one line at a
time. The easiest way to do so is leveraging the <a href="#fs_class_fs_readstream"><code>fs.ReadStream</code></a> API as
well as a <code>for await...of</code> loop:</p>
<pre><code class="language-js">const fs = require('fs');
const readline = require('readline');

async function processLineByLine() {
  const fileStream = fs.createReadStream('input.txt');

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });
  // Note: we use the crlfDelay option to recognize all instances of CR LF
  // ('\r\n') in input.txt as a single line break.

  for await (const line of rl) {
    // Each line in input.txt will be successively available here as `line`.
    console.log(`Line from file: ${line}`);
  }
}

processLineByLine();
</code></pre>
<p>Alternatively, one could use the <a href="#readline_event_line"><code>'line'</code></a> event:</p>
<pre><code class="language-js">const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
  input: fs.createReadStream('sample.txt'),
  crlfDelay: Infinity
});

rl.on('line', (line) => {
  console.log(`Line from file: ${line}`);
});
</code></pre>
<p>Currently, <code>for await...of</code> loop can be a bit slower. If <code>async</code> / <code>await</code>
flow and speed are both essential, a mixed approach can be applied:</p>
<pre><code class="language-js">const { once } = require('events');
const { createReadStream } = require('fs');
const { createInterface } = require('readline');

(async function processLineByLine() {
  try {
    const rl = createInterface({
      input: createReadStream('big-file.txt'),
      crlfDelay: Infinity
    });

    rl.on('line', (line) => {
      // Process the line.
    });

    await once(rl, 'close');

    console.log('File processed.');
  } catch (err) {
    console.error(err);
  }
})();
</code></pre>
<h2>TTY keybindings<span><a class="mark" href="#readline_tty_keybindings" id="readline_tty_keybindings">#</a></span></h2>
<table>
  <tbody><tr>
    <th>Keybindings</th>
    <th>Description</th>
    <th>Notes</th>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>shift</code> + <code>backspace</code></td>
    <td>Delete line left</td>
    <td>Doesn't work on Linux, Mac and Windows</td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>shift</code> + <code>delete</code></td>
    <td>Delete line right</td>
    <td>Doesn't work on Mac</td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>c</code></td>
    <td>Emit <code>SIGINT</code> or close the readline instance</td>
    <td></td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>h</code></td>
    <td>Delete left</td>
    <td></td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>d</code></td>
    <td>Delete right or close the readline instance in case the current line is empty / EOF</td>
    <td>Doesn't work on Windows</td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>u</code></td>
    <td>Delete from the current position to the line start</td>
    <td></td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>k</code></td>
    <td>Delete from the current position to the end of line</td>
    <td></td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>a</code></td>
    <td>Go to start of line</td>
    <td></td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>e</code></td>
    <td>Go to to end of line</td>
    <td></td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>b</code></td>
    <td>Back one character</td>
    <td></td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>f</code></td>
    <td>Forward one character</td>
    <td></td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>l</code></td>
    <td>Clear screen</td>
    <td></td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>n</code></td>
    <td>Next history item</td>
    <td></td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>p</code></td>
    <td>Previous history item</td>
    <td></td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>z</code></td>
    <td>Moves running process into background. Type
    <code>fg</code> and press <code>enter</code>
    to return.</td>
    <td>Doesn't work on Windows</td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>w</code> or <code>ctrl</code>
    + <code>backspace</code></td>
    <td>Delete backwards to a word boundary</td>
    <td><code>ctrl</code> + <code>backspace</code> Doesn't
    work on Linux, Mac and Windows</td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>delete</code></td>
    <td>Delete forward to a word boundary</td>
    <td>Doesn't work on Mac</td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>left</code> or
    <code>meta</code> + <code>b</code></td>
    <td>Word left</td>
    <td><code>ctrl</code> + <code>left</code> Doesn't work
    on Mac</td>
  </tr>
  <tr>
    <td><code>ctrl</code> + <code>right</code> or
    <code>meta</code> + <code>f</code></td>
    <td>Word right</td>
    <td><code>ctrl</code> + <code>right</code> Doesn't work
    on Mac</td>
  </tr>
  <tr>
    <td><code>meta</code> + <code>d</code> or <code>meta</code>
    + <code>delete</code></td>
    <td>Delete word right</td>
    <td><code>meta</code> + <code>delete</code> Doesn't work
    on windows</td>
  </tr>
  <tr>
    <td><code>meta</code> + <code>backspace</code></td>
    <td>Delete word left</td>
    <td>Doesn't work on Mac</td>
  </tr>
</tbody></table>
<h1>REPL<span><a class="mark" href="#repl_repl" id="repl_repl">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>repl</code> module provides a Read-Eval-Print-Loop (REPL) implementation that
is available both as a standalone program or includible in other applications.
It can be accessed using:</p>
<pre><code class="language-js">const repl = require('repl');
</code></pre>
<h2>Design and features<span><a class="mark" href="#repl_design_and_features" id="repl_design_and_features">#</a></span></h2>
<p>The <code>repl</code> module exports the <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> class. While running,
instances of <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> will accept individual lines of user input,
evaluate those according to a user-defined evaluation function, then output the
result. Input and output may be from <code>stdin</code> and <code>stdout</code>, respectively, or may
be connected to any Node.js <a href="stream.html">stream</a>.</p>
<p>Instances of <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> support automatic completion of inputs,
completion preview, simplistic Emacs-style line editing, multi-line inputs,
<a href="https://en.wikipedia.org/wiki/Z_shell">ZSH</a>-like reverse-i-search, <a href="https://en.wikipedia.org/wiki/Z_shell">ZSH</a>-like substring-based history search,
ANSI-styled output, saving and restoring current REPL session state, error
recovery, and customizable evaluation functions. Terminals that do not support
ANSI styles and Emacs-style line editing automatically fall back to a limited
feature set.</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>&#x3C;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 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>&#x3C;ctrl>-D</code> to finish, <code>&#x3C;ctrl>-C</code> to cancel).</li>
</ul>
<pre><code class="language-console">> .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>&#x3C;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>&#x3C;ctrl>-D</code>: Has the same effect as the <code>.exit</code> command.</li>
<li><code>&#x3C;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>
<p>For key bindings related to the reverse-i-search, see <a href="#repl_reverse_i_search"><code>reverse-i-search</code></a>.
For all other key bindings, see <a href="#readline_tty_keybindings">TTY keybindings</a>.</p>
<h3>Default evaluation<span><a class="mark" href="#repl_default_evaluation" id="repl_default_evaluation">#</a></span></h3>
<p>By default, all instances of <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> use an evaluation function
that evaluates JavaScript expressions and provides access to Node.js built-in
modules. This default behavior can be overridden by passing in an alternative
evaluation function when the <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> instance is created.</p>
<h4>JavaScript expressions<span><a class="mark" href="#repl_javascript_expressions" id="repl_javascript_expressions">#</a></span></h4>
<p>The default evaluator supports direct evaluation of JavaScript expressions:</p>
<pre><code class="language-console">> 1 + 1
2
> const m = 2
undefined
> m + 1
3
</code></pre>
<p>Unless otherwise scoped within blocks or functions, variables declared
either implicitly or using the <code>const</code>, <code>let</code>, or <code>var</code> keywords
are declared at the global scope.</p>
<h4>Global and local scope<span><a class="mark" href="#repl_global_and_local_scope" id="repl_global_and_local_scope">#</a></span></h4>
<p>The default evaluator provides access to any variables that exist in the global
scope. It is possible to expose a variable to the REPL explicitly by assigning
it to the <code>context</code> object associated with each <code>REPLServer</code>:</p>
<pre><code class="language-js">const repl = require('repl');
const msg = 'message';

repl.start('> ').context.m = msg;
</code></pre>
<p>Properties in the <code>context</code> object appear as local within the REPL:</p>
<pre><code class="language-console">$ node repl_test.js
> m
'message'
</code></pre>
<p>Context properties are not read-only by default. To specify read-only globals,
context properties must be defined using <code>Object.defineProperty()</code>:</p>
<pre><code class="language-js">const repl = require('repl');
const msg = 'message';

const r = repl.start('> ');
Object.defineProperty(r.context, 'm', {
  configurable: false,
  enumerable: true,
  value: msg
});
</code></pre>
<h4>Accessing core Node.js modules<span><a class="mark" href="#repl_accessing_core_node_js_modules" id="repl_accessing_core_node_js_modules">#</a></span></h4>
<p>The default evaluator will automatically load Node.js core modules into the
REPL environment when used. For instance, unless otherwise declared as a
global or scoped variable, the input <code>fs</code> will be evaluated on-demand as
<code>global.fs = require('fs')</code>.</p>
<pre><code class="language-console">> fs.createReadStream('./some/file');
</code></pre>
<h4>Global uncaught exceptions<span><a class="mark" href="#repl_global_uncaught_exceptions" id="repl_global_uncaught_exceptions">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.3.0</td>
<td><p>The <code>'uncaughtException'</code> event is from now on triggered if the repl is used as standalone program.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The REPL uses the <a href="domain.html"><code>domain</code></a> module to catch all uncaught exceptions for that
REPL session.</p>
<p>This use of the <a href="domain.html"><code>domain</code></a> module in the REPL has these side effects:</p>
<ul>
<li>Uncaught exceptions only emit the <a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a> event in the
standalone REPL. Adding a listener for this event in a REPL within
another Node.js program throws <a href="#errors_err_invalid_repl_input"><code>ERR_INVALID_REPL_INPUT</code></a>.</li>
<li>Trying to use <a href="#process_process_setuncaughtexceptioncapturecallback_fn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> throws
an <a href="#errors_err_domain_cannot_set_uncaught_exception_capture"><code>ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</code></a> error.</li>
</ul>
<p>As standalone program:</p>
<pre><code class="language-js">process.on('uncaughtException', () => console.log('Uncaught'));

throw new Error('foobar');
// Uncaught
</code></pre>
<p>When used in another application:</p>
<pre><code class="language-js">process.on('uncaughtException', () => console.log('Uncaught'));
// TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`
// cannot be used in the REPL

throw new Error('foobar');
// Thrown:
// Error: foobar
</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>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.8.0</td>
<td><p>Added <code>_error</code> support.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The default evaluator will, by default, assign the result of the most recently
evaluated expression to the special variable <code>_</code> (underscore).
Explicitly setting <code>_</code> to a value will disable this behavior.</p>
<pre><code class="language-console">> [ '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>
<pre><code class="language-console">> throw new Error('foo');
Error: foo
> _error.message
'foo'
</code></pre>
<h4><code>await</code> keyword<span><a class="mark" href="#repl_await_keyword" id="repl_await_keyword">#</a></span></h4>
<p>With the <a href="#cli_experimental_repl_await"><code>--experimental-repl-await</code></a> command line option specified,
experimental support for the <code>await</code> keyword is enabled.</p>
<pre><code class="language-console">> await Promise.resolve(123)
123
> await Promise.reject(new Error('REPL await'))
Error: REPL await
    at repl:1:45
> const timeout = util.promisify(setTimeout);
undefined
> const old = Date.now(); await timeout(1000); console.log(Date.now() - old);
1002
undefined
</code></pre>
<h3>Reverse-i-search<span><a class="mark" href="#repl_reverse_i_search" id="repl_reverse_i_search">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<p>The REPL supports bi-directional reverse-i-search similar to <a href="https://en.wikipedia.org/wiki/Z_shell">ZSH</a>. It is
triggered with <code>&#x3C;ctrl> + R</code> to search backwards and <code>&#x3C;ctrl> + S</code> to search
forwards.</p>
<p>Duplicated history entires will be skipped.</p>
<p>Entries are accepted as soon as any button is pressed that doesn't correspond
with the reverse search. Cancelling is possible by pressing <code>escape</code> or
<code>&#x3C;ctrl> + C</code>.</p>
<p>Changing the direction immediately searches for the next entry in the expected
direction from the current position on.</p>
<h3>Custom evaluation functions<span><a class="mark" href="#repl_custom_evaluation_functions" id="repl_custom_evaluation_functions">#</a></span></h3>
<p>When a new <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> is created, a custom evaluation function may be
provided. This can be used, for instance, to implement fully customized REPL
applications.</p>
<p>The following illustrates a hypothetical example of a REPL that performs
translation of text from one language to another:</p>
<pre><code class="language-js">const repl = require('repl');
const { Translator } = require('translator');

const myTranslator = new Translator('en', 'fr');

function myEval(cmd, context, filename, callback) {
  callback(null, myTranslator.translate(cmd));
}

repl.start({ prompt: '> ', eval: myEval });
</code></pre>
<h4>Recoverable errors<span><a class="mark" href="#repl_recoverable_errors" id="repl_recoverable_errors">#</a></span></h4>
<p>As a user is typing input into the REPL prompt, pressing the <code>&#x3C;enter></code> key will
send the current line of input to the <code>eval</code> function. In order to support
multi-line input, the eval function can return an instance of <code>repl.Recoverable</code>
to the provided callback function:</p>
<pre><code class="language-js">function myEval(cmd, context, filename, callback) {
  let result;
  try {
    result = vm.runInThisContext(cmd);
  } catch (e) {
    if (isRecoverableError(e)) {
      return callback(new repl.Recoverable(e));
    }
  }
  callback(null, result);
}

function isRecoverableError(error) {
  if (error.name === 'SyntaxError') {
    return /^(Unexpected end of input|Unexpected token)/.test(error.message);
  }
  return false;
}
</code></pre>
<h3>Customizing REPL output<span><a class="mark" href="#repl_customizing_repl_output" id="repl_customizing_repl_output">#</a></span></h3>
<p>By default, <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> instances format output using the
<a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> method before writing the output to the provided <code>Writable</code>
stream (<code>process.stdout</code> by default). The <code>showProxy</code> inspection option is set
to true by default and the <code>colors</code> option is set to true depending on the
REPL's <code>useColors</code> option.</p>
<p>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>If the REPL is run as standalone program, it is also possible to change the
REPL's <a href="#util_util_inspect_object_options">inspection defaults</a> from inside the REPL by using the
<code>inspect.replDefaults</code> property which mirrors the <code>defaultOptions</code> from
<a href="#util_util_inspect_object_options"><code>util.inspect()</code></a>.</p>
<pre><code class="language-console">> util.inspect.replDefaults.compact = false;
false
> [1]
[
  1
]
>
</code></pre>
<p>To fully customize the output of a <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> instance pass in a new
function for the <code>writer</code> option on construction. The following example, for
instance, simply converts any input text to upper case:</p>
<pre><code class="language-js">const repl = require('repl');

const r = repl.start({ prompt: '> ', eval: myEval, writer: myWriter });

function myEval(cmd, context, filename, callback) {
  callback(null, cmd);
}

function myWriter(output) {
  return output.toUpperCase();
}
</code></pre>
<h2>Class: <code>REPLServer</code><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>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> See <a href="#repl_repl_start_options"><code>repl.start()</code></a></li>
<li>Extends: <a href="#readline_class_interface" class="type">&#x3C;readline.Interface></a></li>
</ul>
<p>Instances of <code>repl.REPLServer</code> are created using the <a href="#repl_repl_start_options"><code>repl.start()</code></a> method
or directly using the JavaScript <code>new</code> keyword.</p>
<pre><code class="language-js">const repl = require('repl');

const options = { useColors: true };

const firstInstance = repl.start(options);
const secondInstance = new repl.REPLServer(options);
</code></pre>
<h3>Event: <code>'exit'</code><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>&#x3C;ctrl>-C</code> twice to signal <code>SIGINT</code>,
or by pressing <code>&#x3C;ctrl>-D</code> to signal <code>'end'</code> on the input stream. The listener
callback is invoked without any arguments.</p>
<pre><code class="language-js">replServer.on('exit', () => {
  console.log('Received "exit" event from repl!');
  process.exit();
});
</code></pre>
<h3>Event: <code>'reset'</code><span><a class="mark" href="#repl_event_reset" id="repl_event_reset">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.0</span>
</div>
<p>The <code>'reset'</code> event is emitted when the REPL's context is reset. This occurs
whenever the <code>.clear</code> command is received as input <em>unless</em> the REPL is using
the default evaluator and the <code>repl.REPLServer</code> instance was created with the
<code>useGlobal</code> option set to <code>true</code>. The listener callback will be called with a
reference to the <code>context</code> object as the only argument.</p>
<p>This can be used primarily to re-initialize REPL context to some pre-defined
state:</p>
<pre><code class="language-js">const repl = require('repl');

function initializeContext(context) {
  context.m = 'test';
}

const r = repl.start({ prompt: '> ' });
initializeContext(r.context);

r.on('reset', initializeContext);
</code></pre>
<p>When this code is executed, the global <code>'m'</code> variable can be modified but then
reset to its initial value using the <code>.clear</code> command:</p>
<pre><code class="language-console">$ ./node example.js
> m
'test'
> m = 1
1
> m
1
> .clear
Clearing context...
> m
'test'
>
</code></pre>
<h3><code>replServer.defineCommand(keyword, cmd)</code><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">&#x3C;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">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to invoke when the command is processed.</li>
</ul>
<p>The <code>replServer.defineCommand()</code> method is used to add new <code>.</code>-prefixed commands
to the REPL instance. Such commands are invoked by typing a <code>.</code> followed by the
<code>keyword</code>. The <code>cmd</code> is either a <code>Function</code> or an <code>Object</code> with the following
properties:</p>
<ul>
<li><code>help</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Function></a> The function to execute, optionally accepting a single
string argument.</li>
</ul>
<p>The following example shows two new commands added to the REPL instance:</p>
<pre><code class="language-js">const repl = require('repl');

const replServer = repl.start({ prompt: '> ' });
replServer.defineCommand('sayhello', {
  help: 'Say hello',
  action(name) {
    this.clearBufferedCommand();
    console.log(`Hello, ${name}!`);
    this.displayPrompt();
  }
});
replServer.defineCommand('saybye', function saybye() {
  console.log('Goodbye!');
  this.close();
});
</code></pre>
<p>The new commands can then be used from within the REPL instance:</p>
<pre><code class="language-console">> .sayhello Node.js User
Hello, Node.js User!
> .saybye
Goodbye!
</code></pre>
<h3><code>replServer.displayPrompt([preserveCursor])</code><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">&#x3C;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><code>replServer.clearBufferedCommand()</code><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><code>replServer.parseREPLKeyword(keyword[, rest])</code><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>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated.</div><p></p>
<ul>
<li><code>keyword</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> the potential keyword to parse and execute</li>
<li><code>rest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> any parameters to the keyword command</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<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>
<h3><code>replServer.setupHistory(historyPath, callback)</code><span><a class="mark" href="#repl_replserver_setuphistory_historypath_callback" id="repl_replserver_setuphistory_historypath_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><code>historyPath</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> the path to the history file</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> called when history writes are ready or upon error</p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>repl</code> <a href="#repl_class_replserver" class="type">&#x3C;repl.REPLServer></a></li>
</ul>
</li>
</ul>
<p>Initializes a history log file for the REPL instance. When executing the
Node.js binary and using the command line REPL, a history file is initialized
by default. However, this is not the case when creating a REPL
programmatically. Use this method to initialize a history log file when working
with REPL instances programmatically.</p>
<h2><code>repl.start([options])</code><span><a class="mark" href="#repl_repl_start_options" id="repl_repl_start_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>The <code>preview</code> option is now available.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>The <code>terminal</code> option now follows the default description in all cases and <code>useColors</code> checks <code>hasColors()</code> if available.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>REPL_MAGIC_MODE</code> <code>replMode</code> was removed.</p></td></tr>
<tr><td>v5.8.0</td>
<td><p>The <code>options</code> parameter is optional now.</p></td></tr>
<tr><td>v0.1.91</td>
<td><p><span>Added in: v0.1.91</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>prompt</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The input prompt to display. <strong>Default:</strong> <code>'> '</code>
(with a trailing space).</li>
<li><code>input</code> <a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a> The <code>Readable</code> stream from which REPL input will
be read. <strong>Default:</strong> <code>process.stdin</code>.</li>
<li><code>output</code> <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a> The <code>Writable</code> stream to which REPL output will
be written. <strong>Default:</strong> <code>process.stdout</code>.</li>
<li><code>terminal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, specifies that the <code>output</code> should be
treated as a TTY terminal.
<strong>Default:</strong> checking the value of the <code>isTTY</code> property on the <code>output</code>
stream upon instantiation.</li>
<li><code>eval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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">&#x3C;boolean></a> If <code>true</code>, specifies that the default <code>writer</code>
function should include ANSI color styling to REPL output. If a custom
<code>writer</code> function is provided then this has no effect. <strong>Default:</strong> checking
color support on the <code>output</code> stream if the REPL instance's <code>terminal</code> value
is <code>true</code>.</li>
<li><code>useGlobal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, specifies that the default evaluation
function will use the JavaScript <code>global</code> as the context as opposed to
creating a new separate context for the REPL instance. The node CLI REPL
sets this value to <code>true</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>ignoreUndefined</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, specifies that the default writer
will not output the return value of a command if it evaluates to
<code>undefined</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>writer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function to invoke to format the output of each
 command before writing to <code>output</code>. <strong>Default:</strong> <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a>.</li>
<li><code>completer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> An optional function used for custom Tab auto
 completion. See <a href="#readline_use_of_the_completer_function"><code>readline.InterfaceCompleter</code></a> for an example.</li>
<li>
<p><code>replMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> A flag that specifies whether the default evaluator
executes all JavaScript commands in strict mode or default (sloppy) mode.
Acceptable values are:</p>
<ul>
<li><code>repl.REPL_MODE_SLOPPY</code> to evaluate expressions in sloppy mode.</li>
<li><code>repl.REPL_MODE_STRICT</code> to evaluate expressions in strict mode. This is
equivalent to prefacing every repl statement with <code>'use strict'</code>.</li>
</ul>
</li>
<li><code>breakEvalOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Stop evaluating the current piece of code when
<code>SIGINT</code> is received, such as when <code>Ctrl+C</code> is pressed. This cannot be used
together with a custom <code>eval</code> function. <strong>Default:</strong> <code>false</code>.</li>
<li><code>preview</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Defines if the repl prints autocomplete and output
previews or not. <strong>Default:</strong> <code>true</code> with the default eval function and
<code>false</code> in case a custom eval function is used. If <code>terminal</code> is falsy, then
there are no previews and the value of <code>preview</code> has no effect.</li>
</ul>
</li>
<li>Returns: <a href="#repl_class_replserver" class="type">&#x3C;repl.REPLServer></a></li>
</ul>
<p>The <code>repl.start()</code> method creates and starts a <a href="#repl_class_replserver"><code>repl.REPLServer</code></a> instance.</p>
<p>If <code>options</code> is a string, then it specifies the input prompt:</p>
<pre><code class="language-js">const repl = require('repl');

// a Unix style prompt
repl.start('$ ');
</code></pre>
<h2>The Node.js REPL<span><a class="mark" href="#repl_the_node_js_repl" id="repl_the_node_js_repl">#</a></span></h2>
<p>Node.js itself uses the <code>repl</code> module to provide its own interactive interface
for executing JavaScript. This can be used by executing the Node.js binary
without passing any arguments (or by passing the <code>-i</code> argument):</p>
<pre><code class="language-console">$ node
> const a = [1, 2, 3];
undefined
> a
[ 1, 2, 3 ]
> a.forEach((v) => {
...   console.log(v);
...   });
1
2
3
</code></pre>
<h3>Environment variable options<span><a class="mark" href="#repl_environment_variable_options" id="repl_environment_variable_options">#</a></span></h3>
<p>Various behaviors of the Node.js REPL can be customized using the following
environment variables:</p>
<ul>
<li><code>NODE_REPL_HISTORY</code>: When a valid path is given, persistent REPL history
will be saved to the specified file rather than <code>.node_repl_history</code> in the
user's home directory. Setting this value to <code>''</code> (an empty string) will
disable persistent REPL history. Whitespace will be trimmed from the value.
On Windows platforms environment variables with empty values are invalid so
set this variable to one or more spaces to disable persistent REPL history.</li>
<li><code>NODE_REPL_HISTORY_SIZE</code>: Controls how many lines of history will be
persisted if history is available. Must be a positive number.
<strong>Default:</strong> <code>1000</code>.</li>
<li><code>NODE_REPL_MODE</code>: May be either <code>'sloppy'</code> or <code>'strict'</code>. <strong>Default:</strong>
<code>'sloppy'</code>, which will allow non-strict mode code to be run.</li>
</ul>
<h3>Persistent history<span><a class="mark" href="#repl_persistent_history" id="repl_persistent_history">#</a></span></h3>
<p>By default, the Node.js REPL will persist history between <code>node</code> REPL sessions
by saving inputs to a <code>.node_repl_history</code> file located in the user's home
directory. This can be disabled by setting the environment variable
<code>NODE_REPL_HISTORY=''</code>.</p>
<h3>Using the Node.js REPL with advanced line-editors<span><a class="mark" href="#repl_using_the_node_js_repl_with_advanced_line_editors" id="repl_using_the_node_js_repl_with_advanced_line_editors">#</a></span></h3>
<p>For advanced line-editors, start Node.js with the environment variable
<code>NODE_NO_READLINE=1</code>. This will start the main and debugger REPL in canonical
terminal settings, which will allow use with <code>rlwrap</code>.</p>
<p>For example, the following can be added to a <code>.bashrc</code> file:</p>
<pre><code class="language-text">alias node="env NODE_NO_READLINE=1 rlwrap node"
</code></pre>
<h3>Starting multiple REPL instances against a single running instance<span><a class="mark" href="#repl_starting_multiple_repl_instances_against_a_single_running_instance" id="repl_starting_multiple_repl_instances_against_a_single_running_instance">#</a></span></h3>
<p>It is possible to create and run multiple REPL instances against a single
running instance of Node.js that share a single <code>global</code> object but have
separate I/O interfaces.</p>
<p>The following example, for instance, provides separate REPLs on <code>stdin</code>, a Unix
socket, and a TCP socket:</p>
<pre><code class="language-js">const net = require('net');
const repl = require('repl');
let connections = 0;

repl.start({
  prompt: 'Node.js via stdin> ',
  input: process.stdin,
  output: process.stdout
});

net.createServer((socket) => {
  connections += 1;
  repl.start({
    prompt: 'Node.js via Unix socket> ',
    input: socket,
    output: socket
  }).on('exit', () => {
    socket.end();
  });
}).listen('/tmp/node-repl-sock');

net.createServer((socket) => {
  connections += 1;
  repl.start({
    prompt: 'Node.js via TCP socket> ',
    input: socket,
    output: socket
  }).on('exit', () => {
    socket.end();
  });
}).listen(5001);
</code></pre>
<p>Running this application from the command line will start a REPL on stdin.
Other REPL clients may connect through the Unix socket or TCP socket. <code>telnet</code>,
for instance, is useful for connecting to TCP sockets, while <code>socat</code> can be used
to connect to both Unix and TCP sockets.</p>
<p>By starting a REPL from a Unix socket-based server instead of stdin, it is
possible to connect to a long-running Node.js process without restarting it.</p>
<p>For an example of running a "full-featured" (<code>terminal</code>) REPL over
a <code>net.Server</code> and <code>net.Socket</code> instance, see:
<a href="https://gist.github.com/TooTallNate/2209310">https://gist.github.com/TooTallNate/2209310</a>.</p>
<p>For an example of running a REPL instance over <a href="https://curl.haxx.se/docs/manpage.html"></a><a href="https://curl.haxx.se/docs/manpage.html"><code>curl(1)</code></a>, see:
<a href="https://gist.github.com/TooTallNate/2053342">https://gist.github.com/TooTallNate/2053342</a>.</p>
<h1>Diagnostic report<span><a class="mark" href="#report_diagnostic_report" id="report_diagnostic_report">#</a></span></h1>


<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>

<p>Delivers a JSON-formatted diagnostic summary, written to a file.</p>
<p>The report is intended for development, test and production use, to capture
and preserve information for problem determination. It includes JavaScript
and native stack traces, heap statistics, platform information, resource
usage etc. With the report option enabled, diagnostic reports can be triggered
on unhandled exceptions, fatal errors and user signals, in addition to
triggering programmatically through API calls.</p>
<p>A complete example report that was generated on an uncaught exception
is provided below for reference.</p>
<pre><code class="language-json">{
  "header": {
    "reportVersion": 1,
    "event": "exception",
    "trigger": "Exception",
    "filename": "report.20181221.005011.8974.0.001.json",
    "dumpEventTime": "2018-12-21T00:50:11Z",
    "dumpEventTimeStamp": "1545371411331",
    "processId": 8974,
    "cwd": "/home/nodeuser/project/node",
    "commandLine": [
      "/home/nodeuser/project/node/out/Release/node",
      "--report-uncaught-exception",
      "/home/nodeuser/project/node/test/report/test-exception.js",
      "child"
    ],
    "nodejsVersion": "v12.0.0-pre",
    "glibcVersionRuntime": "2.17",
    "glibcVersionCompiler": "2.17",
    "wordSize": "64 bit",
    "arch": "x64",
    "platform": "linux",
    "componentVersions": {
      "node": "12.0.0-pre",
      "v8": "7.1.302.28-node.5",
      "uv": "1.24.1",
      "zlib": "1.2.11",
      "ares": "1.15.0",
      "modules": "68",
      "nghttp2": "1.34.0",
      "napi": "3",
      "llhttp": "1.0.1",
      "http_parser": "2.8.0",
      "openssl": "1.1.0j"
    },
    "release": {
      "name": "node"
    },
    "osName": "Linux",
    "osRelease": "3.10.0-862.el7.x86_64",
    "osVersion": "#1 SMP Wed Mar 21 18:14:51 EDT 2018",
    "osMachine": "x86_64",
    "cpus": [
      {
        "model": "Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz",
        "speed": 2700,
        "user": 88902660,
        "nice": 0,
        "sys": 50902570,
        "idle": 241732220,
        "irq": 0
      },
      {
        "model": "Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz",
        "speed": 2700,
        "user": 88902660,
        "nice": 0,
        "sys": 50902570,
        "idle": 241732220,
        "irq": 0
      }
    ],
    "networkInterfaces": [
      {
        "name": "en0",
        "internal": false,
        "mac": "13:10:de:ad:be:ef",
        "address": "10.0.0.37",
        "netmask": "255.255.255.0",
        "family": "IPv4"
      }
    ],
    "host": "test_machine"
  },
  "javascriptStack": {
    "message": "Error: *** test-exception.js: throwing uncaught Error",
    "stack": [
      "at myException (/home/nodeuser/project/node/test/report/test-exception.js:9:11)",
      "at Object.&#x3C;anonymous> (/home/nodeuser/project/node/test/report/test-exception.js:12:3)",
      "at Module._compile (internal/modules/cjs/loader.js:718:30)",
      "at Object.Module._extensions..js (internal/modules/cjs/loader.js:729:10)",
      "at Module.load (internal/modules/cjs/loader.js:617:32)",
      "at tryModuleLoad (internal/modules/cjs/loader.js:560:12)",
      "at Function.Module._load (internal/modules/cjs/loader.js:552:3)",
      "at Function.Module.runMain (internal/modules/cjs/loader.js:771:12)",
      "at executeUserCode (internal/bootstrap/node.js:332:15)"
    ]
  },
  "nativeStack": [
    {
      "pc": "0x000055b57f07a9ef",
      "symbol": "report::GetNodeReport(v8::Isolate*, node::Environment*, char const*, char const*, v8::Local&#x3C;v8::String>, std::ostream&#x26;) [./node]"
    },
    {
      "pc": "0x000055b57f07cf03",
      "symbol": "report::GetReport(v8::FunctionCallbackInfo&#x3C;v8::Value> const&#x26;) [./node]"
    },
    {
      "pc": "0x000055b57f1bccfd",
      "symbol": " [./node]"
    },
    {
      "pc": "0x000055b57f1be048",
      "symbol": "v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [./node]"
    },
    {
      "pc": "0x000055b57feeda0e",
      "symbol": " [./node]"
    }
  ],
  "javascriptHeap": {
    "totalMemory": 6127616,
    "totalCommittedMemory": 4357352,
    "usedMemory": 3221136,
    "availableMemory": 1521370240,
    "memoryLimit": 1526909922,
    "heapSpaces": {
      "read_only_space": {
        "memorySize": 524288,
        "committedMemory": 39208,
        "capacity": 515584,
        "used": 30504,
        "available": 485080
      },
      "new_space": {
        "memorySize": 2097152,
        "committedMemory": 2019312,
        "capacity": 1031168,
        "used": 985496,
        "available": 45672
      },
      "old_space": {
        "memorySize": 2273280,
        "committedMemory": 1769008,
        "capacity": 1974640,
        "used": 1725488,
        "available": 249152
      },
      "code_space": {
        "memorySize": 696320,
        "committedMemory": 184896,
        "capacity": 152128,
        "used": 152128,
        "available": 0
      },
      "map_space": {
        "memorySize": 536576,
        "committedMemory": 344928,
        "capacity": 327520,
        "used": 327520,
        "available": 0
      },
      "large_object_space": {
        "memorySize": 0,
        "committedMemory": 0,
        "capacity": 1520590336,
        "used": 0,
        "available": 1520590336
      },
      "new_large_object_space": {
        "memorySize": 0,
        "committedMemory": 0,
        "capacity": 0,
        "used": 0,
        "available": 0
      }
    }
  },
  "resourceUsage": {
    "userCpuSeconds": 0.069595,
    "kernelCpuSeconds": 0.019163,
    "cpuConsumptionPercent": 0.000000,
    "maxRss": 18079744,
    "pageFaults": {
      "IORequired": 0,
      "IONotRequired": 4610
    },
    "fsActivity": {
      "reads": 0,
      "writes": 0
    }
  },
  "uvthreadResourceUsage": {
    "userCpuSeconds": 0.068457,
    "kernelCpuSeconds": 0.019127,
    "cpuConsumptionPercent": 0.000000,
    "fsActivity": {
      "reads": 0,
      "writes": 0
    }
  },
  "libuv": [
    {
      "type": "async",
      "is_active": true,
      "is_referenced": false,
      "address": "0x0000000102910900",
      "details": ""
    },
    {
      "type": "timer",
      "is_active": false,
      "is_referenced": false,
      "address": "0x00007fff5fbfeab0",
      "repeat": 0,
      "firesInMsFromNow": 94403548320796,
      "expired": true
    },
    {
      "type": "check",
      "is_active": true,
      "is_referenced": false,
      "address": "0x00007fff5fbfeb48"
    },
    {
      "type": "idle",
      "is_active": false,
      "is_referenced": true,
      "address": "0x00007fff5fbfebc0"
    },
    {
      "type": "prepare",
      "is_active": false,
      "is_referenced": false,
      "address": "0x00007fff5fbfec38"
    },
    {
      "type": "check",
      "is_active": false,
      "is_referenced": false,
      "address": "0x00007fff5fbfecb0"
    },
    {
      "type": "async",
      "is_active": true,
      "is_referenced": false,
      "address": "0x000000010188f2e0"
    },
    {
      "type": "tty",
      "is_active": false,
      "is_referenced": true,
      "address": "0x000055b581db0e18",
      "width": 204,
      "height": 55,
      "fd": 17,
      "writeQueueSize": 0,
      "readable": true,
      "writable": true
    },
    {
      "type": "signal",
      "is_active": true,
      "is_referenced": false,
      "address": "0x000055b581d80010",
      "signum": 28,
      "signal": "SIGWINCH"
    },
    {
      "type": "tty",
      "is_active": true,
      "is_referenced": true,
      "address": "0x000055b581df59f8",
      "width": 204,
      "height": 55,
      "fd": 19,
      "writeQueueSize": 0,
      "readable": true,
      "writable": true
    },
    {
      "type": "loop",
      "is_active": true,
      "address": "0x000055fc7b2cb180"
    }
  ],
  "workers": [],
  "environmentVariables": {
    "REMOTEHOST": "REMOVED",
    "MANPATH": "/opt/rh/devtoolset-3/root/usr/share/man:",
    "XDG_SESSION_ID": "66126",
    "HOSTNAME": "test_machine",
    "HOST": "test_machine",
    "TERM": "xterm-256color",
    "SHELL": "/bin/csh",
    "SSH_CLIENT": "REMOVED",
    "PERL5LIB": "/opt/rh/devtoolset-3/root//usr/lib64/perl5/vendor_perl:/opt/rh/devtoolset-3/root/usr/lib/perl5:/opt/rh/devtoolset-3/root//usr/share/perl5/vendor_perl",
    "OLDPWD": "/home/nodeuser/project/node/src",
    "JAVACONFDIRS": "/opt/rh/devtoolset-3/root/etc/java:/etc/java",
    "SSH_TTY": "/dev/pts/0",
    "PCP_DIR": "/opt/rh/devtoolset-3/root",
    "GROUP": "normaluser",
    "USER": "nodeuser",
    "LD_LIBRARY_PATH": "/opt/rh/devtoolset-3/root/usr/lib64:/opt/rh/devtoolset-3/root/usr/lib",
    "HOSTTYPE": "x86_64-linux",
    "XDG_CONFIG_DIRS": "/opt/rh/devtoolset-3/root/etc/xdg:/etc/xdg",
    "MAIL": "/var/spool/mail/nodeuser",
    "PATH": "/home/nodeuser/project/node:/opt/rh/devtoolset-3/root/usr/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin",
    "PWD": "/home/nodeuser/project/node",
    "LANG": "en_US.UTF-8",
    "PS1": "\\u@\\h : \\[\\e[31m\\]\\w\\[\\e[m\\] >  ",
    "SHLVL": "2",
    "HOME": "/home/nodeuser",
    "OSTYPE": "linux",
    "VENDOR": "unknown",
    "PYTHONPATH": "/opt/rh/devtoolset-3/root/usr/lib64/python2.7/site-packages:/opt/rh/devtoolset-3/root/usr/lib/python2.7/site-packages",
    "MACHTYPE": "x86_64",
    "LOGNAME": "nodeuser",
    "XDG_DATA_DIRS": "/opt/rh/devtoolset-3/root/usr/share:/usr/local/share:/usr/share",
    "LESSOPEN": "||/usr/bin/lesspipe.sh %s",
    "INFOPATH": "/opt/rh/devtoolset-3/root/usr/share/info",
    "XDG_RUNTIME_DIR": "/run/user/50141",
    "_": "./node"
  },
  "userLimits": {
    "core_file_size_blocks": {
      "soft": "",
      "hard": "unlimited"
    },
    "data_seg_size_kbytes": {
      "soft": "unlimited",
      "hard": "unlimited"
    },
    "file_size_blocks": {
      "soft": "unlimited",
      "hard": "unlimited"
    },
    "max_locked_memory_bytes": {
      "soft": "unlimited",
      "hard": 65536
    },
    "max_memory_size_kbytes": {
      "soft": "unlimited",
      "hard": "unlimited"
    },
    "open_files": {
      "soft": "unlimited",
      "hard": 4096
    },
    "stack_size_bytes": {
      "soft": "unlimited",
      "hard": "unlimited"
    },
    "cpu_time_seconds": {
      "soft": "unlimited",
      "hard": "unlimited"
    },
    "max_user_processes": {
      "soft": "unlimited",
      "hard": 4127290
    },
    "virtual_memory_kbytes": {
      "soft": "unlimited",
      "hard": "unlimited"
    }
  },
  "sharedObjects": [
    "/lib64/libdl.so.2",
    "/lib64/librt.so.1",
    "/lib64/libstdc++.so.6",
    "/lib64/libm.so.6",
    "/lib64/libgcc_s.so.1",
    "/lib64/libpthread.so.0",
    "/lib64/libc.so.6",
    "/lib64/ld-linux-x86-64.so.2"
  ]
}
</code></pre>
<h2>Usage<span><a class="mark" href="#report_usage" id="report_usage">#</a></span></h2>
<pre><code class="language-bash">node --report-uncaught-exception --report-on-signal \
--report-on-fatalerror app.js
</code></pre>
<ul>
<li>
<p><code>--report-uncaught-exception</code> Enables report to be generated on
un-caught exceptions. Useful when inspecting JavaScript stack in conjunction
with native stack and other runtime environment data.</p>
</li>
<li>
<p><code>--report-on-signal</code> Enables report to be generated upon receiving
the specified (or predefined) signal to the running Node.js process. (See below
on how to modify the signal that triggers the report.) Default signal is <code>SIGUSR2</code>.
Useful when a report needs to be triggered from another program.
Application monitors may leverage this feature to collect report at regular
intervals and plot rich set of internal runtime data to their views.</p>
</li>
</ul>
<p>Signal based report generation is not supported in Windows.</p>
<p>Under normal circumstances, there is no need to modify the report triggering
signal. However, if <code>SIGUSR2</code> is already used for other purposes, then this
flag helps to change the signal for report generation and preserve the original
meaning of <code>SIGUSR2</code> for the said purposes.</p>
<ul>
<li>
<p><code>--report-on-fatalerror</code> Enables the report to be triggered on
fatal errors (internal errors within the Node.js runtime, such as out of memory)
that leads to termination of the application. Useful to inspect various
diagnostic data elements such as heap, stack, event loop state, resource
consumption etc. to reason about the fatal error.</p>
</li>
<li>
<p><code>--report-compact</code> Write reports in a compact format, single-line JSON, more
easily consumable by log processing systems than the default multi-line format
designed for human consumption.</p>
</li>
<li>
<p><code>--report-directory</code> Location at which the report will be
generated.</p>
</li>
<li>
<p><code>--report-filename</code> Name of the file to which the report will be
written.</p>
</li>
<li>
<p><code>--report-signal</code> Sets or resets the signal for report generation
(not supported on Windows). Default signal is <code>SIGUSR2</code>.</p>
</li>
</ul>
<p>A report can also be triggered via an API call from a JavaScript application:</p>
<pre><code class="language-js">process.report.writeReport();
</code></pre>
<p>This function takes an optional additional argument <code>filename</code>, which is
the name of a file into which the report is written.</p>
<pre><code class="language-js">process.report.writeReport('./foo.json');
</code></pre>
<p>This function takes an optional additional argument <code>err</code> which is an <code>Error</code>
object that will be used as the context for the JavaScript stack printed in the
report. When using report to handle errors in a callback or an exception
handler, this allows the report to include the location of the original error as
well as where it was handled.</p>
<pre><code class="language-js">try {
  process.chdir('/non-existent-path');
} catch (err) {
  process.report.writeReport(err);
}
// Any other code
</code></pre>
<p>If both filename and error object are passed to <code>writeReport()</code> the
error object must be the second parameter.</p>
<pre><code class="language-js">try {
  process.chdir('/non-existent-path');
} catch (err) {
  process.report.writeReport(filename, err);
}
// Any other code
</code></pre>
<p>The content of the diagnostic report can be returned as a JavaScript Object
via an API call from a JavaScript application:</p>
<pre><code class="language-js">const report = process.report.getReport();
console.log(typeof report === 'object'); // true

// Similar to process.report.writeReport() output
console.log(JSON.stringify(report, null, 2));
</code></pre>
<p>This function takes an optional additional argument <code>err</code>, which is an <code>Error</code>
object that will be used as the context for the JavaScript stack printed in the
report.</p>
<pre><code class="language-js">const report = process.report.getReport(new Error('custom error'));
console.log(typeof report === 'object'); // true
</code></pre>
<p>The API versions are useful when inspecting the runtime state from within
the application, in expectation of self-adjusting the resource consumption,
load balancing, monitoring etc.</p>
<p>The content of the report consists of a header section containing the event
type, date, time, PID and Node.js version, sections containing JavaScript and
native stack traces, a section containing V8 heap information, a section
containing <code>libuv</code> handle information and an OS platform information section
showing CPU and memory usage and system limits. An example report can be
triggered using the Node.js REPL:</p>
<pre><code class="language-console">$ node
> process.report.writeReport();
Writing Node.js report to file: report.20181126.091102.8480.0.001.json
Node.js report completed
>
</code></pre>
<p>When a report is written, start and end messages are issued to stderr
and the filename of the report is returned to the caller. The default filename
includes the date, time, PID and a sequence number. The sequence number helps
in associating the report dump with the runtime state if generated multiple
times for the same Node.js process.</p>
<h2>Configuration<span><a class="mark" href="#report_configuration" id="report_configuration">#</a></span></h2>
<p>Additional runtime configuration of report generation is available via
the following properties of <code>process.report</code>:</p>
<p><code>reportOnFatalError</code> triggers diagnostic reporting on fatal errors when <code>true</code>.
Defaults to <code>false</code>.</p>
<p><code>reportOnSignal</code> triggers diagnostic reporting on signal when <code>true</code>. This is
not supported on Windows. Defaults to <code>false</code>.</p>
<p><code>reportOnUncaughtException</code> triggers diagnostic reporting on uncaught exception
when <code>true</code>. Defaults to <code>false</code>.</p>
<p><code>signal</code> specifies the POSIX signal identifier that will be used
to intercept external triggers for report generation. Defaults to
<code>'SIGUSR2'</code>.</p>
<p><code>filename</code> specifies the name of the output file in the file system.
Special meaning is attached to <code>stdout</code> and <code>stderr</code>. Usage of these
will result in report being written to the associated standard streams.
In cases where standard streams are used, the value in <code>directory</code> is ignored.
URLs are not supported. Defaults to a composite filename that contains
timestamp, PID and sequence number.</p>
<p><code>directory</code> specifies the filesystem directory where the report will be written.
URLs are not supported. Defaults to the current working directory of the
Node.js process.</p>
<pre><code class="language-js">// Trigger report only on uncaught exceptions.
process.report.reportOnFatalError = false;
process.report.reportOnSignal = false;
process.report.reportOnUncaughtException = true;

// Trigger report for both internal errors as well as external signal.
process.report.reportOnFatalError = true;
process.report.reportOnSignal = true;
process.report.reportOnUncaughtException = false;

// Change the default signal to 'SIGQUIT' and enable it.
process.report.reportOnFatalError = false;
process.report.reportOnUncaughtException = false;
process.report.reportOnSignal = true;
process.report.signal = 'SIGQUIT';
</code></pre>
<p>Configuration on module initialization is also available via
environment variables:</p>
<pre><code class="language-bash">NODE_OPTIONS="--report-uncaught-exception \
  --report-on-fatalerror --report-on-signal \
  --report-signal=SIGUSR2  --report-filename=./report.json \
  --report-directory=/home/nodeuser"
</code></pre>
<p>Specific API documentation can be found under
<a href="process.html"><code>process API documentation</code></a> section.</p>
<h2>Interaction with workers<span><a class="mark" href="#report_interaction_with_workers" id="report_interaction_with_workers">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.2</td>
<td><p>Workers are now included in the report.</p></td></tr>
</tbody></table>
</details>
</div>
<p><a href="worker_threads.html"><code>Worker</code></a> threads can create reports in the same way that the main thread
does.</p>
<p>Reports will include information on any Workers that are children of the current
thread as part of the <code>workers</code> section, with each Worker generating a report
in the standard report format.</p>
<p>The thread which is generating the report will wait for the reports from Worker
threads to finish. However, the latency for this will usually be low, as both
running JavaScript and the event loop are interrupted to generate the report.</p>
<h1>Stream<a class="srclink" href="https://github.com/nodejs/node/blob/e3e0927bb93ed92bcdfe81e7ad9af3d78ccc74fb/lib/stream.js#L30">[src]</a><span><a class="mark" href="#stream_stream" id="stream_stream">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>A stream is an abstract interface for working with streaming data in Node.js.
The <code>stream</code> module provides an API for implementing the stream interface.</p>
<p>There are many stream objects provided by Node.js. For instance, a
<a href="#http_class_http_incomingmessage">request to an HTTP server</a> and <a href="#process_process_stdout"><code>process.stdout</code></a>
are both stream instances.</p>
<p>Streams can be readable, writable, or both. All streams are instances of
<a href="#events_class_eventemitter"><code>EventEmitter</code></a>.</p>
<p>To access the <code>stream</code> module:</p>
<pre><code class="language-js">const stream = require('stream');
</code></pre>
<p>The <code>stream</code> module is useful for creating new types of stream instances. It is
usually not necessary to use the <code>stream</code> module to consume streams.</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 contains two primary sections and a third section for notes. The
first section explains how to use existing streams within an application. The
second section explains how to create new types of streams.</p>
<h2>Types of streams<span><a class="mark" href="#stream_types_of_streams" id="stream_types_of_streams">#</a></span></h2>
<p>There are four fundamental stream types within Node.js:</p>
<ul>
<li><a href="#stream_class_stream_writable"><code>Writable</code></a>: streams to which data can be written (for example,
<a href="#fs_fs_createwritestream_path_options"><code>fs.createWriteStream()</code></a>).</li>
<li><a href="#stream_class_stream_readable"><code>Readable</code></a>: streams from which data can be read (for example,
<a href="#fs_fs_createreadstream_path_options"><code>fs.createReadStream()</code></a>).</li>
<li><a href="#stream_class_stream_duplex"><code>Duplex</code></a>: streams that are both <code>Readable</code> and <code>Writable</code> (for example,
<a href="#net_class_net_socket"><code>net.Socket</code></a>).</li>
<li><a href="#stream_class_stream_transform"><code>Transform</code></a>: <code>Duplex</code> streams that can modify or transform the data as it
is written and read (for example, <a href="#zlib_zlib_createdeflate_options"><code>zlib.createDeflate()</code></a>).</li>
</ul>
<p>Additionally, this module includes the utility functions
<a href="#stream_stream_pipeline_streams_callback"><code>stream.pipeline()</code></a>, <a href="#stream_stream_finished_stream_options_callback"><code>stream.finished()</code></a> and
<a href="#stream_stream_readable_from_iterable_options"><code>stream.Readable.from()</code></a>.</p>
<h3>Object mode<span><a class="mark" href="#stream_object_mode" id="stream_object_mode">#</a></span></h3>
<p>All streams created by Node.js APIs operate exclusively on strings and <code>Buffer</code>
(or <code>Uint8Array</code>) objects. It is possible, however, for stream implementations
to work with other types of JavaScript values (with the exception of <code>null</code>,
which serves a special purpose within streams). Such streams are considered to
operate in "object mode".</p>
<p>Stream instances are switched into object mode using the <code>objectMode</code> option
when the stream is created. Attempting to switch an existing stream into
object mode is not safe.</p>
<h3>Buffering<span><a class="mark" href="#stream_buffering" id="stream_buffering">#</a></span></h3>

<p>Both <a href="#stream_class_stream_writable"><code>Writable</code></a> and <a href="#stream_class_stream_readable"><code>Readable</code></a> streams will store data in an internal
buffer that can be retrieved using <code>writable.writableBuffer</code> or
<code>readable.readableBuffer</code>, respectively.</p>
<p>The amount of data potentially buffered depends on the <code>highWaterMark</code> option
passed into the stream's constructor. For normal streams, the <code>highWaterMark</code>
option specifies a <a href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding">total number of bytes</a>. For streams operating
in object mode, the <code>highWaterMark</code> specifies a total number of objects.</p>
<p>Data is buffered in <code>Readable</code> streams when the implementation calls
<a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not
call <a href="#stream_readable_read_size"><code>stream.read()</code></a>, the data will sit in the internal
queue until it is consumed.</p>
<p>Once the total size of the internal read buffer reaches the threshold specified
by <code>highWaterMark</code>, the stream will temporarily stop reading data from the
underlying resource until the data currently buffered can be consumed (that is,
the stream will stop calling the internal <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> method that is
used to fill the read buffer).</p>
<p>Data is buffered in <code>Writable</code> streams when the
<a href="#stream_writable_write_chunk_encoding_callback"><code>writable.write(chunk)</code></a> method is called repeatedly. While the
total size of the internal write buffer is below the threshold set by
<code>highWaterMark</code>, calls to <code>writable.write()</code> will return <code>true</code>. Once
the size of the internal buffer reaches or exceeds the <code>highWaterMark</code>, <code>false</code>
will be returned.</p>
<p>A key goal of the <code>stream</code> API, particularly the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method,
is to limit the buffering of data to acceptable levels such that sources and
destinations of differing speeds will not overwhelm the available memory.</p>
<p>The <code>highWaterMark</code> option is a threshold, not a limit: it dictates the amount
of data that a stream buffers before it stops asking for more data. It does not
enforce a strict memory limitation in general. Specific stream implementations
may choose to enforce stricter limits but doing so is optional.</p>
<p>Because <a href="#stream_class_stream_duplex"><code>Duplex</code></a> and <a href="#stream_class_stream_transform"><code>Transform</code></a> streams are both <code>Readable</code> and
<code>Writable</code>, each maintains <em>two</em> separate internal buffers used for reading and
writing, allowing each side to operate independently of the other while
maintaining an appropriate and efficient flow of data. For example,
<a href="#net_class_net_socket"><code>net.Socket</code></a> instances are <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams whose <code>Readable</code> side allows
consumption of data received <em>from</em> the socket and whose <code>Writable</code> side allows
writing data <em>to</em> the socket. Because data may be written to the socket at a
faster or slower rate than data is received, each side should
operate (and buffer) independently of the other.</p>
<h2>API for stream consumers<span><a class="mark" href="#stream_api_for_stream_consumers" id="stream_api_for_stream_consumers">#</a></span></h2>

<p>Almost all Node.js applications, no matter how simple, use streams in some
manner. The following is an example of using streams in a Node.js application
that implements an HTTP server:</p>
<pre><code class="language-js">const http = require('http');

const server = http.createServer((req, res) => {
  // `req` is an http.IncomingMessage, which is a readable stream.
  // `res` is an http.ServerResponse, which is a writable stream.

  let body = '';
  // Get the data as utf8 strings.
  // If an encoding is not set, Buffer objects will be received.
  req.setEncoding('utf8');

  // Readable streams emit 'data' events once a listener is added.
  req.on('data', (chunk) => {
    body += chunk;
  });

  // The 'end' event indicates that the entire body has been received.
  req.on('end', () => {
    try {
      const data = JSON.parse(body);
      // Write back something interesting to the user:
      res.write(typeof data);
      res.end();
    } catch (er) {
      // uh oh! bad json!
      res.statusCode = 400;
      return res.end(`error: ${er.message}`);
    }
  });
});

server.listen(1337);

// $ curl localhost:1337 -d "{}"
// object
// $ curl localhost:1337 -d "\"foo\""
// string
// $ curl localhost:1337 -d "not json"
// error: Unexpected token o in JSON at position 1
</code></pre>
<p><a href="#stream_class_stream_writable"><code>Writable</code></a> streams (such as <code>res</code> in the example) expose methods such as
<code>write()</code> and <code>end()</code> that are used to write data onto the stream.</p>
<p><a href="#stream_class_stream_readable"><code>Readable</code></a> streams use the <a href="#events_class_eventemitter"><code>EventEmitter</code></a> API for notifying application
code when data is available to be read off the stream. That available data can
be read from the stream in multiple ways.</p>
<p>Both <a href="#stream_class_stream_writable"><code>Writable</code></a> and <a href="#stream_class_stream_readable"><code>Readable</code></a> streams use the <a href="#events_class_eventemitter"><code>EventEmitter</code></a> API in
various ways to communicate the current state of the stream.</p>
<p><a href="#stream_class_stream_duplex"><code>Duplex</code></a> and <a href="#stream_class_stream_transform"><code>Transform</code></a> streams are both <a href="#stream_class_stream_writable"><code>Writable</code></a> and
<a href="#stream_class_stream_readable"><code>Readable</code></a>.</p>
<p>Applications that are either writing data to or consuming data from a stream
are not required to implement the stream interfaces directly and will generally
have no reason to call <code>require('stream')</code>.</p>
<p>Developers wishing to implement new types of streams should refer to the
section <a href="#stream_api_for_stream_implementers">API for stream implementers</a>.</p>
<h3>Writable streams<span><a class="mark" href="#stream_writable_streams" id="stream_writable_streams">#</a></span></h3>
<p>Writable streams are an abstraction for a <em>destination</em> to which data is
written.</p>
<p>Examples of <a href="#stream_class_stream_writable"><code>Writable</code></a> streams include:</p>
<ul>
<li><a href="#http_class_http_clientrequest">HTTP requests, on the client</a></li>
<li><a href="#http_class_http_serverresponse">HTTP responses, on the server</a></li>
<li><a href="#fs_class_fs_writestream">fs write streams</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
<li><a href="#net_class_net_socket">TCP sockets</a></li>
<li><a href="#child_process_subprocess_stdin">child process stdin</a></li>
<li><a href="#process_process_stdout"><code>process.stdout</code></a>, <a href="#process_process_stderr"><code>process.stderr</code></a></li>
</ul>
<p>Some of these examples are actually <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams that implement the
<a href="#stream_class_stream_writable"><code>Writable</code></a> interface.</p>
<p>All <a href="#stream_class_stream_writable"><code>Writable</code></a> streams implement the interface defined by the
<code>stream.Writable</code> class.</p>
<p>While specific instances of <a href="#stream_class_stream_writable"><code>Writable</code></a> streams may differ in various ways,
all <code>Writable</code> streams follow the same fundamental usage pattern as illustrated
in the example below:</p>
<pre><code class="language-js">const myStream = getWritableStreamSomehow();
myStream.write('some data');
myStream.write('some more data');
myStream.end('done writing data');
</code></pre>
<h4>Class: <code>stream.Writable</code><span><a class="mark" href="#stream_class_stream_writable" id="stream_class_stream_writable">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>

<h5>Event: <code>'close'</code><span><a class="mark" href="#stream_event_close" id="stream_event_close">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>'close'</code> event is emitted when the stream and any of its underlying
resources (a file descriptor, for example) have been closed. The event indicates
that no more events will be emitted, and no further computation will occur.</p>
<p>A <a href="#stream_class_stream_writable"><code>Writable</code></a> stream will always emit the <code>'close'</code> event if it is
created with the <code>emitClose</code> option.</p>
<h5>Event: <code>'drain'</code><span><a class="mark" href="#stream_event_drain" id="stream_event_drain">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>If a call to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write(chunk)</code></a> returns <code>false</code>, the
<code>'drain'</code> event will be emitted when it is appropriate to resume writing data
to the stream.</p>
<pre><code class="language-js">// Write the data to the supplied writable stream one million times.
// Be attentive to back-pressure.
function writeOneMillionTimes(writer, data, encoding, callback) {
  let i = 1000000;
  write();
  function write() {
    let ok = true;
    do {
      i--;
      if (i === 0) {
        // Last time!
        writer.write(data, encoding, callback);
      } else {
        // See if we should continue, or wait.
        // Don't pass the callback, because we're not done yet.
        ok = writer.write(data, encoding);
      }
    } while (i > 0 &#x26;&#x26; ok);
    if (i > 0) {
      // Had to stop early!
      // Write some more once it drains.
      writer.once('drain', write);
    }
  }
}
</code></pre>
<h5>Event: <code>'error'</code><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">&#x3C;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 unless the
<a href="#stream_constructor_new_stream_writable_options"><code>autoDestroy</code></a> option was set to <code>true</code> when creating the
stream.</p>
<h5>Event: <code>'finish'</code><span><a class="mark" href="#stream_event_finish" id="stream_event_finish">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'finish'</code> event is emitted after the <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> method
has been called, and all data has been flushed to the underlying system.</p>
<pre><code class="language-js">const writer = getWritableStreamSomehow();
for (let i = 0; i &#x3C; 100; i++) {
  writer.write(`hello, #${i}!\n`);
}
writer.on('finish', () => {
  console.log('All writes are now complete.');
});
writer.end('This is the end\n');
</code></pre>
<h5>Event: <code>'pipe'</code><span><a class="mark" href="#stream_event_pipe" id="stream_event_pipe">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>src</code> <a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a> source stream that is piping to this writable</li>
</ul>
<p>The <code>'pipe'</code> event is emitted when the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method is called on
a readable stream, adding this writable to its set of destinations.</p>
<pre><code class="language-js">const writer = getWritableStreamSomehow();
const reader = getReadableStreamSomehow();
writer.on('pipe', (src) => {
  console.log('Something is piping into the writer.');
  assert.equal(src, reader);
});
reader.pipe(writer);
</code></pre>
<h5>Event: <code>'unpipe'</code><span><a class="mark" href="#stream_event_unpipe" id="stream_event_unpipe">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>src</code> <a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a> The source stream that
<a href="#stream_readable_unpipe_destination">unpiped</a> this writable</li>
</ul>
<p>The <code>'unpipe'</code> event is emitted when the <a href="#stream_readable_unpipe_destination"><code>stream.unpipe()</code></a> method is called
on a <a href="#stream_class_stream_readable"><code>Readable</code></a> stream, removing this <a href="#stream_class_stream_writable"><code>Writable</code></a> from its set of
destinations.</p>
<p>This is also emitted in case this <a href="#stream_class_stream_writable"><code>Writable</code></a> stream emits an error when a
<a href="#stream_class_stream_readable"><code>Readable</code></a> stream pipes into it.</p>
<pre><code class="language-js">const writer = getWritableStreamSomehow();
const reader = getReadableStreamSomehow();
writer.on('unpipe', (src) => {
  console.log('Something has stopped piping into the writer.');
  assert.equal(src, reader);
});
reader.pipe(writer);
reader.unpipe(writer);
</code></pre>
<h5><code>writable.cork()</code><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 accommodate a situation in which
several small chunks are written to the stream in rapid succession. Instead of
immediately forwarding them to the underlying destination, <code>writable.cork()</code>
buffers all the chunks until <code>writable.uncork()</code> is called, which will pass them
all to <code>writable._writev()</code>, if present. This prevents a head-of-line blocking
situation where data is being buffered while waiting for the first small chunk
to be processed. However, use of <code>writable.cork()</code> without implementing
<code>writable._writev()</code> may have an adverse effect on throughput.</p>
<p>See also: <a href="#stream_writable_uncork"><code>writable.uncork()</code></a>, <a href="#stream_writable_writev_chunks_callback"><code>writable._writev()</code></a>.</p>
<h5><code>writable.destroy([error])</code><span><a class="mark" href="#stream_writable_destroy_error" id="stream_writable_destroy_error">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> Optional, an error to emit with <code>'error'</code> event.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type">&#x3C;this></a></li>
</ul>
<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code>
event (unless <code>emitClose</code> is set to <code>false</code>). After this call, the writable
stream has ended and subsequent calls to <code>write()</code> or <code>end()</code> will result in
an <code>ERR_STREAM_DESTROYED</code> error.
This is a destructive and immediate way to destroy a stream. Previous calls to
<code>write()</code> may not have drained, and may trigger an <code>ERR_STREAM_DESTROYED</code> error.
Use <code>end()</code> instead of destroy if data should flush before close, or wait for
the <code>'drain'</code> event before destroying the stream.
Implementors should not override this method,
but instead implement <a href="#stream_writable_destroy_err_callback"><code>writable._destroy()</code></a>.</p>
<h5><code>writable.destroyed</code><span><a class="mark" href="#stream_writable_destroyed" id="stream_writable_destroyed">#</a></span></h5>
<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#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> after <a href="#stream_writable_destroy_error"><code>writable.destroy()</code></a> has been called.</p>
<h5><code>writable.end([chunk[, encoding]][, callback])</code><span><a class="mark" href="#stream_writable_end_chunk_encoding_callback" id="stream_writable_end_chunk_encoding_callback">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Optional data to write. For streams
not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or
<code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value
other than <code>null</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Function></a> Optional callback for when the stream is finished</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type">&#x3C;this></a></li>
</ul>
<p>Calling the <code>writable.end()</code> method signals that no more data will be written
to the <a href="#stream_class_stream_writable"><code>Writable</code></a>. The optional <code>chunk</code> and <code>encoding</code> arguments allow one
final additional chunk of data to be written immediately before closing the
stream. If provided, the optional <code>callback</code> function is attached as a listener
for the <a href="#stream_event_finish"><code>'finish'</code></a> event.</p>
<p>Calling the <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> method after calling
<a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> will raise an error.</p>
<pre><code class="language-js">// Write 'hello, ' and then end with 'world!'.
const fs = require('fs');
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// Writing more now is not allowed!
</code></pre>
<h5><code>writable.setDefaultEncoding(encoding)</code><span><a class="mark" href="#stream_writable_setdefaultencoding_encoding" id="stream_writable_setdefaultencoding_encoding">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.1.0</td>
<td><p>This method now returns a reference to <code>writable</code>.</p></td></tr>
<tr><td>v0.11.15</td>
<td><p><span>Added in: v0.11.15</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;this></a></li>
</ul>
<p>The <code>writable.setDefaultEncoding()</code> method sets the default <code>encoding</code> for a
<a href="#stream_class_stream_writable"><code>Writable</code></a> stream.</p>
<h5><code>writable.uncork()</code><span><a class="mark" href="#stream_writable_uncork" id="stream_writable_uncork">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div>
<p>The <code>writable.uncork()</code> method flushes all data buffered since
<a href="#stream_writable_cork"><code>stream.cork()</code></a> was called.</p>
<p>When using <a href="#stream_writable_cork"><code>writable.cork()</code></a> and <code>writable.uncork()</code> to manage the buffering
of writes to a stream, it is recommended that calls to <code>writable.uncork()</code> be
deferred using <code>process.nextTick()</code>. Doing so allows batching of all
<code>writable.write()</code> calls that occur within a given Node.js event loop phase.</p>
<pre><code class="language-js">stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
</code></pre>
<p>If the <a href="#stream_writable_cork"><code>writable.cork()</code></a> method is called multiple times on a stream, the
same number of calls to <code>writable.uncork()</code> must be called to flush the buffered
data.</p>
<pre><code class="language-js">stream.cork();
stream.write('some ');
stream.cork();
stream.write('data ');
process.nextTick(() => {
  stream.uncork();
  // The data will not be flushed until uncork() is called a second time.
  stream.uncork();
});
</code></pre>
<p>See also: <a href="#stream_writable_cork"><code>writable.cork()</code></a>.</p>
<h5><code>writable.writable</code><span><a class="mark" href="#stream_writable_writable" id="stream_writable_writable">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v11.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> if it is safe to call <a href="#stream_writable_write_chunk_encoding_callback"><code>writable.write()</code></a>.</p>
<h5><code>writable.writableEnded</code><span><a class="mark" href="#stream_writable_writableended" id="stream_writable_writableended">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> after <a href="#stream_writable_end_chunk_encoding_callback"><code>writable.end()</code></a> has been called. This property
does not indicate whether the data has been flushed, for this use
<a href="#stream_writable_writablefinished"><code>writable.writableFinished</code></a> instead.</p>
<h5><code>writable.writableCorked</code><span><a class="mark" href="#stream_writable_writablecorked" id="stream_writable_writablecorked">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Number of times <a href="#stream_writable_uncork"><code>writable.uncork()</code></a> needs to be
called in order to fully uncork the stream.</p>
<h5><code>writable.writableFinished</code><span><a class="mark" href="#stream_writable_writablefinished" id="stream_writable_writablefinished">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v12.6.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is set to <code>true</code> immediately before the <a href="#stream_event_finish"><code>'finish'</code></a> event is emitted.</p>
<h5><code>writable.writableHighWaterMark</code><span><a class="mark" href="#stream_writable_writablehighwatermark" id="stream_writable_writablehighwatermark">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v9.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Return the value of <code>highWaterMark</code> passed when constructing this
<code>Writable</code>.</p>
<h5><code>writable.writableLength</code><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>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<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><code>writable.writableObjectMode</code><span><a class="mark" href="#stream_writable_writableobjectmode" id="stream_writable_writableobjectmode">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v12.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Getter for the property <code>objectMode</code> of a given <code>Writable</code> stream.</p>
<h5><code>writable.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#stream_writable_write_chunk_encoding_callback" id="stream_writable_write_chunk_encoding_callback">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Passing <code>null</code> as the <code>chunk</code> parameter will always be considered invalid now, even in object mode.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Optional data to write. For streams
not operating in object mode, <code>chunk</code> must be a string, <code>Buffer</code> or
<code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be any JavaScript value
other than <code>null</code>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The encoding, if <code>chunk</code> is a string. <strong>Default:</strong> <code>'utf8'</code></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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">&#x3C;boolean></a> <code>false</code> if the stream wishes for the calling code to
wait for the <code>'drain'</code> event to be emitted before continuing to write
additional data; otherwise <code>true</code>.</li>
</ul>
<p>The <code>writable.write()</code> method writes some data to the stream, and calls the
supplied <code>callback</code> once the data has been fully handled. If an error
occurs, the <code>callback</code> <em>may or may not</em> be called with the error as its
first argument. To reliably detect write errors, add a listener for the
<code>'error'</code> event.</p>
<p>The return value is <code>true</code> if the internal buffer is less than the
<code>highWaterMark</code> configured when the stream was created after admitting <code>chunk</code>.
If <code>false</code> is returned, further attempts to write data to the stream should
stop until the <a href="#stream_event_drain"><code>'drain'</code></a> event is emitted.</p>
<p>While a stream is not draining, calls to <code>write()</code> will buffer <code>chunk</code>, and
return false. Once all currently buffered chunks are drained (accepted for
delivery by the operating system), the <code>'drain'</code> event will be emitted.
It is recommended that once <code>write()</code> returns false, no more chunks be written
until the <code>'drain'</code> event is emitted. While calling <code>write()</code> on a stream that
is not draining is allowed, Node.js will buffer all written chunks until
maximum memory usage occurs, at which point it will abort unconditionally.
Even before it aborts, high memory usage will cause poor garbage collector
performance and high RSS (which is not typically released back to the system,
even after the memory is no longer required). Since TCP sockets may never
drain if the remote peer does not read the data, writing a socket that is
not draining may lead to a remotely exploitable vulnerability.</p>
<p>Writing data while the stream is not draining is particularly
problematic for a <a href="#stream_class_stream_transform"><code>Transform</code></a>, because the <code>Transform</code> streams are paused
by default until they are piped or a <code>'data'</code> or <code>'readable'</code> event handler
is added.</p>
<p>If the data to be written can be generated or fetched on demand, it is
recommended to encapsulate the logic into a <a href="#stream_class_stream_readable"><code>Readable</code></a> and use
<a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a>. However, if calling <code>write()</code> is preferred, it is
possible to respect backpressure and avoid memory issues using the
<a href="#stream_event_drain"><code>'drain'</code></a> event:</p>
<pre><code class="language-js">function write(data, cb) {
  if (!stream.write(data)) {
    stream.once('drain', cb);
  } else {
    process.nextTick(cb);
  }
}

// Wait for cb to be called before doing any other write.
write('hello', () => {
  console.log('Write completed, do more writes now.');
});
</code></pre>
<p>A <code>Writable</code> stream in object mode will always ignore the <code>encoding</code> argument.</p>
<h3>Readable streams<span><a class="mark" href="#stream_readable_streams" id="stream_readable_streams">#</a></span></h3>
<p>Readable streams are an abstraction for a <em>source</em> from which data is
consumed.</p>
<p>Examples of <code>Readable</code> streams include:</p>
<ul>
<li><a href="#http_class_http_incomingmessage">HTTP responses, on the client</a></li>
<li><a href="#http_class_http_incomingmessage">HTTP requests, on the server</a></li>
<li><a href="#fs_class_fs_readstream">fs read streams</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
<li><a href="#net_class_net_socket">TCP sockets</a></li>
<li><a href="#child_process_subprocess_stdout">child process stdout and stderr</a></li>
<li><a href="#process_process_stdin"><code>process.stdin</code></a></li>
</ul>
<p>All <a href="#stream_class_stream_readable"><code>Readable</code></a> streams implement the interface defined by the
<code>stream.Readable</code> class.</p>
<h4>Two reading modes<span><a class="mark" href="#stream_two_reading_modes" id="stream_two_reading_modes">#</a></span></h4>
<p><code>Readable</code> streams effectively operate in one of two modes: flowing and
paused. These modes are separate from <a href="#stream_object_mode">object mode</a>.
A <a href="#stream_class_stream_readable"><code>Readable</code></a> stream can be in object mode or not, regardless of whether
it is in flowing mode or paused mode.</p>
<ul>
<li>
<p>In flowing mode, data is read from the underlying system automatically
and provided to an application as quickly as possible using events via the
<a href="#events_class_eventemitter"><code>EventEmitter</code></a> interface.</p>
</li>
<li>
<p>In paused mode, the <a href="#stream_readable_read_size"><code>stream.read()</code></a> method must be called
explicitly to read chunks of data from the stream.</p>
</li>
</ul>
<p>All <a href="#stream_class_stream_readable"><code>Readable</code></a> streams begin in paused mode but can be switched to flowing
mode in one of the following ways:</p>
<ul>
<li>Adding a <a href="#stream_event_data"><code>'data'</code></a> event handler.</li>
<li>Calling the <a href="#stream_readable_resume"><code>stream.resume()</code></a> method.</li>
<li>Calling the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method to send the data to a <a href="#stream_class_stream_writable"><code>Writable</code></a>.</li>
</ul>
<p>The <code>Readable</code> can switch back to paused mode using one of the following:</p>
<ul>
<li>If there are no pipe destinations, by calling the
<a href="#stream_readable_pause"><code>stream.pause()</code></a> method.</li>
<li>If there are pipe destinations, by removing all pipe destinations.
Multiple pipe destinations may be removed by calling the
<a href="#stream_readable_unpipe_destination"><code>stream.unpipe()</code></a> method.</li>
</ul>
<p>The important concept to remember is that a <code>Readable</code> will not generate data
until a mechanism for either consuming or ignoring that data is provided. If
the consuming mechanism is disabled or taken away, the <code>Readable</code> will <em>attempt</em>
to stop generating the data.</p>
<p>For backward compatibility reasons, removing <a href="#stream_event_data"><code>'data'</code></a> event handlers will
<strong>not</strong> automatically pause the stream. Also, if there are piped destinations,
then calling <a href="#stream_readable_pause"><code>stream.pause()</code></a> will not guarantee that the
stream will <em>remain</em> paused once those destinations drain and ask for more data.</p>
<p>If a <a href="#stream_class_stream_readable"><code>Readable</code></a> is switched into flowing mode and there are no consumers
available to handle the data, that data will be lost. This can occur, for
instance, when the <code>readable.resume()</code> method is called without a listener
attached to the <code>'data'</code> event, or when a <code>'data'</code> event handler is removed
from the stream.</p>
<p>Adding a <a href="#stream_event_readable"><code>'readable'</code></a> event handler automatically make the stream to
stop flowing, and the data to be consumed via
<a href="#stream_readable_read_size"><code>readable.read()</code></a>. If the <a href="#stream_event_readable"><code>'readable'</code></a> event handler is
removed, then the stream will start flowing again if there is a
<a href="#stream_event_data"><code>'data'</code></a> event handler.</p>
<h4>Three states<span><a class="mark" href="#stream_three_states" id="stream_three_states">#</a></span></h4>
<p>The "two modes" of operation for a <code>Readable</code> stream are a simplified
abstraction for the more complicated internal state management that is happening
within the <code>Readable</code> stream implementation.</p>
<p>Specifically, at any given point in time, every <code>Readable</code> is in one of three
possible states:</p>
<ul>
<li><code>readable.readableFlowing === null</code></li>
<li><code>readable.readableFlowing === false</code></li>
<li><code>readable.readableFlowing === true</code></li>
</ul>
<p>When <code>readable.readableFlowing</code> is <code>null</code>, no mechanism for consuming the
stream's data is provided. Therefore, the stream will not generate data.
While in this state, attaching a listener for the <code>'data'</code> event, calling the
<code>readable.pipe()</code> method, or calling the <code>readable.resume()</code> method will switch
<code>readable.readableFlowing</code> to <code>true</code>, causing the <code>Readable</code> to begin actively
emitting events as data is generated.</p>
<p>Calling <code>readable.pause()</code>, <code>readable.unpipe()</code>, or receiving backpressure
will cause the <code>readable.readableFlowing</code> to be set as <code>false</code>,
temporarily halting the flowing of events but <em>not</em> halting the generation of
data. While in this state, attaching a listener for the <code>'data'</code> event
will not switch <code>readable.readableFlowing</code> to <code>true</code>.</p>
<pre><code class="language-js">const { PassThrough, Writable } = require('stream');
const pass = new PassThrough();
const writable = new Writable();

pass.pipe(writable);
pass.unpipe(writable);
// readableFlowing is now false.

pass.on('data', (chunk) => { console.log(chunk.toString()); });
pass.write('ok');  // Will not emit 'data'.
pass.resume();     // Must be called to make stream emit 'data'.
</code></pre>
<p>While <code>readable.readableFlowing</code> is <code>false</code>, data may be accumulating
within the stream's internal buffer.</p>
<h4>Choose one API style<span><a class="mark" href="#stream_choose_one_api_style" id="stream_choose_one_api_style">#</a></span></h4>
<p>The <code>Readable</code> stream API evolved across multiple Node.js versions and provides
multiple methods of consuming stream data. In general, developers should choose
<em>one</em> of the methods of consuming data and <em>should never</em> use multiple methods
to consume data from a single stream. Specifically, using a combination
of <code>on('data')</code>, <code>on('readable')</code>, <code>pipe()</code>, or async iterators could
lead to unintuitive behavior.</p>
<p>Use of the <code>readable.pipe()</code> method is recommended for most users as it has been
implemented to provide the easiest way of consuming stream data. Developers that
require more fine-grained control over the transfer and generation of data can
use the <a href="#events_class_eventemitter"><code>EventEmitter</code></a> and <code>readable.on('readable')</code>/<code>readable.read()</code>
or the <code>readable.pause()</code>/<code>readable.resume()</code> APIs.</p>
<h4>Class: <code>stream.Readable</code><span><a class="mark" href="#stream_class_stream_readable" id="stream_class_stream_readable">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>

<h5>Event: <code>'close'</code><span><a class="mark" href="#stream_event_close_1" id="stream_event_close_1">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>'close'</code> event is emitted when the stream and any of its underlying
resources (a file descriptor, for example) have been closed. The event indicates
that no more events will be emitted, and no further computation will occur.</p>
<p>A <a href="#stream_class_stream_readable"><code>Readable</code></a> stream will always emit the <code>'close'</code> event if it is
created with the <code>emitClose</code> option.</p>
<h5>Event: <code>'data'</code><span><a class="mark" href="#stream_event_data" id="stream_event_data">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>chunk</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The chunk of data. For streams that are not
operating in object mode, the chunk will be either a string or <code>Buffer</code>.
For streams that are in object mode, the chunk can be any JavaScript value
other than <code>null</code>.</li>
</ul>
<p>The <code>'data'</code> event is emitted whenever the stream is relinquishing ownership of
a chunk of data to a consumer. This may occur whenever the stream is switched
in flowing mode by calling <code>readable.pipe()</code>, <code>readable.resume()</code>, or by
attaching a listener callback to the <code>'data'</code> event. The <code>'data'</code> event will
also be emitted whenever the <code>readable.read()</code> method is called and a chunk of
data is available to be returned.</p>
<p>Attaching a <code>'data'</code> event listener to a stream that has not been explicitly
paused will switch the stream into flowing mode. Data will then be passed as
soon as it is available.</p>
<p>The listener callback will be passed the chunk of data as a string if a default
encoding has been specified for the stream using the
<code>readable.setEncoding()</code> method; otherwise the data will be passed as a
<code>Buffer</code>.</p>
<pre><code class="language-js">const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
  console.log(`Received ${chunk.length} bytes of data.`);
});
</code></pre>
<h5>Event: <code>'end'</code><span><a class="mark" href="#stream_event_end" id="stream_event_end">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'end'</code> event is emitted when there is no more data to be consumed from
the stream.</p>
<p>The <code>'end'</code> event <strong>will not be emitted</strong> unless the data is completely
consumed. This can be accomplished by switching the stream into flowing mode,
or by calling <a href="#stream_readable_read_size"><code>stream.read()</code></a> repeatedly until all data has been
consumed.</p>
<pre><code class="language-js">const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
  console.log(`Received ${chunk.length} bytes of data.`);
});
readable.on('end', () => {
  console.log('There will be no more data.');
});
</code></pre>
<h5>Event: <code>'error'</code><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">&#x3C;Error></a></li>
</ul>
<p>The <code>'error'</code> event may be emitted by a <code>Readable</code> implementation at any time.
Typically, this may occur if the underlying stream is unable to generate data
due to an underlying internal failure, or when a stream implementation attempts
to push an invalid chunk of data.</p>
<p>The listener callback will be passed a single <code>Error</code> object.</p>
<h5>Event: <code>'pause'</code><span><a class="mark" href="#stream_event_pause" id="stream_event_pause">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'pause'</code> event is emitted when <a href="#stream_readable_pause"><code>stream.pause()</code></a> is called
and <code>readableFlowing</code> is not <code>false</code>.</p>
<h5>Event: <code>'readable'</code><span><a class="mark" href="#stream_event_readable" id="stream_event_readable">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>'readable'</code> is always emitted in the next tick after <code>.push()</code> is called.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Using <code>'readable'</code> requires calling <code>.read()</code>.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>'readable'</code> event is emitted when there is data available to be read from
the stream. In some cases, attaching a listener for the <code>'readable'</code> event will
cause some amount of data to be read into an internal buffer.</p>
<pre><code class="language-js">const readable = getReadableStreamSomehow();
readable.on('readable', function() {
  // There is some data to read now.
  let data;

  while (data = this.read()) {
    console.log(data);
  }
});
</code></pre>
<p>The <code>'readable'</code> event will also be emitted once the end of the stream data
has been reached but before the <code>'end'</code> event is emitted.</p>
<p>Effectively, the <code>'readable'</code> event indicates that the stream has new
information: either new data is available or the end of the stream has been
reached. In the former case, <a href="#stream_readable_read_size"><code>stream.read()</code></a> will return the
available data. In the latter case, <a href="#stream_readable_read_size"><code>stream.read()</code></a> will return
<code>null</code>. For instance, in the following example, <code>foo.txt</code> is an empty file:</p>
<pre><code class="language-js">const fs = require('fs');
const rr = fs.createReadStream('foo.txt');
rr.on('readable', () => {
  console.log(`readable: ${rr.read()}`);
});
rr.on('end', () => {
  console.log('end');
});
</code></pre>
<p>The output of running this script is:</p>
<pre><code class="language-console">$ node test.js
readable: null
end
</code></pre>
<p>In general, the <code>readable.pipe()</code> and <code>'data'</code> event mechanisms are easier to
understand than the <code>'readable'</code> event. However, handling <code>'readable'</code> might
result in increased throughput.</p>
<p>If both <code>'readable'</code> and <a href="#stream_event_data"><code>'data'</code></a> are used at the same time, <code>'readable'</code>
takes precedence in controlling the flow, i.e. <code>'data'</code> will be emitted
only when <a href="#stream_readable_read_size"><code>stream.read()</code></a> is called. The
<code>readableFlowing</code> property would become <code>false</code>.
If there are <code>'data'</code> listeners when <code>'readable'</code> is removed, the stream
will start flowing, i.e. <code>'data'</code> events will be emitted without calling
<code>.resume()</code>.</p>
<h5>Event: <code>'resume'</code><span><a class="mark" href="#stream_event_resume" id="stream_event_resume">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'resume'</code> event is emitted when <a href="#stream_readable_resume"><code>stream.resume()</code></a> is
called and <code>readableFlowing</code> is not <code>true</code>.</p>
<h5><code>readable.destroy([error])</code><span><a class="mark" href="#stream_readable_destroy_error" id="stream_readable_destroy_error">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> Error which will be passed as payload in <code>'error'</code> event</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type">&#x3C;this></a></li>
</ul>
<p>Destroy the stream. Optionally emit an <code>'error'</code> event, and emit a <code>'close'</code>
event (unless <code>emitClose</code> is set to <code>false</code>). After this call, the readable
stream will release any internal resources and subsequent calls to <code>push()</code>
will be ignored.
Implementors should not override this method, but instead implement
<a href="#stream_readable_destroy_err_callback"><code>readable._destroy()</code></a>.</p>
<h5><code>readable.destroyed</code><span><a class="mark" href="#stream_readable_destroyed" id="stream_readable_destroyed">#</a></span></h5>
<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#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> after <a href="#stream_readable_destroy_error"><code>readable.destroy()</code></a> has been called.</p>
<h5><code>readable.isPaused()</code><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">&#x3C;boolean></a></li>
</ul>
<p>The <code>readable.isPaused()</code> method returns the current operating state of the
<code>Readable</code>. This is used primarily by the mechanism that underlies the
<code>readable.pipe()</code> method. In most typical cases, there will be no reason to
use this method directly.</p>
<pre><code class="language-js">const readable = new stream.Readable();

readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
</code></pre>
<h5><code>readable.pause()</code><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">&#x3C;this></a></li>
</ul>
<p>The <code>readable.pause()</code> method will cause a stream in flowing mode to stop
emitting <a href="#stream_event_data"><code>'data'</code></a> events, switching out of flowing mode. Any data that
becomes available will remain in the internal buffer.</p>
<pre><code class="language-js">const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
  console.log(`Received ${chunk.length} bytes of data.`);
  readable.pause();
  console.log('There will be no additional data for 1 second.');
  setTimeout(() => {
    console.log('Now data will start flowing again.');
    readable.resume();
  }, 1000);
});
</code></pre>
<p>The <code>readable.pause()</code> method has no effect if there is a <code>'readable'</code>
event listener.</p>
<h5><code>readable.pipe(destination[, options])</code><span><a class="mark" href="#stream_readable_pipe_destination_options" id="stream_readable_pipe_destination_options">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>destination</code> <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a> The destination for writing data</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Pipe options</p>
<ul>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> End the writer when the reader ends. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li>Returns: <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a> The <em>destination</em>, allowing for a chain of pipes if
it is a <a href="#stream_class_stream_duplex"><code>Duplex</code></a> or a <a href="#stream_class_stream_transform"><code>Transform</code></a> stream</li>
</ul>
<p>The <code>readable.pipe()</code> method attaches a <a href="#stream_class_stream_writable"><code>Writable</code></a> stream to the <code>readable</code>,
causing it to switch automatically into flowing mode and push all of its data
to the attached <a href="#stream_class_stream_writable"><code>Writable</code></a>. The flow of data will be automatically managed
so that the destination <code>Writable</code> stream is not overwhelmed by a faster
<code>Readable</code> stream.</p>
<p>The following example pipes all of the data from the <code>readable</code> into a file
named <code>file.txt</code>:</p>
<pre><code class="language-js">const fs = require('fs');
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt'.
readable.pipe(writable);
</code></pre>
<p>It is possible to attach multiple <code>Writable</code> streams to a single <code>Readable</code>
stream.</p>
<p>The <code>readable.pipe()</code> method returns a reference to the <em>destination</em> stream
making it possible to set up chains of piped streams:</p>
<pre><code class="language-js">const fs = require('fs');
const r = fs.createReadStream('file.txt');
const z = zlib.createGzip();
const w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
</code></pre>
<p>By default, <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> is called on the destination <code>Writable</code>
stream when the source <code>Readable</code> stream emits <a href="#stream_event_end"><code>'end'</code></a>, so that the
destination is no longer writable. To disable this default behavior, the <code>end</code>
option can be passed as <code>false</code>, causing the destination stream to remain open:</p>
<pre><code class="language-js">reader.pipe(writer, { end: false });
reader.on('end', () => {
  writer.end('Goodbye\n');
});
</code></pre>
<p>One important caveat is that if the <code>Readable</code> stream emits an error during
processing, the <code>Writable</code> destination <em>is not closed</em> automatically. If an
error occurs, it will be necessary to <em>manually</em> close each stream in order
to prevent memory leaks.</p>
<p>The <a href="#process_process_stderr"><code>process.stderr</code></a> and <a href="#process_process_stdout"><code>process.stdout</code></a> <code>Writable</code> streams are never
closed until the Node.js process exits, regardless of the specified options.</p>
<h5><code>readable.read([size])</code><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">&#x3C;number></a> Optional argument to specify how much data to read.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>The <code>readable.read()</code> method pulls some data out of the internal buffer and
returns it. If no data available to be read, <code>null</code> is returned. By default,
the data will be returned as a <code>Buffer</code> object unless an encoding has been
specified using the <code>readable.setEncoding()</code> method or the stream is operating
in object mode.</p>
<p>The optional <code>size</code> argument specifies a specific number of bytes to read. If
<code>size</code> bytes are not available to be read, <code>null</code> will be returned <em>unless</em>
the stream has ended, in which case all of the data remaining in the internal
buffer will be returned.</p>
<p>If the <code>size</code> argument is not specified, all of the data contained in the
internal buffer will be returned.</p>
<p>The <code>size</code> argument must be less than or equal to 1 GB.</p>
<p>The <code>readable.read()</code> method should only be called on <code>Readable</code> streams
operating in paused mode. In flowing mode, <code>readable.read()</code> is called
automatically until the internal buffer is fully drained.</p>
<pre><code class="language-js">const readable = getReadableStreamSomehow();
readable.on('readable', () => {
  let chunk;
  while (null !== (chunk = readable.read())) {
    console.log(`Received ${chunk.length} bytes of data.`);
  }
});
</code></pre>
<p>The <code>while</code> loop is necessary when processing data with
<code>readable.read()</code>. Only after <code>readable.read()</code> returns <code>null</code>,
<a href="#stream_event_readable"><code>'readable'</code></a> will be emitted.</p>
<p>A <code>Readable</code> stream in object mode will always return a single item from
a call to <a href="#stream_readable_read_size"><code>readable.read(size)</code></a>, regardless of the value of the
<code>size</code> argument.</p>
<p>If the <code>readable.read()</code> method returns a chunk of data, a <code>'data'</code> event will
also be emitted.</p>
<p>Calling <a href="#stream_readable_read_size"><code>stream.read([size])</code></a> after the <a href="#stream_event_end"><code>'end'</code></a> event has
been emitted will return <code>null</code>. No runtime error will be raised.</p>
<h5><code>readable.readable</code><span><a class="mark" href="#stream_readable_readable" id="stream_readable_readable">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v11.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> if it is safe to call <a href="#stream_readable_read_size"><code>readable.read()</code></a>.</p>
<h5><code>readable.readableEncoding</code><span><a class="mark" href="#stream_readable_readableencoding" id="stream_readable_readableencoding">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v12.7.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Getter for the property <code>encoding</code> of a given <code>Readable</code> stream. The <code>encoding</code>
property can be set using the <a href="#stream_readable_setencoding_encoding"><code>readable.setEncoding()</code></a> method.</p>
<h5><code>readable.readableEnded</code><span><a class="mark" href="#stream_readable_readableended" id="stream_readable_readableended">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Becomes <code>true</code> when <a href="#stream_event_end"><code>'end'</code></a> event is emitted.</p>
<h5><code>readable.readableFlowing</code><span><a class="mark" href="#stream_readable_readableflowing" id="stream_readable_readableflowing">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>This property reflects the current state of a <code>Readable</code> stream as described
in the <a href="#stream_three_states">Three states</a> section.</p>
<h5><code>readable.readableHighWaterMark</code><span><a class="mark" href="#stream_readable_readablehighwatermark" id="stream_readable_readablehighwatermark">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v9.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Returns the value of <code>highWaterMark</code> passed when constructing this
<code>Readable</code>.</p>
<h5><code>readable.readableLength</code><span><a class="mark" href="#stream_readable_readablelength" id="stream_readable_readablelength">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>This property contains the number of bytes (or objects) in the queue
ready to be read. The value provides introspection data regarding
the status of the <code>highWaterMark</code>.</p>
<h5><code>readable.readableObjectMode</code><span><a class="mark" href="#stream_readable_readableobjectmode" id="stream_readable_readableobjectmode">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v12.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Getter for the property <code>objectMode</code> of a given <code>Readable</code> stream.</p>
<h5><code>readable.resume()</code><span><a class="mark" href="#stream_readable_resume" id="stream_readable_resume">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>resume()</code> has no effect if there is a <code>'readable'</code> event listening.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type">&#x3C;this></a></li>
</ul>
<p>The <code>readable.resume()</code> method causes an explicitly paused <code>Readable</code> stream to
resume emitting <a href="#stream_event_data"><code>'data'</code></a> events, switching the stream into flowing mode.</p>
<p>The <code>readable.resume()</code> method can be used to fully consume the data from a
stream without actually processing any of that data:</p>
<pre><code class="language-js">getReadableStreamSomehow()
  .resume()
  .on('end', () => {
    console.log('Reached the end, but did not read anything.');
  });
</code></pre>
<p>The <code>readable.resume()</code> method has no effect if there is a <code>'readable'</code>
event listener.</p>
<h5><code>readable.setEncoding(encoding)</code><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">&#x3C;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">&#x3C;this></a></li>
</ul>
<p>The <code>readable.setEncoding()</code> method sets the character encoding for
data read from the <code>Readable</code> stream.</p>
<p>By default, no encoding is assigned and stream data will be returned as
<code>Buffer</code> objects. Setting an encoding causes the stream data
to be returned as strings of the specified encoding rather than as <code>Buffer</code>
objects. For instance, calling <code>readable.setEncoding('utf8')</code> will cause the
output data to be interpreted as UTF-8 data, and passed as strings. Calling
<code>readable.setEncoding('hex')</code> will cause the data to be encoded in hexadecimal
string format.</p>
<p>The <code>Readable</code> stream will properly handle multi-byte characters delivered
through the stream that would otherwise become improperly decoded if simply
pulled from the stream as <code>Buffer</code> objects.</p>
<pre><code class="language-js">const readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
  assert.equal(typeof chunk, 'string');
  console.log('Got %d characters of string data:', chunk.length);
});
</code></pre>
<h5><code>readable.unpipe([destination])</code><span><a class="mark" href="#stream_readable_unpipe_destination" id="stream_readable_unpipe_destination">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>destination</code> <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a> Optional specific stream to unpipe</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type">&#x3C;this></a></li>
</ul>
<p>The <code>readable.unpipe()</code> method detaches a <code>Writable</code> stream previously attached
using the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method.</p>
<p>If the <code>destination</code> is not specified, then <em>all</em> pipes are detached.</p>
<p>If the <code>destination</code> is specified, but no pipe is set up for it, then
the method does nothing.</p>
<pre><code class="language-js">const fs = require('fs');
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second.
readable.pipe(writable);
setTimeout(() => {
  console.log('Stop writing to file.txt.');
  readable.unpipe(writable);
  console.log('Manually close the file stream.');
  writable.end();
}, 1000);
</code></pre>
<h5><code>readable.unshift(chunk[, encoding])</code><span><a class="mark" href="#stream_readable_unshift_chunk_encoding" id="stream_readable_unshift_chunk_encoding">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr>
<tr><td>v0.9.11</td>
<td><p><span>Added in: v0.9.11</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Chunk of data to unshift onto the
read queue. For streams not operating in object mode, <code>chunk</code> must be a
string, <code>Buffer</code>, <code>Uint8Array</code> or <code>null</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">&#x3C;string></a> Encoding of string chunks. Must be a valid
<code>Buffer</code> encoding, such as <code>'utf8'</code> or <code>'ascii'</code>.</li>
</ul>
<p>Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF) and behaves the
same as <code>readable.push(null)</code>, after which no more data can be written. The EOF
signal is put at the end of the buffer and any buffered data will still be
flushed.</p>
<p>The <code>readable.unshift()</code> method pushes a chunk of data back into the internal
buffer. This is useful in certain situations where a stream is being consumed by
code that needs to "un-consume" some amount of data that it has optimistically
pulled out of the source, so that the data can be passed on to some other party.</p>
<p>The <code>stream.unshift(chunk)</code> method cannot be called after the <a href="#stream_event_end"><code>'end'</code></a> event
has been emitted or a runtime error will be thrown.</p>
<p>Developers using <code>stream.unshift()</code> often should consider switching to
use of a <a href="#stream_class_stream_transform"><code>Transform</code></a> stream instead. See the <a href="#stream_api_for_stream_implementers">API for stream implementers</a>
section for more information.</p>
<pre><code class="language-js">// Pull off a header delimited by \n\n.
// Use unshift() if we get too much.
// Call the callback with (error, header, stream).
const { StringDecoder } = require('string_decoder');
function parseHeader(stream, callback) {
  stream.on('error', callback);
  stream.on('readable', onReadable);
  const decoder = new StringDecoder('utf8');
  let header = '';
  function onReadable() {
    let chunk;
    while (null !== (chunk = stream.read())) {
      const str = decoder.write(chunk);
      if (str.match(/\n\n/)) {
        // Found the header boundary.
        const split = str.split(/\n\n/);
        header += split.shift();
        const remaining = split.join('\n\n');
        const buf = Buffer.from(remaining, 'utf8');
        stream.removeListener('error', callback);
        // Remove the 'readable' listener before unshifting.
        stream.removeListener('readable', onReadable);
        if (buf.length)
          stream.unshift(buf);
        // Now the body of the message can be read from the stream.
        callback(null, header, stream);
      } else {
        // Still reading the header.
        header += str;
      }
    }
  }
}
</code></pre>
<p>Unlike <a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>, <code>stream.unshift(chunk)</code> will not
end the reading process by resetting the internal reading state of the stream.
This can cause unexpected results if <code>readable.unshift()</code> is called during a
read (i.e. from within a <a href="#stream_readable_read_size_1"><code>stream._read()</code></a> implementation on a
custom stream). Following the call to <code>readable.unshift()</code> with an immediate
<a href="#stream_readable_push_chunk_encoding"><code>stream.push('')</code></a> will reset the reading state appropriately,
however it is best to simply avoid calling <code>readable.unshift()</code> while in the
process of performing a read.</p>
<h5><code>readable.wrap(stream)</code><span><a class="mark" href="#stream_readable_wrap_stream" id="stream_readable_wrap_stream">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>stream</code> <a href="#stream_stream" class="type">&#x3C;Stream></a> An "old style" readable stream</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type">&#x3C;this></a></li>
</ul>
<p>Prior to Node.js 0.10, streams did not implement the entire <code>stream</code> module API
as it is currently defined. (See <a href="#stream_compatibility_with_older_node_js_versions">Compatibility</a> for more information.)</p>
<p>When using an older Node.js library that emits <a href="#stream_event_data"><code>'data'</code></a> events and has a
<a href="#stream_readable_pause"><code>stream.pause()</code></a> method that is advisory only, the
<code>readable.wrap()</code> method can be used to create a <a href="#stream_class_stream_readable"><code>Readable</code></a> stream that uses
the old stream as its data source.</p>
<p>It will rarely be necessary to use <code>readable.wrap()</code> but the method has been
provided as a convenience for interacting with older Node.js applications and
libraries.</p>
<pre><code class="language-js">const { OldReader } = require('./old-api-module.js');
const { Readable } = require('stream');
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);

myReader.on('readable', () => {
  myReader.read(); // etc.
});
</code></pre>
<h5><code>readable[Symbol.asyncIterator]()</code><span><a class="mark" href="#stream_readable_symbol_asynciterator" id="stream_readable_symbol_asynciterator">#</a></span></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.14.0</td>
<td><p>Symbol.asyncIterator support is no longer experimental.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p><span>Added in: v10.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type">&#x3C;AsyncIterator></a> to fully consume the stream.</li>
</ul>
<pre><code class="language-js">const fs = require('fs');

async function print(readable) {
  readable.setEncoding('utf8');
  let data = '';
  for await (const chunk of readable) {
    data += chunk;
  }
  console.log(data);
}

print(fs.createReadStream('file')).catch(console.error);
</code></pre>
<p>If the loop terminates with a <code>break</code> or a <code>throw</code>, the stream will be
destroyed. In other terms, iterating over a stream will consume the stream
fully. The stream will be read in chunks of size equal to the <code>highWaterMark</code>
option. In the code example above, data will be in a single chunk if the file
has less then 64KB of data because no <code>highWaterMark</code> option is provided to
<a href="#fs_fs_createreadstream_path_options"><code>fs.createReadStream()</code></a>.</p>
<h3>Duplex and transform streams<span><a class="mark" href="#stream_duplex_and_transform_streams" id="stream_duplex_and_transform_streams">#</a></span></h3>
<h4>Class: <code>stream.Duplex</code><span><a class="mark" href="#stream_class_stream_duplex" id="stream_class_stream_duplex">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.8.0</td>
<td><p>Instances of <code>Duplex</code> now return <code>true</code> when checking <code>instanceof stream.Writable</code>.</p></td></tr>
<tr><td>v0.9.4</td>
<td><p><span>Added in: v0.9.4</span></p></td></tr>
</tbody></table>
</details>
</div>

<p>Duplex streams are streams that implement both the <a href="#stream_class_stream_readable"><code>Readable</code></a> and
<a href="#stream_class_stream_writable"><code>Writable</code></a> interfaces.</p>
<p>Examples of <code>Duplex</code> streams include:</p>
<ul>
<li><a href="#net_class_net_socket">TCP sockets</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
</ul>
<h4>Class: <code>stream.Transform</code><span><a class="mark" href="#stream_class_stream_transform" id="stream_class_stream_transform">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>

<p>Transform streams are <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams where the output is in some way
related to the input. Like all <a href="#stream_class_stream_duplex"><code>Duplex</code></a> streams, <code>Transform</code> streams
implement both the <a href="#stream_class_stream_readable"><code>Readable</code></a> and <a href="#stream_class_stream_writable"><code>Writable</code></a> interfaces.</p>
<p>Examples of <code>Transform</code> streams include:</p>
<ul>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
</ul>
<h5><code>transform.destroy([error])</code><span><a class="mark" href="#stream_transform_destroy_error" id="stream_transform_destroy_error">#</a></span></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type">&#x3C;this></a></li>
</ul>
<p>Destroy the stream, and optionally emit an <code>'error'</code> event. 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>
unless <code>emitClose</code> is set in false.</p>
<h3><code>stream.finished(stream[, options], callback)</code><span><a class="mark" href="#stream_stream_finished_stream_options_callback" id="stream_stream_finished_stream_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#stream_stream" class="type">&#x3C;Stream></a> A readable and/or writable stream.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to <code>false</code>, then a call to <code>emit('error', err)</code> is
not treated as finished. <strong>Default</strong>: <code>true</code>.</li>
<li><code>readable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When set to <code>false</code>, the callback will be called when
the stream ends even though the stream might still be readable.
<strong>Default</strong>: <code>true</code>.</li>
<li><code>writable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When set to <code>false</code>, the callback will be called when
the stream ends even though the stream might still be writable.
<strong>Default</strong>: <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">&#x3C;Function></a> A callback function that takes an optional error
argument.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A cleanup function which removes all registered
listeners.</li>
</ul>
<p>A function to get notified when a stream is no longer readable, writable
or has experienced an error or a premature close event.</p>
<pre><code class="language-js">const { finished } = require('stream');

const rs = fs.createReadStream('archive.tar');

finished(rs, (err) => {
  if (err) {
    console.error('Stream failed.', err);
  } else {
    console.log('Stream is done reading.');
  }
});

rs.resume(); // Drain the stream.
</code></pre>
<p>Especially useful in error handling scenarios where a stream is destroyed
prematurely (like an aborted HTTP request), and will not emit <code>'end'</code>
or <code>'finish'</code>.</p>
<p>The <code>finished</code> API is promisify-able as well;</p>
<pre><code class="language-js">const finished = util.promisify(stream.finished);

const rs = fs.createReadStream('archive.tar');

async function run() {
  await finished(rs);
  console.log('Stream is done reading.');
}

run().catch(console.error);
rs.resume(); // Drain the stream.
</code></pre>
<p><code>stream.finished()</code> leaves dangling event listeners (in particular
<code>'error'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code>) after <code>callback</code> has been
invoked. The reason for this is so that unexpected <code>'error'</code> events (due to
incorrect stream implementations) do not cause unexpected crashes.
If this is unwanted behavior then the returned cleanup function needs to be
invoked in the callback:</p>
<pre><code class="language-js">const cleanup = finished(rs, (err) => {
  cleanup();
  // ...
});
</code></pre>
<h3><code>stream.pipeline(...streams, callback)</code><span><a class="mark" href="#stream_stream_pipeline_streams_callback" id="stream_stream_pipeline_streams_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>...streams</code> <a href="#stream_stream" class="type">&#x3C;Stream></a> Two or more streams to pipe between.</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called when the pipeline is fully done.</p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
</li>
</ul>
<p>A module method to pipe between streams forwarding errors and properly cleaning
up and provide a callback when the pipeline is complete.</p>
<pre><code class="language-js">const { pipeline } = require('stream');
const fs = require('fs');
const zlib = require('zlib');

// Use the pipeline API to easily pipe a series of streams
// together and get notified when the pipeline is fully done.

// A pipeline to gzip a potentially huge tar file efficiently:

pipeline(
  fs.createReadStream('archive.tar'),
  zlib.createGzip(),
  fs.createWriteStream('archive.tar.gz'),
  (err) => {
    if (err) {
      console.error('Pipeline failed.', err);
    } else {
      console.log('Pipeline succeeded.');
    }
  }
);
</code></pre>
<p>The <code>pipeline</code> API is promisify-able as well:</p>
<pre><code class="language-js">const pipeline = util.promisify(stream.pipeline);

async function run() {
  await pipeline(
    fs.createReadStream('archive.tar'),
    zlib.createGzip(),
    fs.createWriteStream('archive.tar.gz')
  );
  console.log('Pipeline succeeded.');
}

run().catch(console.error);
</code></pre>
<p><code>stream.pipeline()</code> will call <code>stream.destroy(err)</code> on all streams except:</p>
<ul>
<li><code>Readable</code> streams which have emitted <code>'end'</code> or <code>'close'</code>.</li>
<li><code>Writable</code> streams which have emitted <code>'finish'</code> or <code>'close'</code>.</li>
</ul>
<p><code>stream.pipeline()</code> leaves dangling event listeners on the streams
after the <code>callback</code> has been invoked. In the case of reuse of streams after
failure, this can cause event listener leaks and swallowed errors.</p>
<h3><code>stream.Readable.from(iterable, [options])</code><span><a class="mark" href="#stream_stream_readable_from_iterable_options" id="stream_stream_readable_from_iterable_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.3.0, v10.17.0</span>
</div>
<ul>
<li><code>iterable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> Object implementing the <code>Symbol.asyncIterator</code> or
<code>Symbol.iterator</code> iterable protocol. Emits an 'error' event if a null
value is passed.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Options provided to <code>new stream.Readable([options])</code>.
By default, <code>Readable.from()</code> will set <code>options.objectMode</code> to <code>true</code>, unless
this is explicitly opted out by setting <code>options.objectMode</code> to <code>false</code>.</li>
<li>Returns: <a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>A utility method for creating readable streams out of iterators.</p>
<pre><code class="language-js">const { Readable } = require('stream');

async function * generate() {
  yield 'hello';
  yield 'streams';
}

const readable = Readable.from(generate());

readable.on('data', (chunk) => {
  console.log(chunk);
});
</code></pre>
<p>Calling <code>Readable.from(string)</code> or <code>Readable.from(buffer)</code> will not have
the strings or buffers be iterated to match the other streams semantics
for performance reasons.</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>

<p>The <code>stream</code> module API has been designed to make it possible to easily
implement streams using JavaScript's prototypal inheritance model.</p>
<p>First, a stream developer would declare a new JavaScript class that extends one
of the four basic stream classes (<code>stream.Writable</code>, <code>stream.Readable</code>,
<code>stream.Duplex</code>, or <code>stream.Transform</code>), making sure they call the appropriate
parent class constructor:</p>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js">const { Writable } = require('stream');

class MyWritable extends Writable {
  constructor({ highWaterMark, ...options }) {
    super({
      highWaterMark,
      autoDestroy: true,
      emitClose: true
    });
    // ...
  }
}
</code></pre>
<p>When extending streams, keep in mind what options the user
can and should provide before forwarding these to the base constructor. For
example, if the implementation makes assumptions in regard to the
<code>autoDestroy</code> and <code>emitClose</code> options, do not allow the
user to override these. Be explicit about what
options are forwarded instead of implicitly forwarding all options.</p>
<p>The new stream class must then implement one or more specific methods, depending
on the type of stream being created, as detailed in the chart below:</p>






























<table><thead><tr><th>Use-case</th><th>Class</th><th>Method(s) to implement</th></tr></thead><tbody><tr><td>Reading only</td><td><a href="#stream_class_stream_readable"><code>Readable</code></a></td><td><a href="#stream_readable_read_size_1"><code>_read()</code></a></td></tr><tr><td>Writing only</td><td><a href="#stream_class_stream_writable"><code>Writable</code></a></td><td><a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write()</code></a>, <a href="#stream_writable_writev_chunks_callback"><code>_writev()</code></a>, <a href="#stream_writable_final_callback"><code>_final()</code></a></td></tr><tr><td>Reading and writing</td><td><a href="#stream_class_stream_duplex"><code>Duplex</code></a></td><td><a href="#stream_readable_read_size_1"><code>_read()</code></a>, <a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write()</code></a>, <a href="#stream_writable_writev_chunks_callback"><code>_writev()</code></a>, <a href="#stream_writable_final_callback"><code>_final()</code></a></td></tr><tr><td>Operate on written data, then read the result</td><td><a href="#stream_class_stream_transform"><code>Transform</code></a></td><td><a href="#stream_transform_transform_chunk_encoding_callback"><code>_transform()</code></a>, <a href="#stream_transform_flush_callback"><code>_flush()</code></a>, <a href="#stream_writable_final_callback"><code>_final()</code></a></td></tr></tbody></table>
<p>The implementation code for a stream should <em>never</em> call the "public" methods
of a stream that are intended for use by consumers (as described in the
<a href="#stream_api_for_stream_consumers">API for stream consumers</a> section). Doing so may lead to adverse side effects
in application code consuming the stream.</p>
<p>Avoid overriding public methods such as <code>write()</code>, <code>end()</code>, <code>cork()</code>,
<code>uncork()</code>, <code>read()</code> and <code>destroy()</code>, or emitting internal events such
as <code>'error'</code>, <code>'data'</code>, <code>'end'</code>, <code>'finish'</code> and <code>'close'</code> through <code>.emit()</code>.
Doing so can break current and future stream invariants leading to behavior
and/or compatibility issues with other streams, stream utilities, and user
expectations.</p>
<h3>Simplified construction<span><a class="mark" href="#stream_simplified_construction" id="stream_simplified_construction">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.2.0</span>
</div>
<p>For many simple cases, it is possible to construct a stream without relying on
inheritance. This can be accomplished by directly creating instances of the
<code>stream.Writable</code>, <code>stream.Readable</code>, <code>stream.Duplex</code> or <code>stream.Transform</code>
objects and passing appropriate methods as constructor options.</p>
<pre><code class="language-js">const { Writable } = require('stream');

const myWritable = new Writable({
  write(chunk, encoding, callback) {
    // ...
  }
});
</code></pre>
<h3>Implementing a writable stream<span><a class="mark" href="#stream_implementing_a_writable_stream" id="stream_implementing_a_writable_stream">#</a></span></h3>
<p>The <code>stream.Writable</code> class is extended to implement a <a href="#stream_class_stream_writable"><code>Writable</code></a> stream.</p>
<p>Custom <code>Writable</code> streams <em>must</em> call the <code>new stream.Writable([options])</code>
constructor and implement the <code>writable._write()</code> and/or <code>writable._writev()</code>
method.</p>
<h4>Constructor: <code>new stream.Writable([options])</code><span><a class="mark" href="#stream_constructor_new_stream_writable_options" id="stream_constructor_new_stream_writable_options">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.2.0</td>
<td><p>Add <code>autoDestroy</code> option to automatically <code>destroy()</code> the stream when it emits <code>'finish'</code> or errors.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Buffer level when
<a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> starts returning <code>false</code>. <strong>Default:</strong>
<code>16384</code> (16KB), or <code>16</code> for <code>objectMode</code> streams.</li>
<li><code>decodeStrings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether to encode <code>string</code>s passed to
<a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> to <code>Buffer</code>s (with the encoding
specified in the <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> call) before passing
them to <a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write()</code></a>. Other types of data are not
converted (i.e. <code>Buffer</code>s are not decoded into <code>string</code>s). Setting to
false will prevent <code>string</code>s from being converted. <strong>Default:</strong> <code>true</code>.</li>
<li><code>defaultEncoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The default encoding that is used when no
encoding is specified as an argument to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>.
<strong>Default:</strong> <code>'utf8'</code>.</li>
<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether or not the
<a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write(anyObj)</code></a> is a valid operation. When set,
it becomes possible to write JavaScript values other than string,
<code>Buffer</code> or <code>Uint8Array</code> if supported by the stream implementation.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>emitClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether or not the stream should emit <code>'close'</code>
after it has been destroyed. <strong>Default:</strong> <code>true</code>.</li>
<li><code>write</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;Function></a> Implementation for the
<a href="#stream_writable_final_callback"><code>stream._final()</code></a> method.</li>
<li><code>autoDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether this stream should automatically call
<code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js">const { Writable } = require('stream');

class MyWritable extends Writable {
  constructor(options) {
    // Calls the stream.Writable() constructor.
    super(options);
    // ...
  }
}
</code></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js">const { Writable } = require('stream');
const util = require('util');

function MyWritable(options) {
  if (!(this instanceof MyWritable))
    return new MyWritable(options);
  Writable.call(this, options);
}
util.inherits(MyWritable, Writable);
</code></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js">const { Writable } = require('stream');

const myWritable = new Writable({
  write(chunk, encoding, callback) {
    // ...
  },
  writev(chunks, callback) {
    // ...
  }
});
</code></pre>
<h4><code>writable._write(chunk, encoding, callback)</code><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="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.11.0</td>
<td><p>_write() is optional when providing _writev().</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The <code>Buffer</code> to be written, converted from the
<code>string</code> passed to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>. If the stream's
<code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode,
the chunk will not be converted &#x26; will be whatever was passed to
<a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;Function></a> Call this function (optionally with an error
argument) when processing is complete for the supplied chunk.</li>
</ul>
<p>All <code>Writable</code> stream implementations must provide a
<a href="#stream_writable_write_chunk_encoding_callback_1"><code>writable._write()</code></a> and/or
<a href="#stream_writable_writev_chunks_callback"><code>writable._writev()</code></a> method to send data to the underlying
resource.</p>
<p><a href="#stream_class_stream_transform"><code>Transform</code></a> streams provide their own implementation of the
<a href="#stream_writable_write_chunk_encoding_callback_1"><code>writable._write()</code></a>.</p>
<p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal <code>Writable</code> class
methods only.</p>
<p>The <code>callback</code> method must be called to signal either that the write completed
successfully or failed with an error. The first argument passed to the
<code>callback</code> must be the <code>Error</code> object if the call failed or <code>null</code> if the
write succeeded.</p>
<p>All calls to <code>writable.write()</code> that occur between the time <code>writable._write()</code>
is called and the <code>callback</code> is called will cause the written data to be
buffered. When the <code>callback</code> is invoked, the stream might emit a <a href="#stream_event_drain"><code>'drain'</code></a>
event. If a stream implementation is capable of processing multiple chunks of
data at once, the <code>writable._writev()</code> method should be implemented.</p>
<p>If the <code>decodeStrings</code> property is explicitly set to <code>false</code> in the constructor
options, then <code>chunk</code> will remain the same object that is passed to <code>.write()</code>,
and may be a string rather than a <code>Buffer</code>. This is to support implementations
that have an optimized handling for certain string data encodings. In that case,
the <code>encoding</code> argument will indicate the character encoding of the string.
Otherwise, the <code>encoding</code> argument can be safely ignored.</p>
<p>The <code>writable._write()</code> method is prefixed with an underscore because it is
internal to the class that defines it, and should never be called directly by
user programs.</p>
<h4><code>writable._writev(chunks, callback)</code><span><a class="mark" href="#stream_writable_writev_chunks_callback" id="stream_writable_writev_chunks_callback">#</a></span></h4>
<ul>
<li><code>chunks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> The chunks to be written. Each chunk has following
format: <code>{ chunk: ..., encoding: ... }</code>.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A callback function (optionally with an error
argument) to be invoked when processing is complete for the supplied chunks.</li>
</ul>
<p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal <code>Writable</code> class
methods only.</p>
<p>The <code>writable._writev()</code> method may be implemented in addition or alternatively
to <code>writable._write()</code> in stream implementations that are capable of processing
multiple chunks of data at once. If implemented and if there is buffered data
from previous writes, <code>_writev()</code> will be called instead of <code>_write()</code>.</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><code>writable._destroy(err, callback)</code><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">&#x3C;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">&#x3C;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><code>writable._final(callback)</code><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">&#x3C;Function></a> Call this function (optionally with an error
argument) when finished writing any remaining data.</li>
</ul>
<p>The <code>_final()</code> method <strong>must not</strong> be called directly. It may be implemented
by child classes, and if so, will be called by the internal <code>Writable</code>
class methods only.</p>
<p>This optional function will be called before the stream closes, delaying the
<code>'finish'</code> event until <code>callback</code> is called. This is useful to close resources
or write buffered data before a stream ends.</p>
<h4>Errors while writing<span><a class="mark" href="#stream_errors_while_writing" id="stream_errors_while_writing">#</a></span></h4>
<p>Errors occurring during the processing of the <a href="#stream_writable_write_chunk_encoding_callback_1"><code>writable._write()</code></a>,
<a href="#stream_writable_writev_chunks_callback"><code>writable._writev()</code></a> and <a href="#stream_writable_final_callback"><code>writable._final()</code></a> methods must be propagated
by invoking the callback and passing the error as the first argument.
Throwing an <code>Error</code> from within these methods or manually emitting an <code>'error'</code>
event results in undefined behavior.</p>
<p>If a <code>Readable</code> stream pipes into a <code>Writable</code> stream when <code>Writable</code> emits an
error, the <code>Readable</code> stream will be unpiped.</p>
<pre><code class="language-js">const { Writable } = require('stream');

const myWritable = new Writable({
  write(chunk, encoding, callback) {
    if (chunk.toString().indexOf('a') >= 0) {
      callback(new Error('chunk is invalid'));
    } else {
      callback();
    }
  }
});
</code></pre>
<h4>An example writable stream<span><a class="mark" href="#stream_an_example_writable_stream" id="stream_an_example_writable_stream">#</a></span></h4>
<p>The following illustrates a rather simplistic (and somewhat pointless) custom
<code>Writable</code> stream implementation. While this specific <code>Writable</code> stream instance
is not of any real particular usefulness, the example illustrates each of the
required elements of a custom <a href="#stream_class_stream_writable"><code>Writable</code></a> stream instance:</p>
<pre><code class="language-js">const { Writable } = require('stream');

class MyWritable extends Writable {
  _write(chunk, encoding, callback) {
    if (chunk.toString().indexOf('a') >= 0) {
      callback(new Error('chunk is invalid'));
    } else {
      callback();
    }
  }
}
</code></pre>
<h4>Decoding buffers in a writable stream<span><a class="mark" href="#stream_decoding_buffers_in_a_writable_stream" id="stream_decoding_buffers_in_a_writable_stream">#</a></span></h4>
<p>Decoding buffers is a common task, for instance, when using transformers whose
input is a string. This is not a trivial process when using multi-byte
characters encoding, such as UTF-8. The following example shows how to decode
multi-byte strings using <code>StringDecoder</code> and <a href="#stream_class_stream_writable"><code>Writable</code></a>.</p>
<pre><code class="language-js">const { Writable } = require('stream');
const { StringDecoder } = require('string_decoder');

class StringWritable extends Writable {
  constructor(options) {
    super(options);
    this._decoder = new StringDecoder(options &#x26;&#x26; options.defaultEncoding);
    this.data = '';
  }
  _write(chunk, encoding, callback) {
    if (encoding === 'buffer') {
      chunk = this._decoder.write(chunk);
    }
    this.data += chunk;
    callback();
  }
  _final(callback) {
    this.data += this._decoder.end();
    callback();
  }
}

const euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);
const w = new StringWritable();

w.write('currency: ');
w.write(euro[0]);
w.end(euro[1]);

console.log(w.data); // currency: €
</code></pre>
<h3>Implementing a readable stream<span><a class="mark" href="#stream_implementing_a_readable_stream" id="stream_implementing_a_readable_stream">#</a></span></h3>
<p>The <code>stream.Readable</code> class is extended to implement a <a href="#stream_class_stream_readable"><code>Readable</code></a> stream.</p>
<p>Custom <code>Readable</code> streams <em>must</em> call the <code>new stream.Readable([options])</code>
constructor and implement the <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> method.</p>
<h4><code>new stream.Readable([options])</code><span><a class="mark" href="#stream_new_stream_readable_options" id="stream_new_stream_readable_options">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.2.0</td>
<td><p>Add <code>autoDestroy</code> option to automatically <code>destroy()</code> the stream when it emits <code>'end'</code> or errors.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The maximum <a href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding">number of bytes</a> to store
in the internal buffer before ceasing to read from the underlying resource.
<strong>Default:</strong> <code>16384</code> (16KB), or <code>16</code> for <code>objectMode</code> streams.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If specified, then buffers will be decoded to
strings using the specified encoding. <strong>Default:</strong> <code>null</code>.</li>
<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether this stream should behave
as a stream of objects. Meaning that <a href="#stream_readable_read_size"><code>stream.read(n)</code></a> returns
a single value instead of a <code>Buffer</code> of size <code>n</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>emitClose</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether or not the stream should emit <code>'close'</code>
after it has been destroyed. <strong>Default:</strong> <code>true</code>.</li>
<li><code>read</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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">&#x3C;Function></a> Implementation for the
<a href="#stream_readable_destroy_err_callback"><code>stream._destroy()</code></a> method.</li>
<li><code>autoDestroy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether this stream should automatically call
<code>.destroy()</code> on itself after ending. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js">const { Readable } = require('stream');

class MyReadable extends Readable {
  constructor(options) {
    // Calls the stream.Readable(options) constructor.
    super(options);
    // ...
  }
}
</code></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js">const { Readable } = require('stream');
const util = require('util');

function MyReadable(options) {
  if (!(this instanceof MyReadable))
    return new MyReadable(options);
  Readable.call(this, options);
}
util.inherits(MyReadable, Readable);
</code></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js">const { Readable } = require('stream');

const myReadable = new Readable({
  read(size) {
    // ...
  }
});
</code></pre>
<h4><code>readable._read(size)</code><span><a class="mark" href="#stream_readable_read_size_1" id="stream_readable_read_size_1">#</a></span></h4>
<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">&#x3C;number></a> Number of bytes to read asynchronously</li>
</ul>
<p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal <code>Readable</code> class
methods only.</p>
<p>All <code>Readable</code> stream implementations must provide an implementation of the
<a href="#stream_readable_read_size_1"><code>readable._read()</code></a> method to fetch data from the underlying resource.</p>
<p>When <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> 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 <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> method has been called, it will not be called
again until more data is pushed through the <a href="#stream_readable_push_chunk_encoding"><code>readable.push()</code></a>
method. Empty data such as empty buffers and strings will not cause
<a href="#stream_readable_read_size_1"><code>readable._read()</code></a> to be 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 <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> 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><code>readable._destroy(err, callback)</code><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">&#x3C;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">&#x3C;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><code>readable.push(chunk[, encoding])</code><span><a class="mark" href="#stream_readable_push_chunk_encoding" id="stream_readable_push_chunk_encoding">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>Uint8Array</code> instance.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Chunk of data to push into the
read queue. For streams not operating in object mode, <code>chunk</code> must be a
string, <code>Buffer</code> or <code>Uint8Array</code>. For object mode streams, <code>chunk</code> may be
any JavaScript value.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Encoding of string chunks. Must be a valid
<code>Buffer</code> encoding, such as <code>'utf8'</code> or <code>'ascii'</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if additional chunks of data may continue to be
pushed; <code>false</code> otherwise.</li>
</ul>
<p>When <code>chunk</code> is a <code>Buffer</code>, <code>Uint8Array</code> or <code>string</code>, the <code>chunk</code> of data will
be added to the internal queue for users of the stream to consume.
Passing <code>chunk</code> as <code>null</code> signals the end of the stream (EOF), after which no
more data can be written.</p>
<p>When the <code>Readable</code> is operating in paused mode, the data added with
<code>readable.push()</code> can be read out by calling the
<a href="#stream_readable_read_size"><code>readable.read()</code></a> method when the <a href="#stream_event_readable"><code>'readable'</code></a> event is
emitted.</p>
<p>When the <code>Readable</code> is operating in flowing mode, the data added with
<code>readable.push()</code> will be delivered by emitting a <code>'data'</code> event.</p>
<p>The <code>readable.push()</code> method is designed to be as flexible as possible. For
example, when wrapping a lower-level source that provides some form of
pause/resume mechanism, and a data callback, the low-level source can be wrapped
by the custom <code>Readable</code> instance:</p>
<pre><code class="language-js">// `_source` is an object with readStop() and readStart() methods,
// and an `ondata` member that gets called when it has data, and
// an `onend` member that gets called when the data is over.

class SourceWrapper extends Readable {
  constructor(options) {
    super(options);

    this._source = getLowLevelSourceObject();

    // Every time there's data, push it into the internal buffer.
    this._source.ondata = (chunk) => {
      // If push() returns false, then stop reading from source.
      if (!this.push(chunk))
        this._source.readStop();
    };

    // When the source ends, push the EOF-signaling `null` chunk.
    this._source.onend = () => {
      this.push(null);
    };
  }
  // _read() will be called when the stream wants to pull more data in.
  // The advisory size argument is ignored in this case.
  _read(size) {
    this._source.readStart();
  }
}
</code></pre>
<p>The <code>readable.push()</code> method is used to push the content
into the internal buffer. It can be driven by the <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> 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>Errors occurring during processing of the <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> must be
propagated through the <a href="#stream_readable_destroy_err_callback"><code>readable.destroy(err)</code></a> method.
Throwing an <code>Error</code> from within <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> or manually emitting an
<code>'error'</code> event results in undefined behavior.</p>
<pre><code class="language-js">const { Readable } = require('stream');

const myReadable = new Readable({
  read(size) {
    const err = checkSomeErrorCondition();
    if (err) {
      this.destroy(err);
    } else {
      // Do some work.
    }
  }
});
</code></pre>
<h4>An example counting stream<span><a class="mark" href="#stream_an_example_counting_stream" id="stream_an_example_counting_stream">#</a></span></h4>

<p>The following is a basic example of a <code>Readable</code> stream that emits the numerals
from 1 to 1,000,000 in ascending order, and then ends.</p>
<pre><code class="language-js">const { Readable } = require('stream');

class Counter extends Readable {
  constructor(opt) {
    super(opt);
    this._max = 1000000;
    this._index = 1;
  }

  _read() {
    const i = this._index++;
    if (i > this._max)
      this.push(null);
    else {
      const str = String(i);
      const buf = Buffer.from(str, 'ascii');
      this.push(buf);
    }
  }
}
</code></pre>
<h3>Implementing a duplex stream<span><a class="mark" href="#stream_implementing_a_duplex_stream" id="stream_implementing_a_duplex_stream">#</a></span></h3>
<p>A <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream is one that implements both <a href="#stream_class_stream_readable"><code>Readable</code></a> and
<a href="#stream_class_stream_writable"><code>Writable</code></a>, such as a TCP socket connection.</p>
<p>Because JavaScript does not have support for multiple inheritance, the
<code>stream.Duplex</code> class is extended to implement a <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream (as opposed
to extending the <code>stream.Readable</code> <em>and</em> <code>stream.Writable</code> classes).</p>
<p>The <code>stream.Duplex</code> class prototypically inherits from <code>stream.Readable</code> and
parasitically from <code>stream.Writable</code>, but <code>instanceof</code> will work properly for
both base classes due to overriding <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance"><code>Symbol.hasInstance</code></a> on
<code>stream.Writable</code>.</p>
<p>Custom <code>Duplex</code> streams <em>must</em> call the <code>new stream.Duplex([options])</code>
constructor and implement <em>both</em> the <a href="#stream_readable_read_size_1"><code>readable._read()</code></a> and
<code>writable._write()</code> methods.</p>
<h4><code>new stream.Duplex(options)</code><span><a class="mark" href="#stream_new_stream_duplex_options" id="stream_new_stream_duplex_options">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.4.0</td>
<td><p>The <code>readableHighWaterMark</code> and <code>writableHighWaterMark</code> options are supported now.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Passed to both <code>Writable</code> and <code>Readable</code>
constructors. Also has the following fields:</p>
<ul>
<li><code>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to <code>false</code>, then the stream will
automatically end the writable side when the readable side ends.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>readableObjectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Sets <code>objectMode</code> for readable side of the
stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>writableObjectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Sets <code>objectMode</code> for writable side of the
stream. Has no effect if <code>objectMode</code> is <code>true</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>readableHighWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;number></a> Sets <code>highWaterMark</code> for the writable side
of the stream. Has no effect if <code>highWaterMark</code> is provided.</li>
</ul>
</li>
</ul>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js">const { Duplex } = require('stream');

class MyDuplex extends Duplex {
  constructor(options) {
    super(options);
    // ...
  }
}
</code></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js">const { Duplex } = require('stream');
const util = require('util');

function MyDuplex(options) {
  if (!(this instanceof MyDuplex))
    return new MyDuplex(options);
  Duplex.call(this, options);
}
util.inherits(MyDuplex, Duplex);
</code></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js">const { Duplex } = require('stream');

const myDuplex = new Duplex({
  read(size) {
    // ...
  },
  write(chunk, encoding, callback) {
    // ...
  }
});
</code></pre>
<h4>An example duplex stream<span><a class="mark" href="#stream_an_example_duplex_stream" id="stream_an_example_duplex_stream">#</a></span></h4>
<p>The following illustrates a simple example of a <code>Duplex</code> stream that wraps a
hypothetical lower-level source object to which data can be written, and
from which data can be read, albeit using an API that is not compatible with
Node.js streams.
The following illustrates a simple example of a <code>Duplex</code> stream that buffers
incoming written data via the <a href="#stream_class_stream_writable"><code>Writable</code></a> interface that is read back out
via the <a href="#stream_class_stream_readable"><code>Readable</code></a> interface.</p>
<pre><code class="language-js">const { Duplex } = require('stream');
const kSource = Symbol('source');

class MyDuplex extends Duplex {
  constructor(source, options) {
    super(options);
    this[kSource] = source;
  }

  _write(chunk, encoding, callback) {
    // The underlying source only deals with strings.
    if (Buffer.isBuffer(chunk))
      chunk = chunk.toString();
    this[kSource].writeSomeData(chunk);
    callback();
  }

  _read(size) {
    this[kSource].fetchSomeData(size, (data, encoding) => {
      this.push(Buffer.from(data, encoding));
    });
  }
}
</code></pre>
<p>The most important aspect of a <code>Duplex</code> stream is that the <code>Readable</code> and
<code>Writable</code> sides operate independently of one another despite co-existing within
a single object instance.</p>
<h4>Object mode duplex streams<span><a class="mark" href="#stream_object_mode_duplex_streams" id="stream_object_mode_duplex_streams">#</a></span></h4>
<p>For <code>Duplex</code> streams, <code>objectMode</code> can be set exclusively for either the
<code>Readable</code> or <code>Writable</code> side using the <code>readableObjectMode</code> and
<code>writableObjectMode</code> options respectively.</p>
<p>In the following example, for instance, a new <code>Transform</code> stream (which is a
type of <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream) is created that has an object mode <code>Writable</code> side
that accepts JavaScript numbers that are converted to hexadecimal strings on
the <code>Readable</code> side.</p>
<pre><code class="language-js">const { Transform } = require('stream');

// All Transform streams are also Duplex Streams.
const myTransform = new Transform({
  writableObjectMode: true,

  transform(chunk, encoding, callback) {
    // Coerce the chunk to a number if necessary.
    chunk |= 0;

    // Transform the chunk into something else.
    const data = chunk.toString(16);

    // Push the data onto the readable queue.
    callback(null, '0'.repeat(data.length % 2) + data);
  }
});

myTransform.setEncoding('ascii');
myTransform.on('data', (chunk) => console.log(chunk));

myTransform.write(1);
// Prints: 01
myTransform.write(10);
// Prints: 0a
myTransform.write(100);
// Prints: 64
</code></pre>
<h3>Implementing a transform stream<span><a class="mark" href="#stream_implementing_a_transform_stream" id="stream_implementing_a_transform_stream">#</a></span></h3>
<p>A <a href="#stream_class_stream_transform"><code>Transform</code></a> stream is a <a href="#stream_class_stream_duplex"><code>Duplex</code></a> stream where the output is computed
in some way from the input. Examples include <a href="zlib.html">zlib</a> streams or <a href="crypto.html">crypto</a>
streams that compress, encrypt, or decrypt data.</p>
<p>There is no requirement that the output be the same size as the input, the same
number of chunks, or arrive at the same time. For example, a <code>Hash</code> stream will
only ever have a single chunk of output which is provided when the input is
ended. A <code>zlib</code> stream will produce output that is either much smaller or much
larger than its input.</p>
<p>The <code>stream.Transform</code> class is extended to implement a <a href="#stream_class_stream_transform"><code>Transform</code></a> stream.</p>
<p>The <code>stream.Transform</code> class prototypically inherits from <code>stream.Duplex</code> and
implements its own versions of the <code>writable._write()</code> and
<a href="#stream_readable_read_size_1"><code>readable._read()</code></a> methods. Custom <code>Transform</code> implementations <em>must</em>
implement the <a href="#stream_transform_transform_chunk_encoding_callback"><code>transform._transform()</code></a> method and <em>may</em>
also implement the <a href="#stream_transform_flush_callback"><code>transform._flush()</code></a> method.</p>
<p>Care must be taken when using <code>Transform</code> streams in that data written to the
stream can cause the <code>Writable</code> side of the stream to become paused if the
output on the <code>Readable</code> side is not consumed.</p>
<h4><code>new stream.Transform([options])</code><span><a class="mark" href="#stream_new_stream_transform_options" id="stream_new_stream_transform_options">#</a></span></h4>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Passed to both <code>Writable</code> and <code>Readable</code>
constructors. Also has the following fields:</p>
<ul>
<li><code>transform</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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">&#x3C;Function></a> Implementation for the <a href="#stream_transform_flush_callback"><code>stream._flush()</code></a>
method.</li>
</ul>
</li>
</ul>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js">const { Transform } = require('stream');

class MyTransform extends Transform {
  constructor(options) {
    super(options);
    // ...
  }
}
</code></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js">const { Transform } = require('stream');
const util = require('util');

function MyTransform(options) {
  if (!(this instanceof MyTransform))
    return new MyTransform(options);
  Transform.call(this, options);
}
util.inherits(MyTransform, Transform);
</code></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js">const { Transform } = require('stream');

const myTransform = new Transform({
  transform(chunk, encoding, callback) {
    // ...
  }
});
</code></pre>
<h4>Events: <code>'finish'</code> and <code>'end'</code><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><code>transform._flush(callback)</code><span><a class="mark" href="#stream_transform_flush_callback" id="stream_transform_flush_callback">#</a></span></h4>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A callback function (optionally with an error
argument and data) to be called when remaining data has been flushed.</li>
</ul>
<p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal <code>Readable</code> class
methods only.</p>
<p>In some cases, a transform operation may need to emit an additional bit of
data at the end of the stream. For example, a <code>zlib</code> compression stream will
store an amount of internal state used to optimally compress the output. When
the stream ends, however, that additional data needs to be flushed so that the
compressed data will be complete.</p>
<p>Custom <a href="#stream_class_stream_transform"><code>Transform</code></a> implementations <em>may</em> implement the <code>transform._flush()</code>
method. This will be called when there is no more written data to be consumed,
but before the <a href="#stream_event_end"><code>'end'</code></a> event is emitted signaling the end of the
<a href="#stream_class_stream_readable"><code>Readable</code></a> stream.</p>
<p>Within the <code>transform._flush()</code> implementation, the <code>readable.push()</code> method
may be called zero or more times, as appropriate. The <code>callback</code> function must
be called when the flush operation is complete.</p>
<p>The <code>transform._flush()</code> method is prefixed with an underscore because it is
internal to the class that defines it, and should never be called directly by
user programs.</p>
<h4><code>transform._transform(chunk, encoding, callback)</code><span><a class="mark" href="#stream_transform_transform_chunk_encoding_callback" id="stream_transform_transform_chunk_encoding_callback">#</a></span></h4>
<ul>
<li><code>chunk</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The <code>Buffer</code> to be transformed, converted from
the <code>string</code> passed to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>. If the stream's
<code>decodeStrings</code> option is <code>false</code> or the stream is operating in object mode,
the chunk will not be converted &#x26; will be whatever was passed to
<a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a>.</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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 <code>'buffer'</code>. Ignore it in that case.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A callback function (optionally with an error
argument and data) to be called after the supplied <code>chunk</code> has been
processed.</li>
</ul>
<p>This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal <code>Readable</code> class
methods only.</p>
<p>All <code>Transform</code> stream implementations must provide a <code>_transform()</code>
method to accept input and produce output. The <code>transform._transform()</code>
implementation handles the bytes being written, computes an output, then passes
that output off to the readable portion using the <code>readable.push()</code> method.</p>
<p>The <code>transform.push()</code> method may be called zero or more times to generate
output from a single input chunk, depending on how much is to be output
as a result of the chunk.</p>
<p>It is possible that no output is generated from any given chunk of input data.</p>
<p>The <code>callback</code> function must be called only when the current chunk is completely
consumed. The first argument passed to the <code>callback</code> must be an <code>Error</code> object
if an error occurred while processing the input or <code>null</code> otherwise. If a second
argument is passed to the <code>callback</code>, it will be forwarded on to the
<code>readable.push()</code> method. In other words, the following are equivalent:</p>
<pre><code class="language-js">transform.prototype._transform = function(data, encoding, callback) {
  this.push(data);
  callback();
};

transform.prototype._transform = function(data, encoding, callback) {
  callback(null, data);
};
</code></pre>
<p>The <code>transform._transform()</code> method is prefixed with an underscore because it
is internal to the class that defines it, and should never be called directly by
user programs.</p>
<p><code>transform._transform()</code> is never called in parallel; streams implement a
queue mechanism, and to receive the next chunk, <code>callback</code> must be
called, either synchronously or asynchronously.</p>
<h4>Class: <code>stream.PassThrough</code><span><a class="mark" href="#stream_class_stream_passthrough" id="stream_class_stream_passthrough">#</a></span></h4>
<p>The <code>stream.PassThrough</code> class is a trivial implementation of a <a href="#stream_class_stream_transform"><code>Transform</code></a>
stream that simply passes the input bytes across to the output. Its purpose is
primarily for examples and testing, but there are some use cases where
<code>stream.PassThrough</code> is useful as a building block for novel sorts of streams.</p>
<h2>Additional notes<span><a class="mark" href="#stream_additional_notes" id="stream_additional_notes">#</a></span></h2>

<h3>Streams compatibility with async generators and async iterators<span><a class="mark" href="#stream_streams_compatibility_with_async_generators_and_async_iterators" id="stream_streams_compatibility_with_async_generators_and_async_iterators">#</a></span></h3>
<p>With the support of async generators and iterators in JavaScript, async
generators are effectively a first-class language-level stream construct at
this point.</p>
<p>Some common interop cases of using Node.js streams with async generators
and async iterators are provided below.</p>
<h4>Consuming readable streams with async iterators<span><a class="mark" href="#stream_consuming_readable_streams_with_async_iterators" id="stream_consuming_readable_streams_with_async_iterators">#</a></span></h4>
<pre><code class="language-js">(async function() {
  for await (const chunk of readable) {
    console.log(chunk);
  }
})();
</code></pre>
<p>Async iterators register a permanent error handler on the stream to prevent any
unhandled post-destroy errors.</p>
<h4>Creating readable streams with async generators<span><a class="mark" href="#stream_creating_readable_streams_with_async_generators" id="stream_creating_readable_streams_with_async_generators">#</a></span></h4>
<p>We can construct a Node.js readable stream from an asynchronous generator
using the <code>Readable.from()</code> utility method:</p>
<pre><code class="language-js">const { Readable } = require('stream');

async function * generate() {
  yield 'a';
  yield 'b';
  yield 'c';
}

const readable = Readable.from(generate());

readable.on('data', (chunk) => {
  console.log(chunk);
});
</code></pre>
<h4>Piping to writable streams from async iterators<span><a class="mark" href="#stream_piping_to_writable_streams_from_async_iterators" id="stream_piping_to_writable_streams_from_async_iterators">#</a></span></h4>
<p>In the scenario of writing to a writable stream from an async iterator, ensure
the correct handling of backpressure and errors.</p>
<pre><code class="language-js">const { once } = require('events');
const finished = util.promisify(stream.finished);

const writable = fs.createWriteStream('./file');

function drain(writable) {
  if (writable.destroyed) {
    return Promise.reject(new Error('premature close'));
  }
  return Promise.race([
    once(writable, 'drain'),
    once(writable, 'close')
      .then(() => Promise.reject(new Error('premature close')))
  ]);
}

async function pump(iterable, writable) {
  for await (const chunk of iterable) {
    // Handle backpressure on write().
    if (!writable.write(chunk)) {
      await drain(writable);
    }
  }
  writable.end();
}

(async function() {
  // Ensure completion without errors.
  await Promise.all([
    pump(iterable, writable),
    finished(writable)
  ]);
})();
</code></pre>
<p>In the above, errors on <code>write()</code> would be caught and thrown by the
<code>once()</code> listener for the <code>'drain'</code> event, since <code>once()</code> will also handle the
<code>'error'</code> event. To ensure completion of the write stream without errors,
it is safer to use the <code>finished()</code> method as above, instead of using the
<code>once()</code> listener for the <code>'finish'</code> event. Under certain cases, an <code>'error'</code>
event could be emitted by the writable stream after <code>'finish'</code> and as <code>once()</code>
will release the <code>'error'</code> handler on handling the <code>'finish'</code> event, it could
result in an unhandled error.</p>
<p>Alternatively, the readable stream could be wrapped with <code>Readable.from()</code> and
then piped via <code>.pipe()</code>:</p>
<pre><code class="language-js">const finished = util.promisify(stream.finished);

const writable = fs.createWriteStream('./file');

(async function() {
  const readable = Readable.from(iterable);
  readable.pipe(writable);
  // Ensure completion without errors.
  await finished(writable);
})();
</code></pre>
<p>Or, using <code>stream.pipeline()</code> to pipe streams:</p>
<pre><code class="language-js">const pipeline = util.promisify(stream.pipeline);

const writable = fs.createWriteStream('./file');

(async function() {
  const readable = Readable.from(iterable);
  await pipeline(readable, writable);
})();
</code></pre>

<h3>Compatibility with older Node.js versions<span><a class="mark" href="#stream_compatibility_with_older_node_js_versions" id="stream_compatibility_with_older_node_js_versions">#</a></span></h3>

<p>Prior to Node.js 0.10, the <code>Readable</code> stream interface was simpler, but also
less powerful and less useful.</p>
<ul>
<li>Rather than waiting for calls to the <a href="#stream_readable_read_size"><code>stream.read()</code></a> method,
<a href="#stream_event_data"><code>'data'</code></a> events would begin emitting immediately. Applications that
would need to perform some amount of work to decide how to handle data
were required to store read data into buffers so the data would not be lost.</li>
<li>The <a href="#stream_readable_pause"><code>stream.pause()</code></a> method was advisory, rather than
guaranteed. This meant that it was still necessary to be prepared to receive
<a href="#stream_event_data"><code>'data'</code></a> events <em>even when the stream was in a paused state</em>.</li>
</ul>
<p>In Node.js 0.10, the <a href="#stream_class_stream_readable"><code>Readable</code></a> class was added. For backward
compatibility with older Node.js programs, <code>Readable</code> streams switch into
"flowing mode" when a <a href="#stream_event_data"><code>'data'</code></a> event handler is added, or when the
<a href="#stream_readable_resume"><code>stream.resume()</code></a> method is called. The effect is that, even
when not using the new <a href="#stream_readable_read_size"><code>stream.read()</code></a> method and
<a href="#stream_event_readable"><code>'readable'</code></a> event, it is no longer necessary to worry about losing
<a href="#stream_event_data"><code>'data'</code></a> chunks.</p>
<p>While most applications will continue to function normally, this introduces an
edge case in the following conditions:</p>
<ul>
<li>No <a href="#stream_event_data"><code>'data'</code></a> event listener is added.</li>
<li>The <a href="#stream_readable_resume"><code>stream.resume()</code></a> method is never called.</li>
<li>The stream is not piped to any writable destination.</li>
</ul>
<p>For example, consider the following code:</p>
<pre><code class="language-js">// WARNING!  BROKEN!
net.createServer((socket) => {

  // We add an 'end' listener, but never consume the data.
  socket.on('end', () => {
    // It will never get here.
    socket.end('The message was received but was not processed.\n');
  });

}).listen(1337);
</code></pre>
<p>Prior to Node.js 0.10, the incoming message data would be simply discarded.
However, in Node.js 0.10 and beyond, the socket remains paused forever.</p>
<p>The workaround in this situation is to call the
<a href="#stream_readable_resume"><code>stream.resume()</code></a> method to begin the flow of data:</p>
<pre><code class="language-js">// Workaround.
net.createServer((socket) => {
  socket.on('end', () => {
    socket.end('The message was received but was not processed.\n');
  });

  // Start the flow of data, discarding it.
  socket.resume();
}).listen(1337);
</code></pre>
<p>In addition to new <code>Readable</code> streams switching into flowing mode,
pre-0.10 style streams can be wrapped in a <code>Readable</code> class using the
<a href="#stream_readable_wrap_stream"><code>readable.wrap()</code></a> method.</p>
<h3><code>readable.read(0)</code><span><a class="mark" href="#stream_readable_read_0" id="stream_readable_read_0">#</a></span></h3>
<p>There are some cases where it is necessary to trigger a refresh of the
underlying readable stream mechanisms, without actually consuming any
data. In such cases, it is possible to call <code>readable.read(0)</code>, which will
always return <code>null</code>.</p>
<p>If the internal read buffer is below the <code>highWaterMark</code>, and the
stream is not currently reading, then calling <code>stream.read(0)</code> will trigger
a low-level <a href="#stream_readable_read_size_1"><code>stream._read()</code></a> call.</p>
<p>While most applications will almost never need to do this, there are
situations within Node.js where this is done, particularly in the
<code>Readable</code> stream class internals.</p>
<h3><code>readable.push('')</code><span><a class="mark" href="#stream_readable_push" id="stream_readable_push">#</a></span></h3>
<p>Use of <code>readable.push('')</code> is not recommended.</p>
<p>Pushing a zero-byte string, <code>Buffer</code> or <code>Uint8Array</code> to a stream that is not in
object mode has an interesting side effect. Because it <em>is</em> a call to
<a href="#stream_readable_push_chunk_encoding"><code>readable.push()</code></a>, the call will end the reading process.
However, because the argument is an empty string, no data is added to the
readable buffer so there is nothing for a user to consume.</p>
<h3><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code><span><a class="mark" href="#stream_highwatermark_discrepancy_after_calling_readable_setencoding" id="stream_highwatermark_discrepancy_after_calling_readable_setencoding">#</a></span></h3>
<p>The use of <code>readable.setEncoding()</code> will change the behavior of how the
<code>highWaterMark</code> operates in non-object mode.</p>
<p>Typically, the size of the current buffer is measured against the
<code>highWaterMark</code> in <em>bytes</em>. However, after <code>setEncoding()</code> is called, the
comparison function will begin to measure the buffer's size in <em>characters</em>.</p>
<p>This is not a problem in common cases with <code>latin1</code> or <code>ascii</code>. But it is
advised to be mindful about this behavior when working with strings that could
contain multi-byte characters.</p>
<h1>String decoder<span><a class="mark" href="#string_decoder_string_decoder" id="string_decoder_string_decoder">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>string_decoder</code> module provides an API for decoding <code>Buffer</code> objects into
strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16
characters. It can be accessed using:</p>
<pre><code class="language-js">const { StringDecoder } = require('string_decoder');
</code></pre>
<p>The following example shows the basic use of the <code>StringDecoder</code> class.</p>
<pre><code class="language-js">const { StringDecoder } = require('string_decoder');
const decoder = new StringDecoder('utf8');

const cent = Buffer.from([0xC2, 0xA2]);
console.log(decoder.write(cent));

const euro = Buffer.from([0xE2, 0x82, 0xAC]);
console.log(decoder.write(euro));
</code></pre>
<p>When a <code>Buffer</code> instance is written to the <code>StringDecoder</code> instance, an
internal buffer is used to ensure that the decoded string does not contain
any incomplete multibyte characters. These are held in the buffer until the
next call to <code>stringDecoder.write()</code> or until <code>stringDecoder.end()</code> is called.</p>
<p>In the following example, the three UTF-8 encoded bytes of the European Euro
symbol (<code>€</code>) are written over three separate operations:</p>
<pre><code class="language-js">const { StringDecoder } = require('string_decoder');
const decoder = new StringDecoder('utf8');

decoder.write(Buffer.from([0xE2]));
decoder.write(Buffer.from([0x82]));
console.log(decoder.end(Buffer.from([0xAC])));
</code></pre>
<h2>Class: <code>StringDecoder</code><span><a class="mark" href="#string_decoder_class_stringdecoder" id="string_decoder_class_stringdecoder">#</a></span></h2>
<h3><code>new StringDecoder([encoding])</code><span><a class="mark" href="#string_decoder_new_stringdecoder_encoding" id="string_decoder_new_stringdecoder_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The character <a href="#buffer_buffers_and_character_encodings">encoding</a> the <code>StringDecoder</code> will use.
<strong>Default:</strong> <code>'utf8'</code>.</li>
</ul>
<p>Creates a new <code>StringDecoder</code> instance.</p>
<h3><code>stringDecoder.end([buffer])</code><span><a class="mark" href="#string_decoder_stringdecoder_end_buffer" id="string_decoder_stringdecoder_end_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> A <code>Buffer</code>, or <code>TypedArray</code>, or
<code>DataView</code> containing the bytes to decode.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns any remaining input stored in the internal buffer as a string. Bytes
representing incomplete UTF-8 and UTF-16 characters will be replaced with
substitution characters appropriate for the character encoding.</p>
<p>If the <code>buffer</code> argument is provided, one final call to <code>stringDecoder.write()</code>
is performed before returning the remaining input.</p>
<h3><code>stringDecoder.write(buffer)</code><span><a class="mark" href="#string_decoder_stringdecoder_write_buffer" id="string_decoder_stringdecoder_write_buffer">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>Each invalid character is now replaced by a single replacement character instead of one for each individual byte.</p></td></tr>
<tr><td>v0.1.99</td>
<td><p><span>Added in: v0.1.99</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> A <code>Buffer</code>, or <code>TypedArray</code>, or
<code>DataView</code> containing the bytes to decode.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns a decoded string, ensuring that any incomplete multibyte characters at
the end of the <code>Buffer</code>, or <code>TypedArray</code>, or <code>DataView</code> are omitted from the
returned string and stored in an internal buffer for the next call to
<code>stringDecoder.write()</code> or <code>stringDecoder.end()</code>.</p>
<h1>Timers<span><a class="mark" href="#timers_timers" id="timers_timers">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>timer</code> module exposes a global API for scheduling functions to
be called at some future period of time. Because the timer functions are
globals, there is no need to call <code>require('timers')</code> to use the API.</p>
<p>The timer functions within Node.js implement a similar API as the timers API
provided by Web Browsers but use a different internal implementation that is
built around the Node.js <a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout">Event Loop</a>.</p>
<h2>Class: <code>Immediate</code><span><a class="mark" href="#timers_class_immediate" id="timers_class_immediate">#</a></span></h2>
<p>This object is created internally and is returned from <a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a>. It
can be passed to <a href="#timers_clearimmediate_immediate"><code>clearImmediate()</code></a> in order to cancel the scheduled
actions.</p>
<p>By default, when an immediate is scheduled, the Node.js event loop will continue
running as long as the immediate is active. The <code>Immediate</code> object returned by
<a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a> exports both <code>immediate.ref()</code> and <code>immediate.unref()</code>
functions that can be used to control this default behavior.</p>
<h3><code>immediate.hasRef()</code><span><a class="mark" href="#timers_immediate_hasref" id="timers_immediate_hasref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>If true, the <code>Immediate</code> object will keep the Node.js event loop active.</p>
<h3><code>immediate.ref()</code><span><a class="mark" href="#timers_immediate_ref" id="timers_immediate_ref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.7.0</span>
</div>
<ul>
<li>Returns: <a href="#timers_class_immediate" class="type">&#x3C;Immediate></a> a reference to <code>immediate</code></li>
</ul>
<p>When called, requests that the Node.js event loop <em>not</em> exit so long as the
<code>Immediate</code> is active. Calling <code>immediate.ref()</code> multiple times will have no
effect.</p>
<p>By default, all <code>Immediate</code> objects are "ref'ed", making it normally unnecessary
to call <code>immediate.ref()</code> unless <code>immediate.unref()</code> had been called previously.</p>
<h3><code>immediate.unref()</code><span><a class="mark" href="#timers_immediate_unref" id="timers_immediate_unref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.7.0</span>
</div>
<ul>
<li>Returns: <a href="#timers_class_immediate" class="type">&#x3C;Immediate></a> a reference to <code>immediate</code></li>
</ul>
<p>When called, the active <code>Immediate</code> object will not require the Node.js event
loop to remain active. If there is no other activity keeping the event loop
running, the process may exit before the <code>Immediate</code> object's callback is
invoked. Calling <code>immediate.unref()</code> multiple times will have no effect.</p>
<h2>Class: <code>Timeout</code><span><a class="mark" href="#timers_class_timeout" id="timers_class_timeout">#</a></span></h2>
<p>This object is created internally and is returned from <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a> and
<a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>. It can be passed to either <a href="#timers_cleartimeout_timeout"><code>clearTimeout()</code></a> or
<a href="#timers_clearinterval_timeout"><code>clearInterval()</code></a> in order to cancel the scheduled actions.</p>
<p>By default, when a timer is scheduled using either <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a> or
<a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>, the Node.js event loop will continue running as long as the
timer is active. Each of the <code>Timeout</code> objects returned by these functions
export both <code>timeout.ref()</code> and <code>timeout.unref()</code> functions that can be used to
control this default behavior.</p>
<h3><code>timeout.hasRef()</code><span><a class="mark" href="#timers_timeout_hasref" id="timers_timeout_hasref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>If true, the <code>Timeout</code> object will keep the Node.js event loop active.</p>
<h3><code>timeout.ref()</code><span><a class="mark" href="#timers_timeout_ref" id="timers_timeout_ref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#timers_class_timeout" class="type">&#x3C;Timeout></a> a reference to <code>timeout</code></li>
</ul>
<p>When called, requests that the Node.js event loop <em>not</em> exit so long as the
<code>Timeout</code> is active. Calling <code>timeout.ref()</code> multiple times will have no effect.</p>
<p>By default, all <code>Timeout</code> objects are "ref'ed", making it normally unnecessary
to call <code>timeout.ref()</code> unless <code>timeout.unref()</code> had been called previously.</p>
<h3><code>timeout.refresh()</code><span><a class="mark" href="#timers_timeout_refresh" id="timers_timeout_refresh">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.2.0</span>
</div>
<ul>
<li>Returns: <a href="#timers_class_timeout" class="type">&#x3C;Timeout></a> a reference to <code>timeout</code></li>
</ul>
<p>Sets the timer's start time to the current time, and reschedules the timer to
call its callback at the previously specified duration adjusted to the current
time. This is useful for refreshing a timer without allocating a new
JavaScript object.</p>
<p>Using this on a timer that has already called its callback will reactivate the
timer.</p>
<h3><code>timeout.unref()</code><span><a class="mark" href="#timers_timeout_unref" id="timers_timeout_unref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#timers_class_timeout" class="type">&#x3C;Timeout></a> a reference to <code>timeout</code></li>
</ul>
<p>When called, the active <code>Timeout</code> object will not require the Node.js event loop
to remain active. If there is no other activity keeping the event loop running,
the process may exit before the <code>Timeout</code> object's callback is invoked. Calling
<code>timeout.unref()</code> multiple times will have no effect.</p>
<p>Calling <code>timeout.unref()</code> creates an internal timer that will wake the Node.js
event loop. Creating too many of these can adversely impact performance
of the Node.js application.</p>
<h2>Scheduling timers<span><a class="mark" href="#timers_scheduling_timers" id="timers_scheduling_timers">#</a></span></h2>
<p>A timer in Node.js is an internal construct that calls a given function after
a certain period of time. When a timer's function is called varies depending on
which method was used to create the timer and what other work the Node.js
event loop is doing.</p>
<h3><code>setImmediate(callback[, ...args])</code><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">&#x3C;Function></a> The function to call at the end of this turn of
the Node.js <a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout">Event Loop</a></li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Optional arguments to pass when the <code>callback</code> is called.</li>
<li>Returns: <a href="#timers_class_immediate" class="type">&#x3C;Immediate></a> for use with <a href="#timers_clearimmediate_immediate"><code>clearImmediate()</code></a></li>
</ul>
<p>Schedules the "immediate" execution of the <code>callback</code> after I/O events'
callbacks.</p>
<p>When multiple calls to <code>setImmediate()</code> are made, the <code>callback</code> functions are
queued for execution in the order in which they are created. The entire callback
queue is processed every event loop iteration. If an immediate timer is queued
from inside an executing callback, that timer will not be triggered until the
next event loop iteration.</p>
<p>If <code>callback</code> is not a function, a <a href="#errors_class_typeerror"><code>TypeError</code></a> will be thrown.</p>
<p>This method has a custom variant for promises that is available using
<a href="#util_util_promisify_original"><code>util.promisify()</code></a>:</p>
<pre><code class="language-js">const util = require('util');
const setImmediatePromise = util.promisify(setImmediate);

setImmediatePromise('foobar').then((value) => {
  // value === 'foobar' (passing values is optional)
  // This is executed after all I/O callbacks.
});

// Or with async function
async function timerExample() {
  console.log('Before I/O callbacks');
  await setImmediatePromise();
  console.log('After I/O callbacks');
}
timerExample();
</code></pre>
<h3><code>setInterval(callback, delay[, ...args])</code><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">&#x3C;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">&#x3C;number></a> The number of milliseconds to wait before calling the
<code>callback</code>.</li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Optional arguments to pass when the <code>callback</code> is called.</li>
<li>Returns: <a href="#timers_class_timeout" class="type">&#x3C;Timeout></a> for use with <a href="#timers_clearinterval_timeout"><code>clearInterval()</code></a></li>
</ul>
<p>Schedules repeated execution of <code>callback</code> every <code>delay</code> milliseconds.</p>
<p>When <code>delay</code> is larger than <code>2147483647</code> or less than <code>1</code>, the <code>delay</code> will be
set to <code>1</code>. Non-integer delays are truncated to an integer.</p>
<p>If <code>callback</code> is not a function, a <a href="#errors_class_typeerror"><code>TypeError</code></a> will be thrown.</p>
<h3><code>setTimeout(callback, delay[, ...args])</code><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">&#x3C;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">&#x3C;number></a> The number of milliseconds to wait before calling the
<code>callback</code>.</li>
<li><code>...args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Optional arguments to pass when the <code>callback</code> is called.</li>
<li>Returns: <a href="#timers_class_timeout" class="type">&#x3C;Timeout></a> for use with <a href="#timers_cleartimeout_timeout"><code>clearTimeout()</code></a></li>
</ul>
<p>Schedules execution of a one-time <code>callback</code> after <code>delay</code> milliseconds.</p>
<p>The <code>callback</code> will likely not be invoked in precisely <code>delay</code> milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.</p>
<p>When <code>delay</code> is larger than <code>2147483647</code> or less than <code>1</code>, the <code>delay</code>
will be set to <code>1</code>. Non-integer delays are truncated to an integer.</p>
<p>If <code>callback</code> is not a function, a <a href="#errors_class_typeerror"><code>TypeError</code></a> will be thrown.</p>
<p>This method has a custom variant for promises that is available using
<a href="#util_util_promisify_original"><code>util.promisify()</code></a>:</p>
<pre><code class="language-js">const util = require('util');
const setTimeoutPromise = util.promisify(setTimeout);

setTimeoutPromise(40, 'foobar').then((value) => {
  // value === 'foobar' (passing values is optional)
  // This is executed after about 40 milliseconds.
});
</code></pre>
<h2>Cancelling timers<span><a class="mark" href="#timers_cancelling_timers" id="timers_cancelling_timers">#</a></span></h2>
<p>The <a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a>, <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>, and <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a> methods
each return objects that represent the scheduled timers. These can be used to
cancel the timer and prevent it from triggering.</p>
<p>It is not possible to cancel timers that were created using the promisified
variants of <a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a>, <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a>.</p>
<h3><code>clearImmediate(immediate)</code><span><a class="mark" href="#timers_clearimmediate_immediate" id="timers_clearimmediate_immediate">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li><code>immediate</code> <a href="#timers_class_immediate" class="type">&#x3C;Immediate></a> An <code>Immediate</code> object as returned by
<a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a>.</li>
</ul>
<p>Cancels an <code>Immediate</code> object created by <a href="#timers_setimmediate_callback_args"><code>setImmediate()</code></a>.</p>
<h3><code>clearInterval(timeout)</code><span><a class="mark" href="#timers_clearinterval_timeout" id="timers_clearinterval_timeout">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>
<ul>
<li><code>timeout</code> <a href="#timers_class_timeout" class="type">&#x3C;Timeout></a> A <code>Timeout</code> object as returned by <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>.</li>
</ul>
<p>Cancels a <code>Timeout</code> object created by <a href="#timers_setinterval_callback_delay_args"><code>setInterval()</code></a>.</p>
<h3><code>clearTimeout(timeout)</code><span><a class="mark" href="#timers_cleartimeout_timeout" id="timers_cleartimeout_timeout">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>
<ul>
<li><code>timeout</code> <a href="#timers_class_timeout" class="type">&#x3C;Timeout></a> A <code>Timeout</code> object as returned by <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a>.</li>
</ul>
<p>Cancels a <code>Timeout</code> object created by <a href="#timers_settimeout_callback_delay_args"><code>setTimeout()</code></a>.</p>
<h1>TLS (SSL)<span><a class="mark" href="#tls_tls_ssl" id="tls_tls_ssl">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>tls</code> module provides an implementation of the Transport Layer Security
(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.
The module can be accessed using:</p>
<pre><code class="language-js">const tls = require('tls');
</code></pre>
<h2>TLS/SSL concepts<span><a class="mark" href="#tls_tls_ssl_concepts" id="tls_tls_ssl_concepts">#</a></span></h2>
<p>The TLS/SSL is a public/private key infrastructure (PKI). For most common
cases, each client and server must have a <em>private key</em>.</p>
<p>Private keys can be generated in multiple ways. The example below illustrates
use of the OpenSSL command-line interface to generate a 2048-bit RSA private
key:</p>
<pre><code class="language-bash">openssl genrsa -out ryans-key.pem 2048
</code></pre>
<p>With TLS/SSL, all servers (and some clients) must have a <em>certificate</em>.
Certificates are <em>public keys</em> that correspond to a private key, and that are
digitally signed either by a Certificate Authority or by the owner of the
private key (such certificates are referred to as "self-signed"). The first
step to obtaining a certificate is to create a <em>Certificate Signing Request</em>
(CSR) file.</p>
<p>The OpenSSL command-line interface can be used to generate a CSR for a private
key:</p>
<pre><code class="language-bash">openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem
</code></pre>
<p>Once the CSR file is generated, it can either be sent to a Certificate
Authority for signing or used to generate a self-signed certificate.</p>
<p>Creating a self-signed certificate using the OpenSSL command-line interface
is illustrated in the example below:</p>
<pre><code class="language-bash">openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
</code></pre>
<p>Once the certificate is generated, it can be used to generate a <code>.pfx</code> or
<code>.p12</code> file:</p>
<pre><code class="language-bash">openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \
      -certfile ca-cert.pem -out ryans.pfx
</code></pre>
<p>Where:</p>
<ul>
<li><code>in</code>: is the signed certificate</li>
<li><code>inkey</code>: is the associated private key</li>
<li><code>certfile</code>: is a concatenation of all Certificate Authority (CA) certs into
a single file, e.g. <code>cat ca1-cert.pem ca2-cert.pem > ca-cert.pem</code></li>
</ul>
<h3>Perfect forward secrecy<span><a class="mark" href="#tls_perfect_forward_secrecy" id="tls_perfect_forward_secrecy">#</a></span></h3>

<p>The term <em><a href="https://en.wikipedia.org/wiki/Perfect_forward_secrecy">forward secrecy</a></em> or <em>perfect forward secrecy</em> describes a feature
of key-agreement (i.e., key-exchange) methods. That is, the server and client
keys are used to negotiate new temporary keys that are used specifically and
only for the current communication session. Practically, this means that even
if the server's private key is compromised, communication can only be decrypted
by eavesdroppers if the attacker manages to obtain the key-pair specifically
generated for the session.</p>
<p>Perfect forward secrecy is achieved by randomly generating a key pair for
key-agreement on every TLS/SSL handshake (in contrast to using the same key for
all sessions). Methods implementing this technique are called "ephemeral".</p>
<p>Currently two methods are commonly used to achieve perfect forward secrecy (note
the character "E" appended to the traditional abbreviations):</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange">DHE</a>: An ephemeral version of the Diffie Hellman key-agreement protocol.</li>
<li><a href="https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman">ECDHE</a>: An ephemeral version of the Elliptic Curve Diffie Hellman
key-agreement protocol.</li>
</ul>
<p>Ephemeral methods may have some performance drawbacks, because key generation
is expensive.</p>
<p>To use perfect forward secrecy using <code>DHE</code> with the <code>tls</code> module, it is required
to generate Diffie-Hellman parameters and specify them with the <code>dhparam</code>
option to <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>. The following illustrates the use of
the OpenSSL command-line interface to generate such parameters:</p>
<pre><code class="language-bash">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>
<p>Perfect forward secrecy was optional up to TLSv1.2, but it is not optional for
TLSv1.3, because all TLSv1.3 cipher suites use ECDHE.</p>
<h3>ALPN and SNI<span><a class="mark" href="#tls_alpn_and_sni" id="tls_alpn_and_sni">#</a></span></h3>

<p>ALPN (Application-Layer Protocol Negotiation Extension) and
SNI (Server Name Indication) are TLS handshake extensions:</p>
<ul>
<li>ALPN: Allows the use of one TLS server for multiple protocols (HTTP, HTTP/2)</li>
<li>SNI: Allows the use of one TLS server for multiple hostnames with different
SSL certificates.</li>
</ul>
<h3>Pre-shared keys<span><a class="mark" href="#tls_pre_shared_keys" id="tls_pre_shared_keys">#</a></span></h3>

<p>TLS-PSK support is available as an alternative to normal certificate-based
authentication. It uses a pre-shared key instead of certificates to
authenticate a TLS connection, providing mutual authentication.
TLS-PSK and public key infrastructure are not mutually exclusive. Clients and
servers can accommodate both, choosing either of them during the normal cipher
negotiation step.</p>
<p>TLS-PSK is only a good choice where means exist to securely share a
key with every connecting machine, so it does not replace PKI
(Public Key Infrastructure) for the majority of TLS uses.
The TLS-PSK implementation in OpenSSL has seen many security flaws in
recent years, mostly because it is used only by a minority of applications.
Please consider all alternative solutions before switching to PSK ciphers.
Upon generating PSK it is of critical importance to use sufficient entropy as
discussed in <a href="https://tools.ietf.org/html/rfc4086">RFC 4086</a>. Deriving a shared secret from a password or other
low-entropy sources is not secure.</p>
<p>PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly
specifying a cipher suite with the <code>ciphers</code> option. The list of available
ciphers can be retrieved via <code>openssl ciphers -v 'PSK'</code>. All TLS 1.3
ciphers are eligible for PSK but currently only those that use SHA256 digest are
supported they can be retrieved via <code>openssl ciphers -v -s -tls1_3 -psk</code>.</p>
<p>According to the <a href="https://tools.ietf.org/html/rfc4279">RFC 4279</a>, PSK identities up to 128 bytes in length and
PSKs up to 64 bytes in length must be supported. As of OpenSSL 1.1.0
maximum identity size is 128 bytes, and maximum PSK length is 256 bytes.</p>
<p>The current implementation doesn't support asynchronous PSK callbacks due to the
limitations of the underlying OpenSSL API.</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>

<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">&#x3C;number></a> Specifies the number of renegotiation
requests. <strong>Default:</strong> <code>3</code>.</li>
<li><code>tls.CLIENT_RENEG_WINDOW</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the time renegotiation window
in seconds. <strong>Default:</strong> <code>600</code> (10 minutes).</li>
</ul>
<p>The default renegotiation limits should not be modified without a full
understanding of the implications and risks.</p>
<p>TLSv1.3 does not support renegotiation.</p>
<h3>Session resumption<span><a class="mark" href="#tls_session_resumption" id="tls_session_resumption">#</a></span></h3>
<p>Establishing a TLS session can be relatively slow. The process can be sped
up by saving and later reusing the session state. There are several mechanisms
to do so, discussed here from oldest to newest (and preferred).</p>
<h4>Session identifiers<span><a class="mark" href="#tls_session_identifiers" id="tls_session_identifiers">#</a></span></h4>
<p>Servers generate a unique ID for new connections and
send it to the client. Clients and servers save the session state. When
reconnecting, clients send the ID of their saved session state and if the server
also has the state for that ID, it can agree to use it. Otherwise, the server
will create a new session. See <a href="https://www.ietf.org/rfc/rfc2246.txt">RFC 2246</a> for more information, page 23 and
30.</p>
<p>Resumption using session identifiers is supported by most web browsers when
making HTTPS requests.</p>
<p>For Node.js, clients wait for the <a href="#tls_event_session"><code>'session'</code></a> event to get the session data,
and provide the data to the <code>session</code> option of a subsequent <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>
to reuse the session. Servers must
implement handlers for the <a href="#tls_event_newsession"><code>'newSession'</code></a> and <a href="#tls_event_resumesession"><code>'resumeSession'</code></a> events
to save and restore the session data using the session ID as the lookup key to
reuse sessions. To reuse sessions across load balancers or cluster workers,
servers must use a shared session cache (such as Redis) in their session
handlers.</p>
<h4>Session tickets<span><a class="mark" href="#tls_session_tickets" id="tls_session_tickets">#</a></span></h4>
<p>The servers encrypt the entire session state and send it
to the client as a "ticket". When reconnecting, the state is sent to the server
in the initial connection. This mechanism avoids the need for server-side
session cache. If the server doesn't use the ticket, for any reason (failure
to decrypt it, it's too old, etc.), it will create a new session and send a new
ticket. See <a href="https://tools.ietf.org/html/rfc5077">RFC 5077</a> for more information.</p>
<p>Resumption using session tickets is becoming commonly supported by many web
browsers when making HTTPS requests.</p>
<p>For Node.js, clients use the same APIs for resumption with session identifiers
as for resumption with session tickets. For debugging, if
<a href="#tls_tlssocket_gettlsticket"><code>tls.TLSSocket.getTLSTicket()</code></a> returns a value, the session data contains a
ticket, otherwise it contains client-side session state.</p>
<p>With TLSv1.3, be aware that multiple tickets may be sent by the server,
resulting in multiple <code>'session'</code> events, see <a href="#tls_event_session"><code>'session'</code></a> for more
information.</p>
<p>Single process servers need no specific implementation to use session tickets.
To use session tickets across server restarts or load balancers, servers must
all have the same ticket keys. There are three 16-byte keys internally, but the
tls API exposes them as a single 48-byte buffer for convenience.</p>
<p>Its possible to get the ticket keys by calling <a href="#tls_server_getticketkeys"><code>server.getTicketKeys()</code></a> on
one server instance and then distribute them, but it is more reasonable to
securely generate 48 bytes of secure random data and set them with the
<code>ticketKeys</code> option of <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>. The keys should be regularly
regenerated and server's keys can be reset with
<a href="#tls_server_setticketkeys_keys"><code>server.setTicketKeys()</code></a>.</p>
<p>Session ticket keys are cryptographic keys, and they <strong><em>must be stored
securely</em></strong>. With TLS 1.2 and below, if they are compromised all sessions that
used tickets encrypted with them can be decrypted. They should not be stored
on disk, and they should be regenerated regularly.</p>
<p>If clients advertise support for tickets, the server will send them. The
server can disable tickets by supplying
<code>require('constants').SSL_OP_NO_TICKET</code> in <code>secureOptions</code>.</p>
<p>Both session identifiers and session tickets timeout, causing the server to
create new sessions. The timeout can be configured with the <code>sessionTimeout</code>
option of <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>.</p>
<p>For all the mechanisms, when resumption fails, servers will create new sessions.
Since failing to resume the session does not cause TLS/HTTPS connection
failures, it is easy to not notice unnecessarily poor TLS performance. The
OpenSSL CLI can be used to verify that servers are resuming sessions. Use the
<code>-reconnect</code> option to <code>openssl s_client</code>, for example:</p>
<pre><code class="language-console">$ openssl s_client -connect localhost:443 -reconnect
</code></pre>
<p>Read through the debug output. The first connection should say "New", for
example:</p>
<pre><code class="language-text">New, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
</code></pre>
<p>Subsequent connections should say "Reused", for example:</p>
<pre><code class="language-text">Reused, TLSv1.2, Cipher is ECDHE-RSA-AES128-GCM-SHA256
</code></pre>
<h2>Modifying the default TLS cipher suite<span><a class="mark" href="#tls_modifying_the_default_tls_cipher_suite" id="tls_modifying_the_default_tls_cipher_suite">#</a></span></h2>
<p>Node.js is built with a default suite of enabled and disabled TLS ciphers. This
default cipher list can be configured when building Node.js to allow
distributions to provide their own default list.</p>
<p>The following command can be used to show the default cipher suite:</p>
<pre><code class="language-console">node -p crypto.constants.defaultCoreCipherList | tr ':' '\n'
TLS_AES_256_GCM_SHA384
TLS_CHACHA20_POLY1305_SHA256
TLS_AES_128_GCM_SHA256
ECDHE-RSA-AES128-GCM-SHA256
ECDHE-ECDSA-AES128-GCM-SHA256
ECDHE-RSA-AES256-GCM-SHA384
ECDHE-ECDSA-AES256-GCM-SHA384
DHE-RSA-AES128-GCM-SHA256
ECDHE-RSA-AES128-SHA256
DHE-RSA-AES128-SHA256
ECDHE-RSA-AES256-SHA384
DHE-RSA-AES256-SHA384
ECDHE-RSA-AES256-SHA256
DHE-RSA-AES256-SHA256
HIGH
!aNULL
!eNULL
!EXPORT
!DES
!RC4
!MD5
!PSK
!SRP
!CAMELLIA
</code></pre>
<p>This default can be replaced entirely using the <a href="#cli_tls_cipher_list_list"><code>--tls-cipher-list</code></a> command
line switch (directly, or via the <a href="#cli_node_options_options"><code>NODE_OPTIONS</code></a> environment variable). For
instance, the following makes <code>ECDHE-RSA-AES128-GCM-SHA256:!RC4</code> the default TLS
cipher suite:</p>
<pre><code class="language-bash">node --tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4' server.js

export NODE_OPTIONS=--tls-cipher-list='ECDHE-RSA-AES128-GCM-SHA256:!RC4'
node server.js
</code></pre>
<p>The default can also be replaced on a per client or server basis using the
<code>ciphers</code> option from <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>, which is also available
in <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>, <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>, and when creating new
<a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a>s.</p>
<p>The ciphers list can contain a mixture of TLSv1.3 cipher suite names, the ones
that start with <code>'TLS_'</code>, and specifications for TLSv1.2 and below cipher
suites. The TLSv1.2 ciphers support a legacy specification format, consult
the OpenSSL <a href="https://www.openssl.org/docs/man1.1.1/man1/ciphers.html#CIPHER-LIST-FORMAT">cipher list format</a> documentation for details, but those
specifications do <em>not</em> apply to TLSv1.3 ciphers. The TLSv1.3 suites can only
be enabled by including their full name in the cipher list. They cannot, for
example, be enabled or disabled by using the legacy TLSv1.2 <code>'EECDH'</code> or
<code>'!EECDH'</code> specification.</p>
<p>Despite the relative order of TLSv1.3 and TLSv1.2 cipher suites, the TLSv1.3
protocol is significantly more secure than TLSv1.2, and will always be chosen
over TLSv1.2 if the handshake indicates it is supported, and if any TLSv1.3
cipher suites are enabled.</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 OpenSSL <a href="https://www.openssl.org/docs/man1.1.1/man1/ciphers.html#CIPHER-LIST-FORMAT">cipher list format</a> documentation.</p>
<p>There are only 5 TLSv1.3 cipher suites:</p>
<ul>
<li><code>'TLS_AES_256_GCM_SHA384'</code></li>
<li><code>'TLS_CHACHA20_POLY1305_SHA256'</code></li>
<li><code>'TLS_AES_128_GCM_SHA256'</code></li>
<li><code>'TLS_AES_128_CCM_SHA256'</code></li>
<li><code>'TLS_AES_128_CCM_8_SHA256'</code></li>
</ul>
<p>The first 3 are enabled by default. The last 2 <code>CCM</code>-based suites are supported
by TLSv1.3 because they may be more performant on constrained systems, but they
are not enabled by default since they offer less security.</p>
<h2>Class: <code>tls.Server</code><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>
<ul>
<li>Extends: <a href="#net_class_net_server" class="type">&#x3C;net.Server></a></li>
</ul>
<p>Accepts encrypted connections using TLS or SSL.</p>
<h3>Event: <code>'keylog'</code><span><a class="mark" href="#tls_event_keylog" id="tls_event_keylog">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.3.0</span>
</div>
<ul>
<li><code>line</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> Line of ASCII text, in NSS <code>SSLKEYLOGFILE</code> format.</li>
<li><code>tlsSocket</code> <a href="#tls_class_tls_tlssocket" class="type">&#x3C;tls.TLSSocket></a> The <code>tls.TLSSocket</code> instance on which it was
generated.</li>
</ul>
<p>The <code>keylog</code> event is emitted when key material is generated or received by
a connection to this server (typically before handshake has completed, but not
necessarily). This keying material can be stored for debugging, as it allows
captured TLS traffic to be decrypted. It may be emitted multiple times for
each socket.</p>
<p>A typical use case is to append received lines to a common text file, which
is later used by software (such as Wireshark) to decrypt the traffic:</p>
<pre><code class="language-js">const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
// ...
server.on('keylog', (line, tlsSocket) => {
  if (tlsSocket.remoteAddress !== '...')
    return; // Only log keys for a particular IP
  logFile.write(line);
});
</code></pre>
<h3>Event: <code>'newSession'</code><span><a class="mark" href="#tls_event_newsession" id="tls_event_newsession">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.2</span>
</div>
<p>The <code>'newSession'</code> event is emitted upon creation of a new TLS session. This may
be used to store sessions in external storage. The data should be provided to
the <a href="#tls_event_resumesession"><code>'resumeSession'</code></a> callback.</p>
<p>The listener callback is passed three arguments when called:</p>
<ul>
<li><code>sessionId</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The TLS session identifier</li>
<li><code>sessionData</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The TLS session data</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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: <code>'OCSPRequest'</code><span><a class="mark" href="#tls_event_ocsprequest" id="tls_event_ocsprequest">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<p>The <code>'OCSPRequest'</code> event is emitted when the client sends a certificate status
request. The listener callback is passed three arguments when called:</p>
<ul>
<li><code>certificate</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The server certificate</li>
<li><code>issuer</code> <a href="#buffer_class_buffer" class="type">&#x3C;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">&#x3C;Function></a> A callback function that must be invoked to provide
the results of the OCSP request.</li>
</ul>
<p>The server's current certificate can be parsed to obtain the OCSP URL
and certificate ID; after obtaining an OCSP response, <code>callback(null, resp)</code> is
then invoked, where <code>resp</code> is a <code>Buffer</code> instance containing the OCSP response.
Both <code>certificate</code> and <code>issuer</code> are <code>Buffer</code> DER-representations of the
primary and issuer's certificates. These can be used to obtain the OCSP
certificate ID and OCSP endpoint URL.</p>
<p>Alternatively, <code>callback(null, null)</code> may be called, indicating that there was
no OCSP response.</p>
<p>Calling <code>callback(err)</code> will result in a <code>socket.destroy(err)</code> call.</p>
<p>The typical flow of an OCSP Request is as follows:</p>
<ol>
<li>Client connects to the server and sends an <code>'OCSPRequest'</code> (via the status
info extension in ClientHello).</li>
<li>Server receives the request and emits the <code>'OCSPRequest'</code> event, calling the
listener if registered.</li>
<li>Server extracts the OCSP URL from either the <code>certificate</code> or <code>issuer</code> and
performs an <a href="https://en.wikipedia.org/wiki/OCSP_stapling">OCSP request</a> to the CA.</li>
<li>Server receives <code>'OCSPResponse'</code> from the CA and sends it back to the client
via the <code>callback</code> argument</li>
<li>Client validates the response and either destroys the socket or performs a
handshake.</li>
</ol>
<p>The <code>issuer</code> can be <code>null</code> if the certificate is either self-signed or the
issuer is not in the root certificates list. (An issuer may be provided
via the <code>ca</code> option when establishing the TLS connection.)</p>
<p>Listening for this event will have an effect only on connections established
after the addition of the event listener.</p>
<p>An npm module like <a href="https://www.npmjs.com/package/asn1.js">asn1.js</a> may be used to parse the certificates.</p>
<h3>Event: <code>'resumeSession'</code><span><a class="mark" href="#tls_event_resumesession" id="tls_event_resumesession">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.2</span>
</div>
<p>The <code>'resumeSession'</code> event is emitted when the client requests to resume a
previous TLS session. The listener callback is passed two arguments when
called:</p>
<ul>
<li><code>sessionId</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The TLS session identifier</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A callback function to be called when the prior session
has been recovered: <code>callback([err[, sessionData]])</code></p>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
<li><code>sessionData</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
</ul>
<p>The event listener should perform a lookup in external storage for the
<code>sessionData</code> saved by the <a href="#tls_event_newsession"><code>'newSession'</code></a> event handler using the given
<code>sessionId</code>. If found, call <code>callback(null, sessionData)</code> to resume the session.
If not found, the session cannot be resumed. <code>callback()</code> must be called
without <code>sessionData</code> so that the handshake can continue and a new session can
be created. It is possible to call <code>callback(err)</code> to terminate the incoming
connection and destroy the socket.</p>
<p>Listening for this event will have an effect only on connections established
after the addition of the event listener.</p>
<p>The following illustrates resuming a TLS session:</p>
<pre><code class="language-js">const tlsSessionStore = {};
server.on('newSession', (id, data, cb) => {
  tlsSessionStore[id.toString('hex')] = data;
  cb();
});
server.on('resumeSession', (id, cb) => {
  cb(null, tlsSessionStore[id.toString('hex')] || null);
});
</code></pre>
<h3>Event: <code>'secureConnection'</code><span><a class="mark" href="#tls_event_secureconnection" id="tls_event_secureconnection">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div>
<p>The <code>'secureConnection'</code> event is emitted after the handshaking process for a
new connection has successfully completed. The listener callback is passed a
single argument when called:</p>
<ul>
<li><code>tlsSocket</code> <a href="#tls_class_tls_tlssocket" class="type">&#x3C;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. Depending on the settings
of the TLS server, unauthorized connections may still be accepted.</p>
<p>The <code>tlsSocket.alpnProtocol</code> property is a string that contains the selected
ALPN protocol. When ALPN has no selected protocol, <code>tlsSocket.alpnProtocol</code>
equals <code>false</code>.</p>
<p>The <code>tlsSocket.servername</code> property is a string containing the server name
requested via SNI.</p>
<h3>Event: <code>'tlsClientError'</code><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">&#x3C;Error></a> The <code>Error</code> object describing the error</li>
<li><code>tlsSocket</code> <a href="#tls_class_tls_tlssocket" class="type">&#x3C;tls.TLSSocket></a> The <code>tls.TLSSocket</code> instance from which the
error originated.</li>
</ul>
<h3><code>server.addContext(hostname, context)</code><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">&#x3C;string></a> A SNI host name 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">&#x3C;Object></a> An object containing any of the possible properties
from the <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> <code>options</code> arguments (e.g. <code>key</code>,
<code>cert</code>, <code>ca</code>, etc).</li>
</ul>
<p>The <code>server.addContext()</code> method adds a secure context that will be used if
the client request's SNI name matches the supplied <code>hostname</code> (or wildcard).</p>
<h3><code>server.address()</code><span><a class="mark" href="#tls_server_address" id="tls_server_address">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns the bound address, the address family name, and port of the
server as reported by the operating system. See <a href="#net_server_address"><code>net.Server.address()</code></a> for
more information.</p>
<h3><code>server.close([callback])</code><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">&#x3C;Function></a> A listener callback that will be registered to listen
for the server instance's <code>'close'</code> event.</li>
<li>Returns: <a href="#tls_class_tls_server" class="type">&#x3C;tls.Server></a></li>
</ul>
<p>The <code>server.close()</code> method stops the server from accepting new connections.</p>
<p>This function operates asynchronously. The <code>'close'</code> event will be emitted
when the server has no more open connections.</p>
<h3><code>server.connections</code><span><a class="mark" href="#tls_server_connections" id="tls_server_connections">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.2</span><span>Deprecated since: v0.9.7</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#net_server_getconnections_callback"><code>server.getConnections()</code></a> instead.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Returns the current number of concurrent connections on the server.</p>
<h3><code>server.getTicketKeys()</code><span><a class="mark" href="#tls_server_getticketkeys" id="tls_server_getticketkeys">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<ul>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A 48-byte buffer containing the session ticket keys.</li>
</ul>
<p>Returns the session ticket keys.</p>
<p>See <a href="#tls_session_resumption">Session Resumption</a> for more information.</p>
<h3><code>server.listen()</code><span><a class="mark" href="#tls_server_listen" id="tls_server_listen">#</a></span></h3>
<p>Starts the server listening for encrypted connections.
This method is identical to <a href="#net_server_listen"><code>server.listen()</code></a> from <a href="#net_class_net_server"><code>net.Server</code></a>.</p>
<h3><code>server.setSecureContext(options)</code><span><a class="mark" href="#tls_server_setsecurecontext_options" id="tls_server_setsecurecontext_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.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">&#x3C;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.setSecureContext()</code> method replaces the secure context of an
existing server. Existing connections to the server are not interrupted.</p>
<h3><code>server.setTicketKeys(keys)</code><span><a class="mark" href="#tls_server_setticketkeys_keys" id="tls_server_setticketkeys_keys">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<ul>
<li><code>keys</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A 48-byte buffer containing the session ticket keys.</li>
</ul>
<p>Sets the session ticket keys.</p>
<p>Changes to the ticket keys are effective only for future server connections.
Existing or currently pending server connections will use the previous keys.</p>
<p>See <a href="#tls_session_resumption">Session Resumption</a> for more information.</p>
<h2>Class: <code>tls.TLSSocket</code><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>
<ul>
<li>Extends: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Performs transparent encryption of written data and all required TLS
negotiation.</p>
<p>Instances of <code>tls.TLSSocket</code> implement the duplex <a href="#stream_stream">Stream</a> interface.</p>
<p>Methods that return TLS connection metadata (e.g.
<a href="#tls_tlssocket_getpeercertificate_detailed"><code>tls.TLSSocket.getPeerCertificate()</code></a> will only return data while the
connection is open.</p>
<h3><code>new tls.TLSSocket(socket[, options])</code><span><a class="mark" href="#tls_new_tls_tlssocket_socket_options" id="tls_new_tls_tlssocket_socket_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.2.0</td>
<td><p>The <code>enableTrace</code> option is now supported.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>ALPN options are supported now.</p></td></tr>
<tr><td>v0.11.4</td>
<td><p><span>Added in: v0.11.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>socket</code> <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a> | <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a>
On the server side, any <code>Duplex</code> stream. On the client side, any
instance of <a href="#net_class_net_socket"><code>net.Socket</code></a> (for generic <code>Duplex</code> stream support
on the client side, <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> must be used).</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>enableTrace</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>isServer</code>: The SSL/TLS protocol is asymmetrical, TLSSockets must know if
they are to behave as a server or a client. If <code>true</code> the TLS socket will be
instantiated as a server. <strong>Default:</strong> <code>false</code>.</li>
<li><code>server</code> <a href="#net_class_net_server" class="type">&#x3C;net.Server></a> A <a href="#net_class_net_server"><code>net.Server</code></a> instance.</li>
<li><code>requestCert</code>: Whether to authenticate the remote peer by requesting a
certificate. Clients always request a server certificate. Servers
(<code>isServer</code> is true) may set <code>requestCert</code> to true to request a client
certificate.</li>
<li><code>rejectUnauthorized</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>ALPNProtocols</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>SNICallback</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>session</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A <code>Buffer</code> instance containing a TLS session.</li>
<li><code>requestOCSP</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, specifies that the OCSP status request
extension will be added to the client hello and an <code>'OCSPResponse'</code> event
will be emitted on the socket before establishing a secure communication</li>
<li><code>secureContext</code>: TLS context object created with
<a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>. If a <code>secureContext</code> is <em>not</em> provided, one
will be created by passing the entire <code>options</code> object to
<code>tls.createSecureContext()</code>.</li>
<li>...: <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> options that are used if the
<code>secureContext</code> option is missing. Otherwise, they are ignored.</li>
</ul>
</li>
</ul>
<p>Construct a new <code>tls.TLSSocket</code> object from an existing TCP socket.</p>
<h3>Event: <code>'keylog'</code><span><a class="mark" href="#tls_event_keylog_1" id="tls_event_keylog_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.3.0</span>
</div>
<ul>
<li><code>line</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> Line of ASCII text, in NSS <code>SSLKEYLOGFILE</code> format.</li>
</ul>
<p>The <code>keylog</code> event is emitted on a <code>tls.TLSSocket</code> when key material
is generated or received by the socket. This keying material can be stored
for debugging, as it allows captured TLS traffic to be decrypted. It may
be emitted multiple times, before or after the handshake completes.</p>
<p>A typical use case is to append received lines to a common text file, which
is later used by software (such as Wireshark) to decrypt the traffic:</p>
<pre><code class="language-js">const logFile = fs.createWriteStream('/tmp/ssl-keys.log', { flags: 'a' });
// ...
tlsSocket.on('keylog', (line) => logFile.write(line));
</code></pre>
<h3>Event: <code>'OCSPResponse'</code><span><a class="mark" href="#tls_event_ocspresponse" id="tls_event_ocspresponse">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div>
<p>The <code>'OCSPResponse'</code> event is emitted if the <code>requestOCSP</code> option was set
when the <code>tls.TLSSocket</code> was created and an OCSP response has been received.
The listener callback is passed a single argument when called:</p>
<ul>
<li><code>response</code> <a href="#buffer_class_buffer" class="type">&#x3C;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: <code>'secureConnect'</code><span><a class="mark" href="#tls_event_secureconnect" id="tls_event_secureconnect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<p>The <code>'secureConnect'</code> event is emitted after the handshaking process for a new
connection has successfully completed. The listener callback will be called
regardless of whether or not the server's certificate has been authorized. It
is the client's responsibility to check the <code>tlsSocket.authorized</code> property to
determine if the server certificate was signed by one of the specified CAs. If
<code>tlsSocket.authorized === false</code>, then the error can be found by examining the
<code>tlsSocket.authorizationError</code> property. If ALPN was used, the
<code>tlsSocket.alpnProtocol</code> property can be checked to determine the negotiated
protocol.</p>
<h3>Event: <code>'session'</code><span><a class="mark" href="#tls_event_session" id="tls_event_session">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><code>session</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>The <code>'session'</code> event is emitted on a client <code>tls.TLSSocket</code> when a new session
or TLS ticket is available. This may or may not be before the handshake is
complete, depending on the TLS protocol version that was negotiated. The event
is not emitted on the server, or if a new session was not created, for example,
when the connection was resumed. For some TLS protocol versions the event may be
emitted multiple times, in which case all the sessions can be used for
resumption.</p>
<p>On the client, the <code>session</code> can be provided to the <code>session</code> option of
<a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> to resume the connection.</p>
<p>See <a href="#tls_session_resumption">Session Resumption</a> for more information.</p>
<p>For TLSv1.2 and below, <a href="#tls_tlssocket_getsession"><code>tls.TLSSocket.getSession()</code></a> can be called once
the handshake is complete. For TLSv1.3, only ticket-based resumption is allowed
by the protocol, multiple tickets are sent, and the tickets aren't sent until
after the handshake completes. So it is necessary to wait for the
<code>'session'</code> event to get a resumable session. Applications
should use the <code>'session'</code> event instead of <code>getSession()</code> to ensure
they will work for all TLS versions. Applications that only expect to
get or use one session should listen for this event only once:</p>
<pre><code class="language-js">tlsSocket.once('session', (session) => {
  // The session can be used immediately or later.
  tls.connect({
    session: session,
    // Other connect options...
  });
});
</code></pre>
<h3><code>tlsSocket.address()</code><span><a class="mark" href="#tls_tlssocket_address" id="tls_tlssocket_address">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns the bound <code>address</code>, the address <code>family</code> name, and <code>port</code> of the
underlying socket as reported by the operating system:
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code>.</p>
<h3><code>tlsSocket.authorizationError</code><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><code>tlsSocket.authorized</code><span><a class="mark" href="#tls_tlssocket_authorized" id="tls_tlssocket_authorized">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the peer certificate was signed by one of the CAs specified
when creating the <code>tls.TLSSocket</code> instance, otherwise <code>false</code>.</p>
<h3><code>tlsSocket.disableRenegotiation()</code><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><code>tlsSocket.enableTrace()</code><span><a class="mark" href="#tls_tlssocket_enabletrace" id="tls_tlssocket_enabletrace">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.2.0</span>
</div>
<p>When enabled, TLS packet trace information is written to <code>stderr</code>. This can be
used to debug TLS connection problems.</p>
<p>Note: The format of the output is identical to the output of <code>openssl s_client -trace</code> or <code>openssl s_server -trace</code>. While it is produced by OpenSSL's
<code>SSL_trace()</code> function, the format is undocumented, can change without notice,
and should not be relied on.</p>
<h3><code>tlsSocket.encrypted</code><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><code>tlsSocket.getCertificate()</code><span><a class="mark" href="#tls_tlssocket_getcertificate" id="tls_tlssocket_getcertificate">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.2.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns an object representing the local certificate. The returned object has
some properties corresponding to the fields of the certificate.</p>
<p>See <a href="#tls_tlssocket_getpeercertificate_detailed"><code>tls.TLSSocket.getPeerCertificate()</code></a> for an example of the certificate
structure.</p>
<p>If there is no local certificate, an empty object will be returned. If the
socket has been destroyed, <code>null</code> will be returned.</p>
<h3><code>tlsSocket.getCipher()</code><span><a class="mark" href="#tls_tlssocket_getcipher" id="tls_tlssocket_getcipher">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>Return the IETF cipher name as <code>standardName</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Return the minimum cipher version, instead of a fixed string (<code>'TLSv1/SSLv3'</code>).</p></td></tr>
<tr><td>v0.11.4</td>
<td><p><span>Added in: v0.11.4</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> OpenSSL name for the cipher suite.</li>
<li><code>standardName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> IETF name for the cipher suite.</li>
<li><code>version</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The minimum TLS protocol version supported by this cipher
suite.</li>
</ul>
</li>
</ul>
<p>Returns an object containing information on the negotiated cipher suite.</p>
<p>For example:</p>
<pre><code class="language-json">{
    "name": "AES128-SHA256",
    "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256",
    "version": "TLSv1.2"
}
</code></pre>
<p>See
<a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html">SSL_CIPHER_get_name</a>
for more information.</p>
<h3><code>tlsSocket.getEphemeralKeyInfo()</code><span><a class="mark" href="#tls_tlssocket_getephemeralkeyinfo" id="tls_tlssocket_getephemeralkeyinfo">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v5.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns an object representing the type, name, and size of parameter of
an ephemeral key exchange in <a href="#tls_perfect_forward_secrecy">perfect forward secrecy</a> on a client
connection. It returns an empty object when the key exchange is not
ephemeral. As this is only supported on a client socket; <code>null</code> is returned
if called on a server socket. The supported types are <code>'DH'</code> and <code>'ECDH'</code>. The
<code>name</code> property is available only when type is <code>'ECDH'</code>.</p>
<p>For example: <code>{ type: 'ECDH', name: 'prime256v1', size: 256 }</code>.</p>
<h3><code>tlsSocket.getFinished()</code><span><a class="mark" href="#tls_tlssocket_getfinished" id="tls_tlssocket_getfinished">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.9.0</span>
</div>
<ul>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;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><code>tlsSocket.getPeerCertificate([detailed])</code><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">&#x3C;boolean></a> Include the full certificate chain if <code>true</code>, otherwise
include just the peer's certificate.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> A certificate object.</li>
</ul>
<p>Returns an object representing the peer's certificate. If the peer does not
provide a certificate, an empty object will be returned. If the socket has been
destroyed, <code>null</code> will be returned.</p>
<p>If the full certificate chain was requested, each certificate will include an
<code>issuerCertificate</code> property containing an object representing its issuer's
certificate.</p>
<h4>Certificate object<span><a class="mark" href="#tls_certificate_object" id="tls_certificate_object">#</a></span></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.4.0</td>
<td><p>Support Elliptic Curve public key info.</p></td></tr>
</tbody></table>
</details>
</div>
<p>A certificate object has properties corresponding to the fields of the
certificate.</p>
<ul>
<li><code>raw</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The DER encoded X.509 certificate data.</li>
<li><code>subject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The certificate subject, described in terms of
 Country (<code>C:</code>), StateOrProvince (<code>ST</code>), Locality (<code>L</code>), Organization (<code>O</code>),
OrganizationalUnit (<code>OU</code>), and CommonName (<code>CN</code>). The CommonName is typically
a DNS name with TLS certificates. Example:
<code>{C: 'UK', ST: 'BC', L: 'Metro', O: 'Node Fans', OU: 'Docs', CN: 'example.com'}</code>.</li>
<li><code>issuer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The certificate issuer, described in the same terms as the
 <code>subject</code>.</li>
<li><code>valid_from</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The date-time the certificate is valid from.</li>
<li><code>valid_to</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The date-time the certificate is valid to.</li>
<li><code>serialNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The certificate serial number, as a hex string.
 Example: <code>'B9B0D332A1AA5635'</code>.</li>
<li><code>fingerprint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The SHA-1 digest of the DER encoded certificate. It is
returned as a <code>:</code> separated hexadecimal string. Example: <code>'2A:7A:C2:DD:...'</code>.</li>
<li><code>fingerprint256</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The SHA-256 digest of the DER encoded certificate.
 It is returned as a <code>:</code> separated hexadecimal string. Example:
<code>'2A:7A:C2:DD:...'</code>.</li>
<li><code>ext_key_usage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> (Optional) The extended key usage, a set of OIDs.</li>
<li><code>subjectaltname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> (Optional) A string containing concatenated names
for the subject, an alternative to the <code>subject</code> names.</li>
<li><code>infoAccess</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> (Optional) An array describing the AuthorityInfoAccess,
 used with OCSP.</li>
<li><code>issuerCertificate</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> (Optional) The issuer certificate object. For
 self-signed certificates, this may be a circular reference.</li>
</ul>
<p>The certificate may contain information about the public key, depending on
the key type.</p>
<p>For RSA keys, the following properties may be defined:</p>
<ul>
<li><code>bits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The RSA bit size. Example: <code>1024</code>.</li>
<li><code>exponent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The RSA exponent, as a string in hexadecimal number
notation. Example: <code>'0x010001'</code>.</li>
<li><code>modulus</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The RSA modulus, as a hexadecimal string. Example:
 <code>'B56CE45CB7...'</code>.</li>
<li><code>pubkey</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The public key.</li>
</ul>
<p>For EC keys, the following properties may be defined:</p>
<ul>
<li><code>pubkey</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The public key.</li>
<li><code>bits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The key size in bits. Example: <code>256</code>.</li>
<li><code>asn1Curve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> (Optional) The ASN.1 name of the OID of the elliptic
curve. Well-known curves are identified by an OID. While it is unusual, it is
possible that the curve is identified by its mathematical properties, in which
case it will not have an OID. Example: <code>'prime256v1'</code>.</li>
<li><code>nistCurve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> (Optional) The NIST name for the elliptic curve, if it
has one (not all well-known curves have been assigned names by NIST). Example:
<code>'P-256'</code>.</li>
</ul>
<p>Example certificate:</p>
<pre><code class="language-text">{ subject:
   { OU: [ 'Domain Control Validated', 'PositiveSSL Wildcard' ],
     CN: '*.nodejs.org' },
  issuer:
   { C: 'GB',
     ST: 'Greater Manchester',
     L: 'Salford',
     O: 'COMODO CA Limited',
     CN: 'COMODO RSA Domain Validation Secure Server CA' },
  subjectaltname: 'DNS:*.nodejs.org, DNS:nodejs.org',
  infoAccess:
   { 'CA Issuers - URI':
      [ 'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt' ],
     'OCSP - URI': [ 'http://ocsp.comodoca.com' ] },
  modulus: 'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1',
  exponent: '0x10001',
  pubkey: &#x3C;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: &#x3C;Buffer ... > }
</code></pre>
<h3><code>tlsSocket.getPeerFinished()</code><span><a class="mark" href="#tls_tlssocket_getpeerfinished" id="tls_tlssocket_getpeerfinished">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.9.0</span>
</div>
<ul>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;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><code>tlsSocket.getProtocol()</code><span><a class="mark" href="#tls_tlssocket_getprotocol" id="tls_tlssocket_getprotocol">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v5.7.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
</ul>
<p>Returns a string containing the negotiated SSL/TLS protocol version of the
current connection. The value <code>'unknown'</code> will be returned for connected
sockets that have not completed the handshaking process. The value <code>null</code> will
be returned for server sockets or disconnected client sockets.</p>
<p>Protocol versions are:</p>
<ul>
<li><code>'SSLv3'</code></li>
<li><code>'TLSv1'</code></li>
<li><code>'TLSv1.1'</code></li>
<li><code>'TLSv1.2'</code></li>
<li><code>'TLSv1.3'</code></li>
</ul>
<p>See the OpenSSL <a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html"><code>SSL_get_version</code></a> documentation for more information.</p>
<h3><code>tlsSocket.getSession()</code><span><a class="mark" href="#tls_tlssocket_getsession" id="tls_tlssocket_getsession">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Returns the TLS session data or <code>undefined</code> if no session was
negotiated. On the client, the data can be provided to the <code>session</code> option of
<a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> to resume the connection. On the server, it may be useful
for debugging.</p>
<p>See <a href="#tls_session_resumption">Session Resumption</a> for more information.</p>
<p>Note: <code>getSession()</code> works only for TLSv1.2 and below. For TLSv1.3, applications
must use the <a href="#tls_event_session"><code>'session'</code></a> event (it also works for TLSv1.2 and below).</p>
<h3><code>tlsSocket.getSharedSigalgs()</code><span><a class="mark" href="#tls_tlssocket_getsharedsigalgs" id="tls_tlssocket_getsharedsigalgs">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.11.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> List of signature algorithms shared between the server and
the client in the order of decreasing preference.</li>
</ul>
<p>See
<a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html">SSL_get_shared_sigalgs</a>
for more information.</p>
<h3><code>tlsSocket.exportKeyingMaterial(length, label[, context])</code><span><a class="mark" href="#tls_tlssocket_exportkeyingmaterial_length_label_context" id="tls_tlssocket_exportkeyingmaterial_length_label_context">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li>
<p><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> number of bytes to retrieve from keying material</p>
</li>
<li>
<p><code>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> an application specific label, typically this will be a
value from the
<a href="https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels">IANA Exporter Label Registry</a>.</p>
</li>
<li>
<p><code>context</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> Optionally provide a context.</p>
</li>
<li>
<p>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> requested bytes of the keying material</p>
</li>
</ul>
<p>Keying material is used for validations to prevent different kind of attacks in
network protocols, for example in the specifications of IEEE 802.1X.</p>
<p>Example</p>
<pre><code class="language-js">const keyingMaterial = tlsSocket.exportKeyingMaterial(
  128,
  'client finished');

/**
 Example return value of keyingMaterial:
 &#x3C;Buffer 76 26 af 99 c5 56 8e 42 09 91 ef 9f 93 cb ad 6c 7b 65 f8 53 f1 d8 d9
    12 5a 33 b8 b5 25 df 7b 37 9f e0 e2 4f b8 67 83 a3 2f cd 5d 41 42 4c 91
    74 ef 2c ... 78 more bytes>
*/
</code></pre>
<p>See the OpenSSL <a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html"><code>SSL_export_keying_material</code></a> documentation for more
information.</p>
<h3><code>tlsSocket.getTLSTicket()</code><span><a class="mark" href="#tls_tlssocket_gettlsticket" id="tls_tlssocket_gettlsticket">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>For a client, returns the TLS session ticket if one is available, or
<code>undefined</code>. For a server, always returns <code>undefined</code>.</p>
<p>It may be useful for debugging.</p>
<p>See <a href="#tls_session_resumption">Session Resumption</a> for more information.</p>
<h3><code>tlsSocket.isSessionReused()</code><span><a class="mark" href="#tls_tlssocket_issessionreused" id="tls_tlssocket_issessionreused">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.6</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if the session was reused, <code>false</code> otherwise.</li>
</ul>
<p>See <a href="#tls_session_resumption">Session Resumption</a> for more information.</p>
<h3><code>tlsSocket.localAddress</code><span><a class="mark" href="#tls_tlssocket_localaddress" id="tls_tlssocket_localaddress">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the string representation of the local IP address.</p>
<h3><code>tlsSocket.localPort</code><span><a class="mark" href="#tls_tlssocket_localport" id="tls_tlssocket_localport">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Returns the numeric representation of the local port.</p>
<h3><code>tlsSocket.remoteAddress</code><span><a class="mark" href="#tls_tlssocket_remoteaddress" id="tls_tlssocket_remoteaddress">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the string representation of the remote IP address. For example,
<code>'74.125.127.100'</code> or <code>'2001:4860:a005::68'</code>.</p>
<h3><code>tlsSocket.remoteFamily</code><span><a class="mark" href="#tls_tlssocket_remotefamily" id="tls_tlssocket_remotefamily">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the string representation of the remote IP family. <code>'IPv4'</code> or <code>'IPv6'</code>.</p>
<h3><code>tlsSocket.remotePort</code><span><a class="mark" href="#tls_tlssocket_remoteport" id="tls_tlssocket_remoteport">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Returns the numeric representation of the remote port. For example, <code>443</code>.</p>
<h3><code>tlsSocket.renegotiate(options, callback)</code><span><a class="mark" href="#tls_tlssocket_renegotiate_options_callback" id="tls_tlssocket_renegotiate_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>rejectUnauthorized</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If not <code>false</code>, the server certificate is
verified against the list of supplied CAs. An <code>'error'</code> event is emitted if
verification fails; <code>err.code</code> contains the OpenSSL error code. <strong>Default:</strong>
<code>true</code>.</li>
<li><code>requestCert</code></li>
</ul>
</li>
<li>
<p><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> If <code>renegotiate()</code> returned <code>true</code>, callback is
attached once to the <code>'secure'</code> event. If <code>renegotiate()</code> returned <code>false</code>,
<code>callback</code> will be called in the next tick with an error, unless the
<code>tlsSocket</code> has been destroyed, in which case <code>callback</code> will not be called
at all.</p>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if renegotiation was initiated, <code>false</code> otherwise.</p>
</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>
<p>For TLSv1.3, renegotiation cannot be initiated, it is not supported by the
protocol.</p>
<h3><code>tlsSocket.setMaxSendFragment(size)</code><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">&#x3C;number></a> The maximum TLS fragment size. The maximum value is <code>16384</code>.
<strong>Default:</strong> <code>16384</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <code>tlsSocket.setMaxSendFragment()</code> method sets the maximum TLS fragment size.
Returns <code>true</code> if setting the limit succeeded; <code>false</code> otherwise.</p>
<p>Smaller fragment sizes decrease the buffering latency on the client: larger
fragments are buffered by the TLS layer until the entire fragment is received
and its integrity is verified; large fragments can span multiple roundtrips
and their processing can be delayed due to packet loss or reordering. However,
smaller fragments add extra TLS framing bytes and CPU overhead, which may
decrease overall server throughput.</p>
<h2><code>tls.checkServerIdentity(hostname, cert)</code><span><a class="mark" href="#tls_tls_checkserveridentity_hostname_cert" id="tls_tls_checkserveridentity_hostname_cert">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.8.4</span>
</div>
<ul>
<li><code>hostname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The host name or IP address to verify the certificate
against.</li>
<li><code>cert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> A <a href="#tls_certificate_object">certificate object</a> representing the peer's certificate.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>Verifies the certificate <code>cert</code> is issued to <code>hostname</code>.</p>
<p>Returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> object, populating it with <code>reason</code>, <code>host</code>, and <code>cert</code> on
failure. On success, returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;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>
<h2><code>tls.connect(options[, callback])</code><span><a class="mark" href="#tls_tls_connect_options_callback" id="tls_tls_connect_options_callback">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>pskCallback</code> option is now supported.</p></td></tr>
<tr><td>v12.9.0</td>
<td><p>Support the <code>allowHalfOpen</code> option.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p>The <code>hints</code> option is now supported.</p></td></tr>
<tr><td>v12.2.0</td>
<td><p>The <code>enableTrace</code> option is now supported.</p></td></tr>
<tr><td>v11.8.0</td>
<td><p>The <code>timeout</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>lookup</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>ALPNProtocols</code> option can be a <code>TypedArray</code> or <code>DataView</code> now.</p></td></tr>
<tr><td>v5.3.0, v4.7.0</td>
<td><p>The <code>secureContext</code> option is supported now.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>ALPN options are supported now.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p><span>Added in: v0.11.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>enableTrace</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Host the client should connect to. <strong>Default:</strong>
<code>'localhost'</code>.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;string></a> Creates Unix socket connection to path. If this option is
specified, <code>host</code> and <code>port</code> are ignored.</li>
<li><code>socket</code> <a href="#stream_class_stream_duplex" class="type">&#x3C;stream.Duplex></a> Establish secure connection on a given socket
rather than creating a new socket. Typically, this is an instance of
<a href="#net_class_net_socket"><code>net.Socket</code></a>, but any <code>Duplex</code> stream is allowed.
If this option is specified, <code>path</code>, <code>host</code> and <code>port</code> are ignored,
except for certificate validation. Usually, a socket is already connected
when passed to <code>tls.connect()</code>, but it can be connected later.
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>allowHalfOpen</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If the <code>socket</code> option is missing, indicates
whether or not to allow the internally created socket to be half-open,
otherwise the option is ignored. See the <code>allowHalfOpen</code> option of
<a href="#net_class_net_socket"><code>net.Socket</code></a> for details. <strong>Default:</strong> <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">&#x3C;boolean></a> If not <code>false</code>, the server certificate is
verified against the list of supplied CAs. An <code>'error'</code> event is emitted if
verification fails; <code>err.code</code> contains the OpenSSL error code. <strong>Default:</strong>
<code>true</code>.</li>
<li>
<p><code>pskCallback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li>hint: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> optional message sent from the server to help client
decide which identity to use during negotiation.
Always <code>null</code> if TLS 1.3 is used.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> in the form
  <code>{ psk: &#x3C;Buffer|TypedArray|DataView>, identity: &#x3C;string> }</code>
or <code>null</code> to stop the negotiation process. <code>psk</code> must be
compatible with the selected cipher's digest.
<code>identity</code> must use UTF-8 encoding.
When negotiating TLS-PSK (pre-shared keys), this function is called
with optional identity <code>hint</code> provided by the server or <code>null</code>
in case of TLS 1.3 where <code>hint</code> was removed.
It will be necessary to provide a custom <code>tls.checkServerIdentity()</code>
for the connection as the default one will try to check host name/IP
of the server against the certificate but that's not applicable for PSK
because there won't be a certificate present.
More information can be found in the <a href="https://tools.ietf.org/html/rfc4279">RFC 4279</a>.</li>
</ul>
</li>
<li><code>ALPNProtocols</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView[]></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a>
An array of strings, <code>Buffer</code>s or <code>TypedArray</code>s or <code>DataView</code>s, or a
single <code>Buffer</code> or <code>TypedArray</code> or <code>DataView</code> containing the supported ALPN
protocols. <code>Buffer</code>s should have the format <code>[len][name][len][name]...</code>
e.g. <code>'\x08http/1.1\x08http/1.0'</code>, where the <code>len</code> byte is the length of the
next protocol name. Passing an array is usually much simpler, e.g.
<code>['http/1.1', 'http/1.0']</code>. Protocols earlier in the list have higher
preference than those later.</li>
<li><code>servername</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Server name for the SNI (Server Name Indication) TLS
extension. It is the name of the host being connected to, and must be a host
name, and not an IP address. It can be used by a multi-homed server to
choose the correct certificate to present to the client, see the
<code>SNICallback</code> option to <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>.</li>
<li><code>checkServerIdentity(servername, cert)</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A callback function
to be used (instead of the builtin <code>tls.checkServerIdentity()</code> function)
when checking the server's host name (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">&#x3C;Error></a> if
verification fails. The method should return <code>undefined</code> if the <code>servername</code>
and <code>cert</code> are verified.</li>
<li><code>session</code> <a href="#buffer_class_buffer" class="type">&#x3C;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">&#x3C;number></a> Minimum size of the DH parameter in bits to accept a
TLS connection. When a server offers a DH parameter with a size less
than <code>minDHSize</code>, the TLS connection is destroyed and an error is thrown.
<strong>Default:</strong> <code>1024</code>.</li>
<li><code>secureContext</code>: TLS context object created with
<a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>. If a <code>secureContext</code> is <em>not</em> provided, one
will be created by passing the entire <code>options</code> object to
<code>tls.createSecureContext()</code>.</li>
<li>...: <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>
<li>...: Any <a href="#net_socket_connect_options_connectlistener"><code>socket.connect()</code></a> option not already listed.</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#tls_class_tls_tlssocket" class="type">&#x3C;tls.TLSSocket></a></li>
</ul>
<p>The <code>callback</code> function, if specified, will be added as a listener for the
<a href="#tls_event_secureconnect"><code>'secureConnect'</code></a> event.</p>
<p><code>tls.connect()</code> returns a <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> object.</p>
<p>Unlike the <code>https</code> API, <code>tls.connect()</code> does not enable the
SNI (Server Name Indication) extension by default, which may cause some
servers to return an incorrect certificate or reject the connection
altogether. To enable SNI, set the <code>servername</code> option in addition
to <code>host</code>.</p>
<p>The following illustrates a client for the echo server example from
<a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>:</p>
<pre><code class="language-js">// Assumes an echo server that is listening on port 8000.
const tls = require('tls');
const fs = require('fs');

const options = {
  // Necessary only if the server requires client certificate authentication.
  key: fs.readFileSync('client-key.pem'),
  cert: fs.readFileSync('client-cert.pem'),

  // Necessary only if the server uses a self-signed certificate.
  ca: [ fs.readFileSync('server-cert.pem') ],

  // Necessary only if the server's cert isn't for "localhost".
  checkServerIdentity: () => { return null; },
};

const socket = tls.connect(8000, options, () => {
  console.log('client connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  process.stdin.pipe(socket);
  process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
  console.log(data);
});
socket.on('end', () => {
  console.log('server ends connection');
});
</code></pre>
<h2><code>tls.connect(path[, options][, callback])</code><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">&#x3C;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">&#x3C;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">&#x3C;Function></a> See <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>.</li>
<li>Returns: <a href="#tls_class_tls_tlssocket" class="type">&#x3C;tls.TLSSocket></a></li>
</ul>
<p>Same as <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> except that <code>path</code> can be provided
as an argument instead of an option.</p>
<p>A path option, if specified, will take precedence over the path argument.</p>
<h2><code>tls.connect(port[, host][, options][, callback])</code><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">&#x3C;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">&#x3C;string></a> Default value for <code>options.host</code>.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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">&#x3C;Function></a> See <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>.</li>
<li>Returns: <a href="#tls_class_tls_tlssocket" class="type">&#x3C;tls.TLSSocket></a></li>
</ul>
<p>Same as <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> except that <code>port</code> and <code>host</code> can be provided
as arguments instead of options.</p>
<p>A port or host option, if specified, will take precedence over any port or host
argument.</p>
<h2><code>tls.createSecureContext([options])</code><span><a class="mark" href="#tls_tls_createsecurecontext_options" id="tls_tls_createsecurecontext_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.12.0</td>
<td><p>Added <code>privateKeyIdentifier</code> and <code>privateKeyEngine</code> options to get private key from an OpenSSL engine.</p></td></tr>
<tr><td>v12.11.0</td>
<td><p>Added <code>sigalgs</code> option to override supported signature algorithms.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>TLSv1.3 support added.</p></td></tr>
<tr><td>v11.5.0</td>
<td><p>The <code>ca:</code> option now supports <code>BEGIN TRUSTED CERTIFICATE</code>.</p></td></tr>
<tr><td>v11.4.0</td>
<td><p>The <code>minVersion</code> and <code>maxVersion</code> can be used to restrict the allowed TLS protocol versions.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>ecdhCurve</code> cannot be set to <code>false</code> anymore due to a change in OpenSSL.</p></td></tr>
<tr><td>v9.3.0</td>
<td><p>The <code>options</code> parameter can now include <code>clientCertEngine</code>.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>ecdhCurve</code> option can now be multiple <code>':'</code> separated curve names or <code>'auto'</code>.</p></td></tr>
<tr><td>v7.3.0</td>
<td><p>If the <code>key</code> option is an array, individual entries do not need a <code>passphrase</code> property anymore. <code>Array</code> entries can also just be <code>string</code>s or <code>Buffer</code>s now.</p></td></tr>
<tr><td>v5.2.0</td>
<td><p>The <code>ca</code> option can now be a single string containing multiple CA certificates.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>ca</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer[]></a> Optionally override the trusted CA
certificates. Default is to trust the well-known CAs curated by Mozilla.
Mozilla's CAs are completely replaced when CAs are explicitly specified
using this option. The value can be a string or <code>Buffer</code>, or an <code>Array</code> of
strings and/or <code>Buffer</code>s. Any string or <code>Buffer</code> can contain multiple PEM
CAs concatenated together. The peer's certificate must be chainable to a CA
trusted by the server for the connection to be authenticated. When using
certificates that are not chainable to a well-known CA, the certificate's CA
must be explicitly specified as a trusted or the connection will fail to
authenticate.
If the peer uses a certificate that doesn't match or chain to one of the
default CAs, use the <code>ca</code> option to provide a CA certificate that the peer's
certificate can match or chain to.
For self-signed certificates, the certificate is its own CA, and must be
provided.
For PEM encoded certificates, supported types are "TRUSTED CERTIFICATE",
"X509 CERTIFICATE", and "CERTIFICATE".
See also <a href="#tls_tls_rootcertificates"><code>tls.rootCertificates</code></a>.</li>
<li><code>cert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer[]></a> Cert chains in PEM format. One cert
chain should be provided per private key. Each cert chain should consist of
the PEM formatted certificate for a provided private <code>key</code>, followed by the
PEM formatted intermediate certificates (if any), in order, and not
including the root CA (the root CA must be pre-known to the peer, see <code>ca</code>).
When providing multiple cert chains, they do not have to be in the same
order as their private keys in <code>key</code>. If the intermediate certificates are
not provided, the peer will not be able to validate the certificate, and the
handshake will fail.</li>
<li><code>sigalgs</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Colon-separated list of supported signature algorithms.
The list can contain digest algorithms (<code>SHA256</code>, <code>MD5</code> etc.), public key
algorithms (<code>RSA-PSS</code>, <code>ECDSA</code> etc.), combination of both (e.g
'RSA+SHA384') or TLS v1.3 scheme names (e.g. <code>rsa_pss_pss_sha512</code>).
See <a href="https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set1_sigalgs_list.html">OpenSSL man pages</a>
for more info.</li>
<li><code>ciphers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Cipher suite specification, replacing the default. For
more information, see <a href="#tls_modifying_the_default_tls_cipher_suite">modifying the default cipher suite</a>. Permitted
ciphers can be obtained via <a href="#tls_tls_getciphers"><code>tls.getCiphers()</code></a>. Cipher names must be
uppercased in order for OpenSSL to accept them.</li>
<li><code>clientCertEngine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of an OpenSSL engine which can provide the
client certificate.</li>
<li><code>crl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer[]></a> PEM formatted CRLs (Certificate
Revocation Lists).</li>
<li><code>dhparam</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#buffer_class_buffer" class="type">&#x3C;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 or else an error
will be thrown. Although 1024 bits is permissible, use 2048 bits or larger
for stronger security. If omitted or invalid, the parameters are silently
discarded and DHE ciphers will not be available.</li>
<li><code>ecdhCurve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> A string describing a named curve or a colon separated
list of curve NIDs or names, for example <code>P-521:P-384:P-256</code>, to use for
ECDH key agreement. Set to <code>auto</code> to select the
curve automatically. Use <a href="#crypto_crypto_getcurves"><code>crypto.getCurves()</code></a> to obtain a list of
available curve names. On recent releases, <code>openssl ecparam -list_curves</code>
will also display the name and description of each available elliptic curve.
<strong>Default:</strong> <a href="#tls_tls_default_ecdh_curve"><code>tls.DEFAULT_ECDH_CURVE</code></a>.</li>
<li><code>honorCipherOrder</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Attempt to use the server's cipher suite
preferences instead of the client's. When <code>true</code>, causes
<code>SSL_OP_CIPHER_SERVER_PREFERENCE</code> to be set in <code>secureOptions</code>, see
<a href="#crypto_openssl_options">OpenSSL Options</a> for more information.</li>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> Private keys in PEM format.
PEM allows the option of private keys being encrypted. Encrypted keys will
be decrypted with <code>options.passphrase</code>. Multiple keys using different
algorithms can be provided either as an array of unencrypted key strings or
buffers, or an array of objects in the form
<code>{pem: &#x3C;string|buffer>[, passphrase: &#x3C;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>privateKeyEngine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of an OpenSSL engine to get private key
from. Should be used together with <code>privateKeyIdentifier</code>.</li>
<li><code>privateKeyIdentifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Identifier of a private key managed by
an OpenSSL engine. Should be used together with <code>privateKeyEngine</code>.
Should not be set together with <code>key</code>, because both options define a
private key in different ways.</li>
<li><code>maxVersion</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Optionally set the maximum TLS version to allow. One
of <code>'TLSv1.3'</code>, <code>'TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>. Cannot be specified
along with the <code>secureProtocol</code> option, use one or the other.
<strong>Default:</strong> <a href="#tls_tls_default_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a>.</li>
<li><code>minVersion</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Optionally set the minimum TLS version to allow. One
of <code>'TLSv1.3'</code>, <code>'TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>. Cannot be specified
along with the <code>secureProtocol</code> option, use one or the other. It is not
recommended to use less than TLSv1.2, but it may be required for
interoperability.
<strong>Default:</strong> <a href="#tls_tls_default_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a>.</li>
<li><code>passphrase</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Shared passphrase used for a single private key and/or
a PFX.</li>
<li><code>pfx</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> PFX or PKCS12 encoded
private key and certificate chain. <code>pfx</code> is an alternative to providing
<code>key</code> and <code>cert</code> individually. PFX is usually encrypted, if it is,
<code>passphrase</code> will be used to decrypt it. Multiple PFX can be provided either
as an array of unencrypted PFX buffers, or an array of objects in the form
<code>{buf: &#x3C;string|buffer>[, passphrase: &#x3C;string>]}</code>. The object form can only
occur in an array. <code>object.passphrase</code> is optional. Encrypted PFX will be
decrypted with <code>object.passphrase</code> if provided, or <code>options.passphrase</code> if
it is not.</li>
<li><code>secureOptions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Optionally affect the OpenSSL protocol behavior,
which is not usually necessary. This should be used carefully if at all!
Value is a numeric bitmask of the <code>SSL_OP_*</code> options from
<a href="#crypto_openssl_options">OpenSSL Options</a>.</li>
<li><code>secureProtocol</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Legacy mechanism to select the TLS protocol
version to use, it does not support independent control of the minimum and
maximum version, and does not support limiting the protocol to TLSv1.3. Use
<code>minVersion</code> and <code>maxVersion</code> instead. The possible values are listed as
<a href="https://www.openssl.org/docs/man1.1.1/man7/ssl.html#Dealing-with-Protocol-Methods">SSL_METHODS</a>, use the function names as strings. For example, use
<code>'TLSv1_1_method'</code> to force TLS version 1.1, or <code>'TLS_method'</code> to allow any
TLS protocol version up to TLSv1.3. It is not recommended to use TLS
versions less than 1.2, but it may be required for interoperability.
<strong>Default:</strong> none, see <code>minVersion</code>.</li>
<li><code>sessionIdContext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Opaque identifier used by servers to ensure
session state is not shared between applications. Unused by clients.</li>
</ul>
</li>
</ul>
<p><a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a> sets the default value of the <code>honorCipherOrder</code> option
to <code>true</code>, other APIs that create secure contexts leave it unset.</p>
<p><a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a> uses a 128 bit truncated SHA1 hash value generated
from <code>process.argv</code> as the default value of the <code>sessionIdContext</code> option, other
APIs that create secure contexts have no default value.</p>
<p>The <code>tls.createSecureContext()</code> method creates a <code>SecureContext</code> object. It is
usable as an argument to several <code>tls</code> APIs, such as <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>
and <a href="#tls_server_addcontext_hostname_context"><code>server.addContext()</code></a>, but has no public methods.</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 <code>ca</code> option is not given, then Node.js will default to using
<a href="https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt">Mozilla's publicly trusted list of CAs</a>.</p>
<h2><code>tls.createServer([options][, secureConnectionListener])</code><span><a class="mark" href="#tls_tls_createserver_options_secureconnectionlistener" id="tls_tls_createserver_options_secureconnectionlistener">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.3.0</td>
<td><p>The <code>options</code> parameter now supports <code>net.createServer()</code> options.</p></td></tr>
<tr><td>v9.3.0</td>
<td><p>The <code>options</code> parameter can now include <code>clientCertEngine</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>ALPNProtocols</code> option can be a <code>TypedArray</code> or <code>DataView</code> now.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>ALPN options are supported now.</p></td></tr>
<tr><td>v0.3.2</td>
<td><p><span>Added in: v0.3.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>ALPNProtocols</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView[]></a> | <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a>
An array of strings, <code>Buffer</code>s or <code>TypedArray</code>s or <code>DataView</code>s, or a single
<code>Buffer</code> or <code>TypedArray</code> or <code>DataView</code> containing the supported ALPN
protocols. <code>Buffer</code>s should have the format <code>[len][name][len][name]...</code>
e.g. <code>0x05hello0x05world</code>, where the first byte is the length of the next
protocol name. Passing an array is usually much simpler, e.g.
<code>['hello', 'world']</code>. (Protocols should be ordered by their priority.)</li>
<li><code>clientCertEngine</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of an OpenSSL engine which can provide the
client certificate.</li>
<li><code>enableTrace</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, <a href="#tls_tlssocket_enabletrace"><code>tls.TLSSocket.enableTrace()</code></a> will be
called on new connections. Tracing can be enabled after the secure
connection is established, but this option must be used to trace the secure
connection setup. <strong>Default:</strong> <code>false</code>.</li>
<li><code>handshakeTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Abort the connection if the SSL/TLS handshake
does not finish in the specified number of milliseconds.
A <code>'tlsClientError'</code> is emitted on the <code>tls.Server</code> object whenever
a handshake times out. <strong>Default:</strong> <code>120000</code> (120 seconds).</li>
<li><code>rejectUnauthorized</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If not <code>false</code> the server will reject any
connection which is not authorized with the list of supplied CAs. This
option only has an effect if <code>requestCert</code> is <code>true</code>. <strong>Default:</strong> <code>true</code>.</li>
<li><code>requestCert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code> the server will request a certificate from
clients that connect and attempt to verify that certificate. <strong>Default:</strong>
<code>false</code>.</li>
<li><code>sessionTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of seconds after which a TLS session
created by the server will no longer be resumable. See
<a href="#tls_session_resumption">Session Resumption</a> for more information. <strong>Default:</strong> <code>300</code>.</li>
<li><code>SNICallback(servername, cb)</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A function that will be called if
the client supports SNI TLS extension. Two arguments will be passed when
called: <code>servername</code> and <code>cb</code>. <code>SNICallback</code> should invoke <code>cb(null, ctx)</code>,
where <code>ctx</code> is a <code>SecureContext</code> instance. (<code>tls.createSecureContext(...)</code>
can be used to get a proper <code>SecureContext</code>.) If <code>SNICallback</code> wasn't
provided the default callback with high-level API will be used (see below).</li>
<li><code>ticketKeys</code>: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> 48-bytes of cryptographically strong pseudo-random
data. See <a href="#tls_session_resumption">Session Resumption</a> for more information.</li>
<li>
<p><code>pskCallback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li>socket: <a href="#tls_class_tls_tlssocket" class="type">&#x3C;tls.TLSSocket></a> the server <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instance for
this connection.</li>
<li>identity: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> identity parameter sent from the client.</li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> pre-shared key that must either be
  a buffer or <code>null</code> to stop the negotiation process. Returned PSK must be
compatible with the selected cipher's digest.
When negotiating TLS-PSK (pre-shared keys), this function is called
with the identity provided by the client.
If the return value is <code>null</code> the negotiation process will stop and an
"unknown_psk_identity" alert message will be sent to the other party.
If the server wishes to hide the fact that the PSK identity was not known,
the callback must provide some random data as <code>psk</code> to make the connection
fail with "decrypt_error" before negotiation is finished.
PSK ciphers are disabled by default, and using TLS-PSK thus
requires explicitly specifying a cipher suite with the <code>ciphers</code> option.
More information can be found in the <a href="https://tools.ietf.org/html/rfc4279">RFC 4279</a>.</li>
</ul>
</li>
<li><code>pskIdentityHint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> optional hint to send to a client to help
with selecting the identity during TLS-PSK negotiation. Will be ignored
in TLS 1.3. Upon failing to set pskIdentityHint <code>'tlsClientError'</code> will be
emitted with <code>'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED'</code> code.</li>
<li>...: Any <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> option can be provided. For
servers, the identity options (<code>pfx</code>, <code>key</code>/<code>cert</code> or <code>pskCallback</code>)
are usually required.</li>
<li>...: Any <a href="#net_net_createserver_options_connectionlistener"><code>net.createServer()</code></a> option can be provided.</li>
</ul>
</li>
<li><code>secureConnectionListener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li>Returns: <a href="#tls_class_tls_server" class="type">&#x3C;tls.Server></a></li>
</ul>
<p>Creates a new <a href="#tls_class_tls_server"><code>tls.Server</code></a>. The <code>secureConnectionListener</code>, if provided, is
automatically set as a listener for the <a href="#tls_event_secureconnection"><code>'secureConnection'</code></a> event.</p>
<p>The <code>ticketKeys</code> options is automatically shared between <code>cluster</code> module
workers.</p>
<p>The following illustrates a simple echo server:</p>
<pre><code class="language-js">const tls = require('tls');
const fs = require('fs');

const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem'),

  // This is necessary only if using client certificate authentication.
  requestCert: true,

  // This is necessary only if the client uses a self-signed certificate.
  ca: [ fs.readFileSync('client-cert.pem') ]
};

const server = tls.createServer(options, (socket) => {
  console.log('server connected',
              socket.authorized ? 'authorized' : 'unauthorized');
  socket.write('welcome!\n');
  socket.setEncoding('utf8');
  socket.pipe(socket);
});
server.listen(8000, () => {
  console.log('server bound');
});
</code></pre>
<p>The server can be tested by connecting to it using the example client from
<a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>.</p>
<h2><code>tls.getCiphers()</code><span><a class="mark" href="#tls_tls_getciphers" id="tls_tls_getciphers">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.10.2</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>Returns an array with the names of the supported TLS ciphers. The names are
lower-case for historical reasons, but must be uppercased to be used in
the <code>ciphers</code> option of <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>.</p>
<p>Cipher names that start with <code>'tls_'</code> are for TLSv1.3, all the others are for
TLSv1.2 and below.</p>
<pre><code class="language-js">console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...]
</code></pre>
<h2><code>tls.rootCertificates</code><span><a class="mark" href="#tls_tls_rootcertificates" id="tls_tls_rootcertificates">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.3.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>An immutable array of strings representing the root certificates (in PEM format)
from the bundled Mozilla CA store as supplied by current Node.js version.</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>
<h2><code>tls.DEFAULT_ECDH_CURVE</code><span><a class="mark" href="#tls_tls_default_ecdh_curve" id="tls_tls_default_ecdh_curve">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Default value changed to <code>'auto'</code>.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The default curve name to use for ECDH key agreement in a tls server. The
default value is <code>'auto'</code>. See <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a> for further
information.</p>
<h2><code>tls.DEFAULT_MAX_VERSION</code><span><a class="mark" href="#tls_tls_default_max_version" id="tls_tls_default_max_version">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The default value of the <code>maxVersion</code> option of
<a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>. It can be assigned any of the supported TLS
protocol versions, <code>'TLSv1.3'</code>, <code>'TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>.
<strong>Default:</strong> <code>'TLSv1.3'</code>, unless changed using CLI options. Using
<code>--tls-max-v1.2</code> sets the default to <code>'TLSv1.2'</code>. Using <code>--tls-max-v1.3</code> sets
the default to <code>'TLSv1.3'</code>. If multiple of the options are provided, the
highest maximum is used.</li>
</ul>
<h2><code>tls.DEFAULT_MIN_VERSION</code><span><a class="mark" href="#tls_tls_default_min_version" id="tls_tls_default_min_version">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.4.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The default value of the <code>minVersion</code> option of
<a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a>. It can be assigned any of the supported TLS
protocol versions, <code>'TLSv1.3'</code>, <code>'TLSv1.2'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1'</code>.
<strong>Default:</strong> <code>'TLSv1.2'</code>, unless changed using CLI options. Using
<code>--tls-min-v1.0</code> sets the default to <code>'TLSv1'</code>. Using <code>--tls-min-v1.1</code> sets
the default to <code>'TLSv1.1'</code>. Using <code>--tls-min-v1.3</code> sets the default to
<code>'TLSv1.3'</code>. If multiple of the options are provided, the lowest minimum is
used.</li>
</ul>
<h2>Deprecated APIs<span><a class="mark" href="#tls_deprecated_apis" id="tls_deprecated_apis">#</a></span></h2>
<h3>Class: <code>CryptoStream</code><span><a class="mark" href="#tls_class_cryptostream" id="tls_class_cryptostream">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span><span>Deprecated since: v0.11.3</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</div><p></p>
<p>The <code>tls.CryptoStream</code> class represents a stream of encrypted data. This class
is deprecated and should no longer be used.</p>
<h4><code>cryptoStream.bytesWritten</code><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: <code>SecurePair</code><span><a class="mark" href="#tls_class_securepair" id="tls_class_securepair">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.2</span><span>Deprecated since: v0.11.3</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</div><p></p>
<p>Returned by <a href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options"><code>tls.createSecurePair()</code></a>.</p>
<h4>Event: <code>'secure'</code><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><code>tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])</code><span><a class="mark" href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options" id="tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.0.0</td>
<td><p>ALPN options are supported now.</p></td></tr>
<tr><td>v0.11.3</td>
<td><p><span>Deprecated since: v0.11.3</span></p></td></tr>
<tr><td>v0.3.2</td>
<td><p><span>Added in: v0.3.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</div><p></p>
<ul>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;boolean></a> If not <code>false</code> a server automatically reject
clients with invalid certificates. Only applies when <code>isServer</code> is <code>true</code>.</li>
<li>
<p><code>options</code></p>
<ul>
<li><code>enableTrace</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>secureContext</code>: A TLS context object from <a href="#tls_tls_createsecurecontext_options"><code>tls.createSecureContext()</code></a></li>
<li><code>isServer</code>: If <code>true</code> the TLS socket will be instantiated in server-mode.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>server</code> <a href="#net_class_net_server" class="type">&#x3C;net.Server></a> A <a href="#net_class_net_server"><code>net.Server</code></a> instance</li>
<li><code>requestCert</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>rejectUnauthorized</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>ALPNProtocols</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>SNICallback</code>: See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>session</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> A <code>Buffer</code> instance containing a TLS session.</li>
<li><code>requestOCSP</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, specifies that the OCSP status request
extension will be added to the client hello and an <code>'OCSPResponse'</code> event
will be emitted on the socket before establishing a secure communication.</li>
</ul>
</li>
</ul>
<p>Creates a new secure pair object with two streams, one of which reads and writes
the encrypted data and the other of which reads and writes the cleartext data.
Generally, the encrypted stream is piped to/from an incoming encrypted data
stream and the cleartext one is used as a replacement for the initial encrypted
stream.</p>
<p><code>tls.createSecurePair()</code> returns a <code>tls.SecurePair</code> object with <code>cleartext</code> and
<code>encrypted</code> stream properties.</p>
<p>Using <code>cleartext</code> has the same API as <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a>.</p>
<p>The <code>tls.createSecurePair()</code> method is now deprecated in favor of
<code>tls.TLSSocket()</code>. For example, the code:</p>
<pre><code class="language-js">pair = tls.createSecurePair(/* ... */);
pair.encrypted.pipe(socket);
socket.pipe(pair.encrypted);
</code></pre>
<p>can be replaced by:</p>
<pre><code class="language-js">secureSocket = tls.TLSSocket(socket, options);
</code></pre>
<p>where <code>secureSocket</code> has the same API as <code>pair.cleartext</code>.</p>
<h1>Trace events<span><a class="mark" href="#tracing_trace_events" id="tracing_trace_events">#</a></span></h1>

<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>The <code>trace_events</code> module provides a mechanism to centralize tracing information
generated by V8, Node.js core, and userspace code.</p>
<p>Tracing can be enabled with the <code>--trace-event-categories</code> command-line flag
or by using the <code>trace_events</code> module. The <code>--trace-event-categories</code> flag
accepts a list of comma-separated category names.</p>
<p>The available categories are:</p>
<ul>
<li><code>node</code>: An empty placeholder.</li>
<li><code>node.async_hooks</code>: Enables capture of detailed <a href="async_hooks.html"><code>async_hooks</code></a> trace data.
The <a href="async_hooks.html"><code>async_hooks</code></a> events have a unique <code>asyncId</code> and a special <code>triggerId</code>
<code>triggerAsyncId</code> property.</li>
<li><code>node.bootstrap</code>: Enables capture of Node.js bootstrap milestones.</li>
<li><code>node.console</code>: Enables capture of <code>console.time()</code> and <code>console.count()</code>
output.</li>
<li><code>node.dns.native</code>: Enables capture of trace data for DNS queries.</li>
<li><code>node.environment</code>: Enables capture of Node.js Environment milestones.</li>
<li><code>node.fs.sync</code>: Enables capture of trace data for file system sync methods.</li>
<li>
<p><code>node.perf</code>: Enables capture of <a href="perf_hooks.html">Performance API</a> measurements.</p>
<ul>
<li><code>node.perf.usertiming</code>: Enables capture of only Performance API User Timing
measures and marks.</li>
<li><code>node.perf.timerify</code>: Enables capture of only Performance API timerify
measurements.</li>
</ul>
</li>
<li><code>node.promises.rejections</code>: Enables capture of trace data tracking the number
of unhandled Promise rejections and handled-after-rejections.</li>
<li><code>node.vm.script</code>: Enables capture of trace data for the <code>vm</code> module's
<code>runInNewContext()</code>, <code>runInContext()</code>, and <code>runInThisContext()</code> methods.</li>
<li><code>v8</code>: The <a href="v8.html">V8</a> events are GC, compiling, and execution related.</li>
</ul>
<p>By default the <code>node</code>, <code>node.async_hooks</code>, and <code>v8</code> categories are enabled.</p>
<pre><code class="language-bash">node --trace-event-categories v8,node,node.async_hooks server.js
</code></pre>
<p>Prior versions of Node.js required the use of the <code>--trace-events-enabled</code>
flag to enable trace events. This requirement has been removed. However, the
<code>--trace-events-enabled</code> flag <em>may</em> still be used and will enable the
<code>node</code>, <code>node.async_hooks</code>, and <code>v8</code> trace event categories by default.</p>
<pre><code class="language-bash">node --trace-events-enabled

# is equivalent to

node --trace-event-categories v8,node,node.async_hooks
</code></pre>
<p>Alternatively, trace events may be enabled using the <code>trace_events</code> module:</p>
<pre><code class="language-js">const trace_events = require('trace_events');
const tracing = trace_events.createTracing({ categories: ['node.perf'] });
tracing.enable();  // Enable trace event capture for the 'node.perf' category

// do work

tracing.disable();  // Disable trace event capture for the 'node.perf' category
</code></pre>
<p>Running Node.js with tracing enabled will produce log files that can be opened
in the <a href="https://www.chromium.org/developers/how-tos/trace-event-profiling-tool"><code>chrome://tracing</code></a>
tab of Chrome.</p>
<p>The logging file is by default called <code>node_trace.${rotation}.log</code>, where
<code>${rotation}</code> is an incrementing log-rotation id. The filepath pattern can
be specified with <code>--trace-event-file-pattern</code> that accepts a template
string that supports <code>${rotation}</code> and <code>${pid}</code>:</p>
<pre><code class="language-bash">node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js
</code></pre>
<p>Starting with Node.js 10.0.0, the tracing system uses the same time source
as the one used by <code>process.hrtime()</code>
however the trace-event timestamps are expressed in microseconds,
unlike <code>process.hrtime()</code> which returns nanoseconds.</p>
<p>The features from this module are not available in <a href="#worker_threads_class_worker"><code>Worker</code></a> threads.</p>
<h2>The <code>trace_events</code> module<span><a class="mark" href="#tracing_the_trace_events_module" id="tracing_the_trace_events_module">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<h3><code>Tracing</code> object<span><a class="mark" href="#tracing_tracing_object" id="tracing_tracing_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>The <code>Tracing</code> object is used to enable or disable tracing for sets of
categories. Instances are created using the <code>trace_events.createTracing()</code>
method.</p>
<p>When created, the <code>Tracing</code> object is disabled. Calling the
<code>tracing.enable()</code> method adds the categories to the set of enabled trace event
categories. Calling <code>tracing.disable()</code> will remove the categories from the
set of enabled trace event categories.</p>
<h4><code>tracing.categories</code><span><a class="mark" href="#tracing_tracing_categories" id="tracing_tracing_categories">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>A comma-separated list of the trace event categories covered by this
<code>Tracing</code> object.</p>
<h4><code>tracing.disable()</code><span><a class="mark" href="#tracing_tracing_disable" id="tracing_tracing_disable">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>Disables this <code>Tracing</code> object.</p>
<p>Only trace event categories <em>not</em> covered by other enabled <code>Tracing</code> objects
and <em>not</em> specified by the <code>--trace-event-categories</code> flag will be disabled.</p>
<pre><code class="language-js">const trace_events = require('trace_events');
const t1 = trace_events.createTracing({ categories: ['node', 'v8'] });
const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] });
t1.enable();
t2.enable();

// Prints 'node,node.perf,v8'
console.log(trace_events.getEnabledCategories());

t2.disable(); // Will only disable emission of the 'node.perf' category

// Prints 'node,v8'
console.log(trace_events.getEnabledCategories());
</code></pre>
<h4><code>tracing.enable()</code><span><a class="mark" href="#tracing_tracing_enable" id="tracing_tracing_enable">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>Enables this <code>Tracing</code> object for the set of categories covered by the
<code>Tracing</code> object.</p>
<h4><code>tracing.enabled</code><span><a class="mark" href="#tracing_tracing_enabled" id="tracing_tracing_enabled">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> only if the <code>Tracing</code> object has been enabled.</li>
</ul>
<h3><code>trace_events.createTracing(options)</code><span><a class="mark" href="#tracing_trace_events_createtracing_options" id="tracing_trace_events_createtracing_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>categories</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> An array of trace category names. Values included
in the array are coerced to a string when possible. An error will be
thrown if the value cannot be coerced.</li>
</ul>
</li>
<li>Returns: <a href="#tracing_tracing_object" class="type">&#x3C;Tracing></a>.</li>
</ul>
<p>Creates and returns a <code>Tracing</code> object for the given set of <code>categories</code>.</p>
<pre><code class="language-js">const trace_events = require('trace_events');
const categories = ['node.perf', 'node.async_hooks'];
const tracing = trace_events.createTracing({ categories });
tracing.enable();
// do stuff
tracing.disable();
</code></pre>
<h3><code>trace_events.getEnabledCategories()</code><span><a class="mark" href="#tracing_trace_events_getenabledcategories" id="tracing_trace_events_getenabledcategories">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns a comma-separated list of all currently-enabled trace event
categories. The current set of enabled trace event categories is determined
by the <em>union</em> of all currently-enabled <code>Tracing</code> objects and any categories
enabled using the <code>--trace-event-categories</code> flag.</p>
<p>Given the file <code>test.js</code> below, the command
<code>node --trace-event-categories node.perf test.js</code> will print
<code>'node.async_hooks,node.perf'</code> to the console.</p>
<pre><code class="language-js">const trace_events = require('trace_events');
const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] });
const t2 = trace_events.createTracing({ categories: ['node.perf'] });
const t3 = trace_events.createTracing({ categories: ['v8'] });

t1.enable();
t2.enable();

console.log(trace_events.getEnabledCategories());
</code></pre>
<h1>TTY<span><a class="mark" href="#tty_tty" id="tty_tty">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>tty</code> module provides the <code>tty.ReadStream</code> and <code>tty.WriteStream</code> classes.
In most cases, it will not be necessary or possible to use this module directly.
However, it can be accessed using:</p>
<pre><code class="language-js">const tty = require('tty');
</code></pre>
<p>When Node.js detects that it is being run with a text terminal ("TTY")
attached, <a href="#process_process_stdin"><code>process.stdin</code></a> will, by default, be initialized as an instance of
<code>tty.ReadStream</code> and both <a href="#process_process_stdout"><code>process.stdout</code></a> and <a href="#process_process_stderr"><code>process.stderr</code></a> will, by
default be instances of <code>tty.WriteStream</code>. The preferred method of determining
whether Node.js is being run within a TTY context is to check that the value of
the <code>process.stdout.isTTY</code> property is <code>true</code>:</p>
<pre><code class="language-console">$ 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: <code>tty.ReadStream</code><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>
<ul>
<li>Extends: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Represents the readable side of a TTY. In normal circumstances
<a href="#process_process_stdin"><code>process.stdin</code></a> will be the only <code>tty.ReadStream</code> instance in a Node.js
process and there should be no reason to create additional instances.</p>
<h3><code>readStream.isRaw</code><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><code>readStream.isTTY</code><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><code>readStream.setRawMode(mode)</code><span><a class="mark" href="#tty_readstream_setrawmode_mode" id="tty_readstream_setrawmode_mode">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<ul>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, configures the <code>tty.ReadStream</code> to operate as a
raw device. If <code>false</code>, configures the <code>tty.ReadStream</code> to operate in its
default mode. The <code>readStream.isRaw</code> property will be set to the resulting
mode.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this" class="type">&#x3C;this></a> The read stream instance.</li>
</ul>
<p>Allows configuration of <code>tty.ReadStream</code> so that it operates as a raw device.</p>
<p>When in raw mode, input is always available character-by-character, not
including modifiers. Additionally, all special processing of characters by the
terminal is disabled, including echoing input characters.
<code>CTRL</code>+<code>C</code> will no longer cause a <code>SIGINT</code> when in this mode.</p>
<h2>Class: <code>tty.WriteStream</code><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>
<ul>
<li>Extends: <a href="#net_class_net_socket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Represents the writable side of a TTY. In normal circumstances,
<a href="#process_process_stdout"><code>process.stdout</code></a> and <a href="#process_process_stderr"><code>process.stderr</code></a> will be the only
<code>tty.WriteStream</code> instances created for a Node.js process and there
should be no reason to create additional instances.</p>
<h3>Event: <code>'resize'</code><span><a class="mark" href="#tty_event_resize" id="tty_event_resize">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>The <code>'resize'</code> event is emitted whenever either of the <code>writeStream.columns</code>
or <code>writeStream.rows</code> properties have changed. No arguments are passed to the
listener callback when called.</p>
<pre><code class="language-js">process.stdout.on('resize', () => {
  console.log('screen size has changed!');
  console.log(`${process.stdout.columns}x${process.stdout.rows}`);
});
</code></pre>
<h3><code>writeStream.clearLine(dir[, callback])</code><span><a class="mark" href="#tty_writestream_clearline_dir_callback" id="tty_writestream_clearline_dir_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></p>
<ul>
<li><code>-1</code>: to the left from cursor</li>
<li><code>1</code>: to the right from cursor</li>
<li><code>0</code>: the entire line</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked once the operation completes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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><code>writeStream.clearLine()</code> clears the current line of this <code>WriteStream</code> in a
direction identified by <code>dir</code>.</p>
<h3><code>writeStream.clearScreenDown([callback])</code><span><a class="mark" href="#tty_writestream_clearscreendown_callback" id="tty_writestream_clearscreendown_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked once the operation completes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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><code>writeStream.clearScreenDown()</code> clears this <code>WriteStream</code> from the current
cursor down.</p>
<h3><code>writeStream.columns</code><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><code>writeStream.cursorTo(x[, y][, callback])</code><span><a class="mark" href="#tty_writestream_cursorto_x_y_callback" id="tty_writestream_cursorto_x_y_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>x</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>y</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked once the operation completes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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><code>writeStream.cursorTo()</code> moves this <code>WriteStream</code>'s cursor to the specified
position.</p>
<h3><code>writeStream.getColorDepth([env])</code><span><a class="mark" href="#tty_writestream_getcolordepth_env" id="tty_writestream_getcolordepth_env">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v9.9.0</span>
</div>
<ul>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object containing the environment variables to check. This
enables simulating the usage of a specific terminal. <strong>Default:</strong>
<code>process.env</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Returns:</p>
<ul>
<li><code>1</code> for 2,</li>
<li><code>4</code> for 16,</li>
<li><code>8</code> for 256,</li>
<li><code>24</code> for 16,777,216
colors supported.</li>
</ul>
<p>Use this to determine what colors the terminal supports. Due to the nature of
colors in terminals it is possible to either have false positives or false
negatives. It depends on process information and the environment variables that
may lie about what terminal is used.
It is possible to pass in an <code>env</code> object to simulate the usage of a specific
terminal. This can be useful to check how specific environment settings behave.</p>
<p>To enforce a specific color support, use one of the below environment settings.</p>
<ul>
<li>2 colors: <code>FORCE_COLOR = 0</code> (Disables colors)</li>
<li>16 colors: <code>FORCE_COLOR = 1</code></li>
<li>256 colors: <code>FORCE_COLOR = 2</code></li>
<li>16,777,216 colors: <code>FORCE_COLOR = 3</code></li>
</ul>
<p>Disabling color support is also possible by using the <code>NO_COLOR</code> and
<code>NODE_DISABLE_COLORS</code> environment variables.</p>
<h3><code>writeStream.getWindowSize()</code><span><a class="mark" href="#tty_writestream_getwindowsize" id="tty_writestream_getwindowsize">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number[]></a></li>
</ul>
<p><code>writeStream.getWindowSize()</code> returns the size of the <a href="tty.html">TTY</a>
corresponding to this <code>WriteStream</code>. The array is of the type
<code>[numColumns, numRows]</code> where <code>numColumns</code> and <code>numRows</code> represent the number
of columns and rows in the corresponding <a href="tty.html">TTY</a>.</p>
<h3><code>writeStream.hasColors([count][, env])</code><span><a class="mark" href="#tty_writestream_hascolors_count_env" id="tty_writestream_hascolors_count_env">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.13.0</span>
</div>
<ul>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The number of colors that are requested (minimum 2).
<strong>Default:</strong> 16.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object containing the environment variables to check. This
enables simulating the usage of a specific terminal. <strong>Default:</strong>
<code>process.env</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the <code>writeStream</code> supports at least as many colors as provided
in <code>count</code>. Minimum support is 2 (black and white).</p>
<p>This has the same false positives and negatives as described in
<a href="#tty_writestream_getcolordepth_env"><code>writeStream.getColorDepth()</code></a>.</p>
<pre><code class="language-js">process.stdout.hasColors();
// Returns true or false depending on if `stdout` supports at least 16 colors.
process.stdout.hasColors(256);
// Returns true or false depending on if `stdout` supports at least 256 colors.
process.stdout.hasColors({ TMUX: '1' });
// Returns true.
process.stdout.hasColors(2 ** 24, { TMUX: '1' });
// Returns false (the environment setting pretends to support 2 ** 8 colors).
</code></pre>
<h3><code>writeStream.isTTY</code><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><code>writeStream.moveCursor(dx, dy[, callback])</code><span><a class="mark" href="#tty_writestream_movecursor_dx_dy_callback" id="tty_writestream_movecursor_dx_dy_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.7.0</td>
<td><p>The stream's write() callback and return value are exposed.</p></td></tr>
<tr><td>v0.7.7</td>
<td><p><span>Added in: v0.7.7</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>dx</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>dy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked once the operation completes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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><code>writeStream.moveCursor()</code> moves this <code>WriteStream</code>'s cursor <em>relative</em> to its
current position.</p>
<h3><code>writeStream.rows</code><span><a class="mark" href="#tty_writestream_rows" id="tty_writestream_rows">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<p>A <code>number</code> specifying the number of rows the TTY currently has. This property
is updated whenever the <code>'resize'</code> event is emitted.</p>
<h2><code>tty.isatty(fd)</code><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">&#x3C;number></a> A numeric file descriptor</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <code>tty.isatty()</code> method returns <code>true</code> if the given <code>fd</code> is associated with
a TTY and <code>false</code> if it is not, including whenever <code>fd</code> is not a non-negative
integer.</p>
<h1>UDP/datagram sockets<span><a class="mark" href="#dgram_udp_datagram_sockets" id="dgram_udp_datagram_sockets">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>

<p>The <code>dgram</code> module provides an implementation of UDP datagram sockets.</p>
<pre><code class="language-js">const dgram = require('dgram');
const server = dgram.createSocket('udp4');

server.on('error', (err) => {
  console.log(`server error:\n${err.stack}`);
  server.close();
});

server.on('message', (msg, rinfo) => {
  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});

server.on('listening', () => {
  const address = server.address();
  console.log(`server listening ${address.address}:${address.port}`);
});

server.bind(41234);
// Prints: server listening 0.0.0.0:41234
</code></pre>
<h2>Class: <code>dgram.Socket</code><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>
<ul>
<li>Extends: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>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: <code>'close'</code><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: <code>'connect'</code><span><a class="mark" href="#dgram_event_connect" id="dgram_event_connect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>The <code>'connect'</code> event is emitted after a socket is associated to a remote
address as a result of a successful <a href="#dgram_socket_connect_port_address_callback"><code>connect()</code></a> call.</p>
<h3>Event: <code>'error'</code><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">&#x3C;Error></a></li>
</ul>
<p>The <code>'error'</code> event is emitted whenever any error occurs. The event handler
function is passed a single <code>Error</code> object.</p>
<h3>Event: <code>'listening'</code><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 once the <code>dgram.Socket</code> is addressable and
can receive data. This happens either explicitly with <code>socket.bind()</code> or
implicitly the first time data is sent using <code>socket.send()</code>.
Until the <code>dgram.Socket</code> is listening, the underlying system resources do not
exist and calls such as <code>socket.address()</code> and <code>socket.setTTL()</code> will fail.</p>
<h3>Event: <code>'message'</code><span><a class="mark" href="#dgram_event_message" id="dgram_event_message">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<p>The <code>'message'</code> event is emitted when a new datagram is available on a socket.
The event handler function is passed two arguments: <code>msg</code> and <code>rinfo</code>.</p>
<ul>
<li><code>msg</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> The message.</li>
<li>
<p><code>rinfo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Remote address information.</p>
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;number></a> The message size.</li>
</ul>
</li>
</ul>
<h3><code>socket.addMembership(multicastAddress[, multicastInterface])</code><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">&#x3C;string></a></li>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Tells the kernel to join a multicast group at the given <code>multicastAddress</code> and
<code>multicastInterface</code> using the <code>IP_ADD_MEMBERSHIP</code> socket option. If the
<code>multicastInterface</code> argument is not specified, the operating system will choose
one interface and will add membership to it. To add membership to every
available interface, call <code>addMembership</code> multiple times, once per interface.</p>
<p>When sharing a UDP socket across multiple <code>cluster</code> workers, the
<code>socket.addMembership()</code> function must be called only once or an
<code>EADDRINUSE</code> error will occur:</p>
<pre><code class="language-js">const cluster = require('cluster');
const dgram = require('dgram');
if (cluster.isMaster) {
  cluster.fork(); // Works ok.
  cluster.fork(); // Fails with EADDRINUSE.
} else {
  const s = dgram.createSocket('udp4');
  s.bind(1234, () => {
    s.addMembership('224.0.0.114');
  });
}
</code></pre>
<h3><code>socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code><span><a class="mark" href="#dgram_socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface" id="dgram_socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li><code>sourceAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>groupAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Tells the kernel to join a source-specific multicast channel at the given
<code>sourceAddress</code> and <code>groupAddress</code>, using the <code>multicastInterface</code> with the
<code>IP_ADD_SOURCE_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>socket.addSourceSpecificMembership()</code> multiple times, once per interface.</p>
<h3><code>socket.address()</code><span><a class="mark" href="#dgram_socket_address" id="dgram_socket_address">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns an object containing the address information for a socket.
For UDP sockets, this object will contain <code>address</code>, <code>family</code> and <code>port</code>
properties.</p>
<h3><code>socket.bind([port][, address][, callback])</code><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">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v0.10</td>
<td><p>The method was changed to an asynchronous execution model. Legacy code would need to be changed to pass a callback function to the method call.</p></td></tr>
<tr><td>v0.1.99</td>
<td><p><span>Added in: v0.1.99</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;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>Specifying both a <code>'listening'</code> event listener and passing a
<code>callback</code> to the <code>socket.bind()</code> method is not harmful but not very
useful.</p>
<p>A bound datagram socket keeps the Node.js process running to receive
datagram messages.</p>
<p>If binding fails, an <code>'error'</code> event is generated. In rare case (e.g.
attempting to bind with a closed socket), an <a href="#errors_class_error"><code>Error</code></a> may be thrown.</p>
<p>Example of a UDP server listening on port 41234:</p>
<pre><code class="language-js">const dgram = require('dgram');
const server = dgram.createSocket('udp4');

server.on('error', (err) => {
  console.log(`server error:\n${err.stack}`);
  server.close();
});

server.on('message', (msg, rinfo) => {
  console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});

server.on('listening', () => {
  const address = server.address();
  console.log(`server listening ${address.address}:${address.port}`);
});

server.bind(41234);
// Prints: server listening 0.0.0.0:41234
</code></pre>
<h3><code>socket.bind(options[, callback])</code><span><a class="mark" href="#dgram_socket_bind_options_callback" id="dgram_socket_bind_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Required. Supports the following properties:</p>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
<li><code>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></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">&#x3C;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>The <code>options</code> object may contain a <code>fd</code> property. When a <code>fd</code> greater
than <code>0</code> is set, it will wrap around an existing socket with the given
file descriptor. In this case, the properties of <code>port</code> and <code>address</code>
will be ignored.</p>
<p>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
used when using <code>dgram.Socket</code> objects with the <a href="cluster.html"><code>cluster</code></a> module. When
<code>exclusive</code> is set to <code>false</code> (the default), cluster workers will use the same
underlying socket handle allowing connection handling duties to be shared.
When <code>exclusive</code> is <code>true</code>, however, the handle is not shared and attempted
port sharing results in an error.</p>
<p>A bound datagram socket keeps the Node.js process running to receive
datagram messages.</p>
<p>If binding fails, an <code>'error'</code> event is generated. In rare case (e.g.
attempting to bind with a closed socket), an <a href="#errors_class_error"><code>Error</code></a> may be thrown.</p>
<p>An example socket listening on an exclusive port is shown below.</p>
<pre><code class="language-js">socket.bind({
  address: 'localhost',
  port: 8000,
  exclusive: true
});
</code></pre>
<h3><code>socket.close([callback])</code><span><a class="mark" href="#dgram_socket_close_callback" id="dgram_socket_close_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called when the socket has been closed.</li>
</ul>
<p>Close the underlying socket and stop listening for data on it. If a callback is
provided, it is added as a listener for the <a href="#dgram_event_close"><code>'close'</code></a> event.</p>
<h3><code>socket.connect(port[, address][, callback])</code><span><a class="mark" href="#dgram_socket_connect_port_address_callback" id="dgram_socket_connect_port_address_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called when the connection is completed or on error.</li>
</ul>
<p>Associates the <code>dgram.Socket</code> to a remote address and port. Every
message sent by this handle is automatically sent to that destination. Also,
the socket will only receive messages from that remote peer.
Trying to call <code>connect()</code> on an already connected socket will result
in an <a href="#errors_err_socket_dgram_is_connected"><code>ERR_SOCKET_DGRAM_IS_CONNECTED</code></a> exception. If <code>address</code> is not
provided, <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. Once the connection is complete, a <code>'connect'</code> event
is emitted and the optional <code>callback</code> function is called. In case of failure,
the <code>callback</code> is called or, failing this, an <code>'error'</code> event is emitted.</p>
<h3><code>socket.disconnect()</code><span><a class="mark" href="#dgram_socket_disconnect" id="dgram_socket_disconnect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>A synchronous function that disassociates a connected <code>dgram.Socket</code> from
its remote address. Trying to call <code>disconnect()</code> on an already disconnected
socket will result in an <a href="#errors_err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a> exception.</p>
<h3><code>socket.dropMembership(multicastAddress[, multicastInterface])</code><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">&#x3C;string></a></li>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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><code>socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code><span><a class="mark" href="#dgram_socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface" id="dgram_socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li><code>sourceAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>groupAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>multicastInterface</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Instructs the kernel to leave a source-specific multicast channel at the given
<code>sourceAddress</code> and <code>groupAddress</code> using the <code>IP_DROP_SOURCE_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><code>socket.getRecvBufferSize()</code><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">&#x3C;number></a> the <code>SO_RCVBUF</code> socket receive buffer size in bytes.</li>
</ul>
<h3><code>socket.getSendBufferSize()</code><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">&#x3C;number></a> the <code>SO_SNDBUF</code> socket send buffer size in bytes.</li>
</ul>
<h3><code>socket.ref()</code><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>
<ul>
<li>Returns: <a href="#dgram_class_dgram_socket" class="type">&#x3C;dgram.Socket></a></li>
</ul>
<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><code>socket.remoteAddress()</code><span><a class="mark" href="#dgram_socket_remoteaddress" id="dgram_socket_remoteaddress">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns an object containing the <code>address</code>, <code>family</code>, and <code>port</code> of the remote
endpoint. It throws an <a href="#errors_err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a> exception if the
socket is not connected.</p>
<h3><code>socket.send(msg[, offset, length][, port][, address][, callback])</code><span><a class="mark" href="#dgram_socket_send_msg_offset_length_port_address_callback" id="dgram_socket_send_msg_offset_length_port_address_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.0.0</td>
<td><p>Added support for sending data on connected sockets.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>msg</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>address</code> parameter is always optional now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>On success, <code>callback</code> will now be called with an <code>error</code> argument of <code>null</code> rather than <code>0</code>.</p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>msg</code> parameter can be an array now. Also, the <code>offset</code> and <code>length</code> parameters are optional now.</p></td></tr>
<tr><td>v0.1.99</td>
<td><p><span>Added in: v0.1.99</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>msg</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;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">&#x3C;integer></a> Offset in the buffer where the message starts.</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Number of bytes in the message.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Destination port.</li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Destination host name 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">&#x3C;Function></a> Called when the message has been sent.</li>
</ul>
<p>Broadcasts a datagram on the socket.
For connectionless sockets, the destination <code>port</code> and <code>address</code> must be
specified. Connected sockets, on the other hand, will use their associated
remote endpoint, so the <code>port</code> and <code>address</code> arguments must not be set.</p>
<p>The <code>msg</code> argument contains the message to be sent.
Depending on its type, different behavior can apply. If <code>msg</code> is a <code>Buffer</code>
or <code>Uint8Array</code>,
the <code>offset</code> and <code>length</code> specify the offset within the <code>Buffer</code> where the
message begins and the number of bytes in the message, respectively.
If <code>msg</code> is a <code>String</code>, then it is automatically converted to a <code>Buffer</code>
with <code>'utf8'</code> encoding. With messages that
contain multi-byte characters, <code>offset</code> and <code>length</code> will be calculated with
respect to <a href="#buffer_class_method_buffer_bytelength_string_encoding">byte length</a> and not the character position.
If <code>msg</code> is an array, <code>offset</code> and <code>length</code> must not be specified.</p>
<p>The <code>address</code> argument is a string. If the value of <code>address</code> is a host name,
DNS will be used to resolve the address of the host. If <code>address</code> is not
provided or otherwise falsy, <code>'127.0.0.1'</code> (for <code>udp4</code> sockets) or <code>'::1'</code>
(for <code>udp6</code> sockets) will be used by default.</p>
<p>If the socket has not been previously bound with a call to <code>bind</code>, the socket
is assigned a random port number and is bound to the "all interfaces" address
(<code>'0.0.0.0'</code> for <code>udp4</code> sockets, <code>'::0'</code> for <code>udp6</code> sockets.)</p>
<p>An optional <code>callback</code> function may be specified to as a way of reporting
DNS errors or for determining when it is safe to reuse the <code>buf</code> object.
DNS lookups delay the time to send for at least one tick of the
Node.js event loop.</p>
<p>The only way to know for sure that the datagram has been sent is by using a
<code>callback</code>. If an error occurs and a <code>callback</code> is given, the error will be
passed as the first argument to the <code>callback</code>. If a <code>callback</code> is not given,
the error is emitted as an <code>'error'</code> event on the <code>socket</code> object.</p>
<p>Offset and length are optional but both <em>must</em> be set if either are used.
They are supported only when the first argument is a <code>Buffer</code> or <code>Uint8Array</code>.</p>
<p>Example of sending a UDP packet to a port on <code>localhost</code>;</p>
<pre><code class="language-js">const dgram = require('dgram');
const message = Buffer.from('Some bytes');
const client = dgram.createSocket('udp4');
client.send(message, 41234, 'localhost', (err) => {
  client.close();
});
</code></pre>
<p>Example of sending a UDP packet composed of multiple buffers to a port on
<code>127.0.0.1</code>;</p>
<pre><code class="language-js">const dgram = require('dgram');
const buf1 = Buffer.from('Some ');
const buf2 = Buffer.from('bytes');
const client = dgram.createSocket('udp4');
client.send([buf1, buf2], 41234, (err) => {
  client.close();
});
</code></pre>
<p>Sending multiple buffers might be faster or slower depending on the
application and operating system. Run benchmarks to
determine the optimal strategy on a case-by-case basis. Generally speaking,
however, sending multiple buffers is faster.</p>
<p>Example of sending a UDP packet using a socket connected to a port on
<code>localhost</code>:</p>
<pre><code class="language-js">const dgram = require('dgram');
const message = Buffer.from('Some bytes');
const client = dgram.createSocket('udp4');
client.connect(41234, 'localhost', (err) => {
  client.send(message, (err) => {
    client.close();
  });
});
</code></pre>
<h4>Note about UDP datagram size<span><a class="mark" href="#dgram_note_about_udp_datagram_size" id="dgram_note_about_udp_datagram_size">#</a></span></h4>
<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><code>socket.setBroadcast(flag)</code><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">&#x3C;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><code>socket.setMulticastInterface(multicastInterface)</code><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">&#x3C;string></a></li>
</ul>
<p><em>All references to scope in this section are referring to
<a href="https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses">IPv6 Zone Indices</a>, which are defined by <a href="https://tools.ietf.org/html/rfc4007">RFC 4007</a>. In string form, an IP
with a scope index is written as <code>'IP%scope'</code> where scope is an interface name
or interface number.</em></p>
<p>Sets the default outgoing multicast interface of the socket to a chosen
interface or back to system interface selection. The <code>multicastInterface</code> must
be a valid string representation of an IP from the socket's family.</p>
<p>For IPv4 sockets, this should be the IP configured for the desired physical
interface. All packets sent to multicast on the socket will be sent on the
interface determined by the most recent successful use of this call.</p>
<p>For IPv6 sockets, <code>multicastInterface</code> should include a scope to indicate the
interface as in the examples that follow. In IPv6, individual <code>send</code> calls can
also use explicit scope in addresses, so only packets sent to a multicast
address without specifying an explicit scope are affected by the most recent
successful use of this call.</p>
<h4>Example: IPv6 outgoing multicast interface<span><a class="mark" href="#dgram_example_ipv6_outgoing_multicast_interface" id="dgram_example_ipv6_outgoing_multicast_interface">#</a></span></h4>
<p>On most systems, where scope format uses the interface name:</p>
<pre><code class="language-js">const socket = dgram.createSocket('udp6');

socket.bind(1234, () => {
  socket.setMulticastInterface('::%eth1');
});
</code></pre>
<p>On Windows, where scope format uses an interface number:</p>
<pre><code class="language-js">const socket = dgram.createSocket('udp6');

socket.bind(1234, () => {
  socket.setMulticastInterface('::%2');
});
</code></pre>
<h4>Example: IPv4 outgoing multicast interface<span><a class="mark" href="#dgram_example_ipv4_outgoing_multicast_interface" id="dgram_example_ipv4_outgoing_multicast_interface">#</a></span></h4>
<p>All systems use an IP of the host on the desired physical interface:</p>
<pre><code class="language-js">const socket = dgram.createSocket('udp4');

socket.bind(1234, () => {
  socket.setMulticastInterface('10.0.0.2');
});
</code></pre>
<h4>Call results<span><a class="mark" href="#dgram_call_results" id="dgram_call_results">#</a></span></h4>
<p>A call on a socket that is not ready to send or no longer open may throw a <em>Not
running</em> <a href="#errors_class_error"><code>Error</code></a>.</p>
<p>If <code>multicastInterface</code> can not be parsed into an IP then an <em>EINVAL</em>
<a href="#errors_class_systemerror"><code>System Error</code></a> is thrown.</p>
<p>On IPv4, if <code>multicastInterface</code> is a valid address but does not match any
interface, or if the address does not match the family then
a <a href="#errors_class_systemerror"><code>System Error</code></a> such as <code>EADDRNOTAVAIL</code> or <code>EPROTONOSUP</code> is thrown.</p>
<p>On IPv6, most errors with specifying or omitting scope will result in the socket
continuing to use (or returning to) the system's default interface selection.</p>
<p>A socket's address family's ANY address (IPv4 <code>'0.0.0.0'</code> or IPv6 <code>'::'</code>) can be
used to return control of the sockets default outgoing interface to the system
for future multicast packets.</p>
<h3><code>socket.setMulticastLoopback(flag)</code><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">&#x3C;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><code>socket.setMulticastTTL(ttl)</code><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">&#x3C;integer></a></li>
</ul>
<p>Sets the <code>IP_MULTICAST_TTL</code> socket option. While TTL generally stands for
"Time to Live", in this context it specifies the number of IP hops that a
packet is allowed to travel through, specifically for multicast traffic. Each
router or gateway that forwards a packet decrements the TTL. If the TTL is
decremented to 0 by a router, it will not be forwarded.</p>
<p>The <code>ttl</code> argument may be between 0 and 255. The default on most systems is <code>1</code>.</p>
<h3><code>socket.setRecvBufferSize(size)</code><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">&#x3C;integer></a></li>
</ul>
<p>Sets the <code>SO_RCVBUF</code> socket option. Sets the maximum socket receive buffer
in bytes.</p>
<h3><code>socket.setSendBufferSize(size)</code><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">&#x3C;integer></a></li>
</ul>
<p>Sets the <code>SO_SNDBUF</code> socket option. Sets the maximum socket send buffer
in bytes.</p>
<h3><code>socket.setTTL(ttl)</code><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">&#x3C;integer></a></li>
</ul>
<p>Sets the <code>IP_TTL</code> socket option. While TTL generally stands for "Time to Live",
in this context it specifies the number of IP hops that a packet is allowed to
travel through. Each router or gateway that forwards a packet decrements the
TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
Changing TTL values is typically done for network probes or when multicasting.</p>
<p>The <code>ttl</code> argument may be between between 1 and 255. The default on most systems
is 64.</p>
<h3><code>socket.unref()</code><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>
<ul>
<li>Returns: <a href="#dgram_class_dgram_socket" class="type">&#x3C;dgram.Socket></a></li>
</ul>
<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>
<h2><code>dgram</code> module functions<span><a class="mark" href="#dgram_dgram_module_functions" id="dgram_dgram_module_functions">#</a></span></h2>
<h3><code>dgram.createSocket(options[, callback])</code><span><a class="mark" href="#dgram_dgram_createsocket_options_callback" id="dgram_dgram_createsocket_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.4.0</td>
<td><p>The <code>ipv6Only</code> option is supported.</p></td></tr>
<tr><td>v8.7.0</td>
<td><p>The <code>recvBufferSize</code> and <code>sendBufferSize</code> options are supported now.</p></td></tr>
<tr><td>v8.6.0</td>
<td><p>The <code>lookup</code> option is supported.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Available options are:</p>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;boolean></a> When <code>true</code> <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will reuse the
address, even if another process has already bound a socket on it.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>ipv6Only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Setting <code>ipv6Only</code> to <code>true</code> will
disable dual-stack support, i.e., binding to address <code>::</code> won't make
<code>0.0.0.0</code> be bound. <strong>Default:</strong> <code>false</code>.</li>
<li><code>recvBufferSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;Function></a> Custom lookup function. <strong>Default:</strong> <a href="#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Attached as a listener for <code>'message'</code> events. Optional.</li>
<li>Returns: <a href="#dgram_class_dgram_socket" class="type">&#x3C;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><code>dgram.createSocket(type[, callback])</code><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">&#x3C;string></a> Either <code>'udp4'</code> or <code>'udp6'</code>.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Attached as a listener to <code>'message'</code> events.</li>
<li>Returns: <a href="#dgram_class_dgram_socket" class="type">&#x3C;dgram.Socket></a></li>
</ul>
<p>Creates a <code>dgram.Socket</code> object of the specified <code>type</code>.</p>
<p>Once the socket is created, calling <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will instruct the
socket to begin listening for datagram messages. When <code>address</code> and <code>port</code> are
not passed to <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> the method will bind the socket to the "all
interfaces" address on a random port (it does the right thing for both <code>udp4</code>
and <code>udp6</code> sockets). The bound address and port can be retrieved using
<a href="#dgram_socket_address"><code>socket.address().address</code></a> and <a href="#dgram_socket_address"><code>socket.address().port</code></a>.</p>
<h1>URL<span><a class="mark" href="#url_url" id="url_url">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>url</code> module provides utilities for URL resolution and parsing. It can be
accessed using:</p>
<pre><code class="language-js">const url = require('url');
</code></pre>
<h2>URL strings and URL objects<span><a class="mark" href="#url_url_strings_and_url_objects" id="url_url_strings_and_url_objects">#</a></span></h2>
<p>A URL string is a structured string containing multiple meaningful components.
When parsed, a URL object is returned containing properties for each of these
components.</p>
<p>The <code>url</code> module provides two APIs for working with URLs: a legacy API that is
Node.js specific, and a newer API that implements the same
<a href="https://url.spec.whatwg.org/">WHATWG URL Standard</a> used by web browsers.</p>
<p>A comparison between the WHATWG and Legacy APIs is provided below. Above the URL
<code>'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</code>, properties
of an object returned by the legacy <code>url.parse()</code> are shown. Below it are
properties of a WHATWG <code>URL</code> object.</p>
<p>WHATWG URL's <code>origin</code> property includes <code>protocol</code> and <code>host</code>, but not
<code>username</code> or <code>password</code>.</p>
<pre><code class="language-text">┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                              href                                              │
├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
│ protocol │  │        auth         │          host          │           path            │ hash  │
│          │  │                     ├─────────────────┬──────┼──────────┬────────────────┤       │
│          │  │                     │    hostname     │ port │ pathname │     search     │       │
│          │  │                     │                 │      │          ├─┬──────────────┤       │
│          │  │                     │                 │      │          │ │    query     │       │
"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash "
│          │  │          │          │    hostname     │ port │          │                │       │
│          │  │          │          ├─────────────────┴──────┤          │                │       │
│ protocol │  │ username │ password │          host          │          │                │       │
├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       │
│   origin    │                     │         origin         │ pathname │     search     │ hash  │
├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
│                                              href                                              │
└────────────────────────────────────────────────────────────────────────────────────────────────┘
(All spaces in the "" line should be ignored. They are purely for formatting.)
</code></pre>
<p>Parsing the URL string using the WHATWG API:</p>
<pre><code class="language-js">const myURL =
  new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
</code></pre>
<p>Parsing the URL string using the Legacy API:</p>
<pre><code class="language-js">const url = require('url');
const myURL =
  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
</code></pre>
<h2>The WHATWG URL API<span><a class="mark" href="#url_the_whatwg_url_api" id="url_the_whatwg_url_api">#</a></span></h2>
<h3>Class: <code>URL</code><span><a class="mark" href="#url_class_url" id="url_class_url">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The class is now available on the global object.</p></td></tr>
<tr><td>v7.0.0, v6.13.0</td>
<td><p><span>Added in: v7.0.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Browser-compatible <code>URL</code> class, implemented by following the WHATWG URL
Standard. <a href="https://url.spec.whatwg.org/#example-url-parsing">Examples of parsed URLs</a> may be found in the Standard itself.
The <code>URL</code> class is also available on the global object.</p>
<p>In accordance with browser conventions, all properties of <code>URL</code> objects
are implemented as getters and setters on the class prototype, rather than as
data properties on the object itself. Thus, unlike <a href="#url_legacy_urlobject">legacy <code>urlObject</code></a>s,
using the <code>delete</code> keyword on any properties of <code>URL</code> objects (e.g. <code>delete myURL.protocol</code>, <code>delete myURL.pathname</code>, etc) has no effect but will still
return <code>true</code>.</p>
<h4>Constructor: <code>new URL(input[, base])</code><span><a class="mark" href="#url_constructor_new_url_input_base" id="url_constructor_new_url_input_base">#</a></span></h4>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The absolute or relative input URL to parse. If <code>input</code>
is relative, then <code>base</code> is required. If <code>input</code> is absolute, the <code>base</code>
is ignored.</li>
<li><code>base</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> The base URL to resolve against if the <code>input</code> is not
absolute.</li>
</ul>
<p>Creates a new <code>URL</code> object by parsing the <code>input</code> relative to the <code>base</code>. If
<code>base</code> is passed as a string, it will be parsed equivalent to <code>new URL(base)</code>.</p>
<pre><code class="language-js">const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/foo
</code></pre>
<p>The URL constructor is accessible as a property on the global object.
It can also be imported from the built-in url module:</p>
<pre><code class="language-js">console.log(URL === require('url').URL); // Prints 'true'.
</code></pre>
<p>A <code>TypeError</code> will be thrown if the <code>input</code> or <code>base</code> are not valid URLs. Note
that an effort will be made to coerce the given values into strings. For
instance:</p>
<pre><code class="language-js">const myURL = new URL({ toString: () => 'https://example.org/' });
// https://example.org/
</code></pre>
<p>Unicode characters appearing within the host name of <code>input</code> will be
automatically converted to ASCII using the <a href="https://tools.ietf.org/html/rfc5891#section-4.4">Punycode</a> algorithm.</p>
<pre><code class="language-js">const myURL = new URL('https://測試');
// https://xn--g6w251d/
</code></pre>
<p>This feature is only available if the <code>node</code> executable was compiled with
<a href="#intl_options_for_building_node_js">ICU</a> enabled. If not, the domain names are passed through unchanged.</p>
<p>In cases where it is not known in advance if <code>input</code> is an absolute URL
and a <code>base</code> is provided, it is advised to validate that the <code>origin</code> of
the <code>URL</code> object is what is expected.</p>
<pre><code class="language-js">let myURL = new URL('http://Example.com/', 'https://example.org/');
// http://example.com/

myURL = new URL('https://Example.com/', 'https://example.org/');
// https://example.com/

myURL = new URL('foo://Example.com/', 'https://example.org/');
// foo://Example.com/

myURL = new URL('http:Example.com/', 'https://example.org/');
// http://example.com/

myURL = new URL('https:Example.com/', 'https://example.org/');
// https://example.org/Example.com/

myURL = new URL('foo:Example.com/', 'https://example.org/');
// foo:Example.com/
</code></pre>
<h4><code>url.hash</code><span><a class="mark" href="#url_url_hash" id="url_url_hash">#</a></span></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Gets and sets the fragment portion of the URL.</p>
<pre><code class="language-js">const myURL = new URL('https://example.org/foo#bar');
console.log(myURL.hash);
// Prints #bar

myURL.hash = 'baz';
console.log(myURL.href);
// Prints https://example.org/foo#baz
</code></pre>
<p>Invalid URL characters included in the value assigned to the <code>hash</code> property
are <a href="#whatwg-percent-encoding">percent-encoded</a>. 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><code>url.host</code><span><a class="mark" href="#url_url_host" id="url_url_host">#</a></span></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Gets and sets the host portion of the URL.</p>
<pre><code class="language-js">const myURL = new URL('https://example.org:81/foo');
console.log(myURL.host);
// Prints example.org:81

myURL.host = 'example.com:82';
console.log(myURL.href);
// Prints https://example.com:82/foo
</code></pre>
<p>Invalid host values assigned to the <code>host</code> property are ignored.</p>
<h4><code>url.hostname</code><span><a class="mark" href="#url_url_hostname" id="url_url_hostname">#</a></span></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Gets and sets the host name portion of the URL. The key difference between
<code>url.host</code> and <code>url.hostname</code> is that <code>url.hostname</code> does <em>not</em> include the
port.</p>
<pre><code class="language-js">const myURL = new URL('https://example.org:81/foo');
console.log(myURL.hostname);
// Prints example.org

myURL.hostname = 'example.com:82';
console.log(myURL.href);
// Prints https://example.com:81/foo
</code></pre>
<p>Invalid host name values assigned to the <code>hostname</code> property are ignored.</p>
<h4><code>url.href</code><span><a class="mark" href="#url_url_href" id="url_url_href">#</a></span></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Gets and sets the serialized URL.</p>
<pre><code class="language-js">const myURL = new URL('https://example.org/foo');
console.log(myURL.href);
// Prints https://example.org/foo

myURL.href = 'https://example.com/bar';
console.log(myURL.href);
// Prints https://example.com/bar
</code></pre>
<p>Getting the value of the <code>href</code> property is equivalent to calling
<a href="#url_url_tostring"><code>url.toString()</code></a>.</p>
<p>Setting the value of this property to a new value is equivalent to creating a
new <code>URL</code> object using <a href="#url_constructor_new_url_input_base"><code>new URL(value)</code></a>. Each of the <code>URL</code>
object's properties will be modified.</p>
<p>If the value assigned to the <code>href</code> property is not a valid URL, a <code>TypeError</code>
will be thrown.</p>
<h4><code>url.origin</code><span><a class="mark" href="#url_url_origin" id="url_url_origin">#</a></span></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Gets the read-only serialization of the URL's origin.</p>
<pre><code class="language-js">const myURL = new URL('https://example.org/foo/bar?baz');
console.log(myURL.origin);
// Prints https://example.org
</code></pre>
<pre><code class="language-js">const idnURL = new URL('https://測試');
console.log(idnURL.origin);
// Prints https://xn--g6w251d

console.log(idnURL.hostname);
// Prints xn--g6w251d
</code></pre>
<h4><code>url.password</code><span><a class="mark" href="#url_url_password" id="url_url_password">#</a></span></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Gets and sets the password portion of the URL.</p>
<pre><code class="language-js">const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.password);
// Prints xyz

myURL.password = '123';
console.log(myURL.href);
// Prints https://abc:123@example.com
</code></pre>
<p>Invalid URL characters included in the value assigned to the <code>password</code> property
are <a href="#whatwg-percent-encoding">percent-encoded</a>. 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><code>url.pathname</code><span><a class="mark" href="#url_url_pathname" id="url_url_pathname">#</a></span></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Gets and sets the path portion of the URL.</p>
<pre><code class="language-js">const myURL = new URL('https://example.org/abc/xyz?123');
console.log(myURL.pathname);
// Prints /abc/xyz

myURL.pathname = '/abcdef';
console.log(myURL.href);
// Prints https://example.org/abcdef?123
</code></pre>
<p>Invalid URL characters included in the value assigned to the <code>pathname</code>
property are <a href="#whatwg-percent-encoding">percent-encoded</a>. 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><code>url.port</code><span><a class="mark" href="#url_url_port" id="url_url_port">#</a></span></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Gets and sets the port portion of the URL.</p>
<p>The port value may be a number or a string containing a number in the range
<code>0</code> to <code>65535</code> (inclusive). Setting the value to the default port of the
<code>URL</code> objects given <code>protocol</code> will result in the <code>port</code> value becoming
the empty string (<code>''</code>).</p>
<p>The port value can be an empty string in which case the port depends on
the protocol/scheme:</p>





































<table><thead><tr><th>protocol</th><th>port</th></tr></thead><tbody><tr><td>"ftp"</td><td>21</td></tr><tr><td>"file"</td><td></td></tr><tr><td>"gopher"</td><td>70</td></tr><tr><td>"http"</td><td>80</td></tr><tr><td>"https"</td><td>443</td></tr><tr><td>"ws"</td><td>80</td></tr><tr><td>"wss"</td><td>443</td></tr></tbody></table>
<p>Upon assigning a value to the port, the value will first be converted to a
string using <code>.toString()</code>.</p>
<p>If that string is invalid but it begins with a number, the leading number is
assigned to <code>port</code>.
If the number lies outside the range denoted above, it is ignored.</p>
<pre><code class="language-js">const myURL = new URL('https://example.org:8888');
console.log(myURL.port);
// Prints 8888

// Default ports are automatically transformed to the empty string
// (HTTPS protocol's default port is 443)
myURL.port = '443';
console.log(myURL.port);
// Prints the empty string
console.log(myURL.href);
// Prints https://example.org/

myURL.port = 1234;
console.log(myURL.port);
// Prints 1234
console.log(myURL.href);
// Prints https://example.org:1234/

// Completely invalid port strings are ignored
myURL.port = 'abcd';
console.log(myURL.port);
// Prints 1234

// Leading numbers are treated as a port number
myURL.port = '5678abcd';
console.log(myURL.port);
// Prints 5678

// Non-integers are truncated
myURL.port = 1234.5678;
console.log(myURL.port);
// Prints 1234

// Out-of-range numbers which are not represented in scientific notation
// will be ignored.
myURL.port = 1e10; // 10000000000, will be range-checked as described below
console.log(myURL.port);
// Prints 1234
</code></pre>
<p>Numbers which contain a decimal point,
such as floating-point numbers or numbers in scientific notation,
are not an exception to this rule.
Leading numbers up to the decimal point will be set as the URL's port,
assuming they are valid:</p>
<pre><code class="language-js">myURL.port = 4.567e21;
console.log(myURL.port);
// Prints 4 (because it is the leading number in the string '4.567e21')
</code></pre>
<h4><code>url.protocol</code><span><a class="mark" href="#url_url_protocol" id="url_url_protocol">#</a></span></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Gets and sets the protocol portion of the URL.</p>
<pre><code class="language-js">const myURL = new URL('https://example.org');
console.log(myURL.protocol);
// Prints https:

myURL.protocol = 'ftp';
console.log(myURL.href);
// Prints ftp://example.org/
</code></pre>
<p>Invalid URL protocol values assigned to the <code>protocol</code> property are ignored.</p>
<h5>Special schemes<span><a class="mark" href="#url_special_schemes" id="url_special_schemes">#</a></span></h5>
<p>The <a href="https://url.spec.whatwg.org/">WHATWG URL Standard</a> considers a handful of URL protocol schemes to be
<em>special</em> in terms of how they are parsed and serialized. When a URL is
parsed using one of these special protocols, the <code>url.protocol</code> property
may be changed to another special protocol but cannot be changed to a
non-special protocol, and vice versa.</p>
<p>For instance, changing from <code>http</code> to <code>https</code> works:</p>
<pre><code class="language-js">const u = new URL('http://example.org');
u.protocol = 'https';
console.log(u.href);
// https://example.org
</code></pre>
<p>However, changing from <code>http</code> to a hypothetical <code>fish</code> protocol does not
because the new protocol is not special.</p>
<pre><code class="language-js">const u = new URL('http://example.org');
u.protocol = 'fish';
console.log(u.href);
// http://example.org
</code></pre>
<p>Likewise, changing from a non-special protocol to a special protocol is also
not permitted:</p>
<pre><code class="language-js">const u = new URL('fish://example.org');
u.protocol = 'http';
console.log(u.href);
// fish://example.org
</code></pre>
<p>According to the WHATWG URL Standard, special protocol schemes are <code>ftp</code>,
<code>file</code>, <code>gopher</code>, <code>http</code>, <code>https</code>, <code>ws</code>, and <code>wss</code>.</p>
<h4><code>url.search</code><span><a class="mark" href="#url_url_search" id="url_url_search">#</a></span></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Gets and sets the serialized query portion of the URL.</p>
<pre><code class="language-js">const myURL = new URL('https://example.org/abc?123');
console.log(myURL.search);
// Prints ?123

myURL.search = 'abc=xyz';
console.log(myURL.href);
// Prints https://example.org/abc?abc=xyz
</code></pre>
<p>Any invalid URL characters appearing in the value assigned the <code>search</code>
property will be <a href="#whatwg-percent-encoding">percent-encoded</a>. 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><code>url.searchParams</code><span><a class="mark" href="#url_url_searchparams" id="url_url_searchparams">#</a></span></h4>
<ul>
<li><a href="#url_class_urlsearchparams" class="type">&#x3C;URLSearchParams></a></li>
</ul>
<p>Gets the <a href="#url_class_urlsearchparams"><code>URLSearchParams</code></a> object representing the query parameters of the
URL. This property is read-only but the <code>URLSearchParams</code> object it provides
can be used to mutate the URL instance; 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>
<p>Use care when using <code>.searchParams</code> to modify the <code>URL</code> because,
per the WHATWG specification, the <code>URLSearchParams</code> object uses
different rules to determine which characters to percent-encode. For
instance, the <code>URL</code> object will not percent encode the ASCII tilde (<code>~</code>)
character, while <code>URLSearchParams</code> will always encode it:</p>
<pre><code class="language-js">const myUrl = new URL('https://example.org/abc?foo=~bar');

console.log(myUrl.search);  // prints ?foo=~bar

// Modify the URL via searchParams...
myUrl.searchParams.sort();

console.log(myUrl.search);  // prints ?foo=%7Ebar
</code></pre>
<h4><code>url.username</code><span><a class="mark" href="#url_url_username" id="url_url_username">#</a></span></h4>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Gets and sets the username portion of the URL.</p>
<pre><code class="language-js">const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.username);
// Prints abc

myURL.username = '123';
console.log(myURL.href);
// Prints https://123:xyz@example.com/
</code></pre>
<p>Any invalid URL characters appearing in the value assigned the <code>username</code>
property will be <a href="#whatwg-percent-encoding">percent-encoded</a>. 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><code>url.toString()</code><span><a class="mark" href="#url_url_tostring" id="url_url_tostring">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>toString()</code> method on the <code>URL</code> object returns the serialized URL. The
value returned is equivalent to that of <a href="#url_url_href"><code>url.href</code></a> and <a href="#url_url_tojson"><code>url.toJSON()</code></a>.</p>
<p>Because of the need for standard compliance, this method does not allow users
to customize the serialization process of the URL. For more flexibility,
<a href="#url_url_format_url_options"><code>require('url').format()</code></a> method might be of interest.</p>
<h4><code>url.toJSON()</code><span><a class="mark" href="#url_url_tojson" id="url_url_tojson">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>toJSON()</code> method on the <code>URL</code> object returns the serialized URL. The
value returned is equivalent to that of <a href="#url_url_href"><code>url.href</code></a> and
<a href="#url_url_tostring"><code>url.toString()</code></a>.</p>
<p>This method is automatically called when an <code>URL</code> object is serialized
with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify"><code>JSON.stringify()</code></a>.</p>
<pre><code class="language-js">const myURLs = [
  new URL('https://www.example.com'),
  new URL('https://test.example.org')
];
console.log(JSON.stringify(myURLs));
// Prints ["https://www.example.com/","https://test.example.org/"]
</code></pre>
<h3>Class: <code>URLSearchParams</code><span><a class="mark" href="#url_class_urlsearchparams" id="url_class_urlsearchparams">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The class is now available on the global object.</p></td></tr>
<tr><td>v7.5.0, v6.13.0</td>
<td><p><span>Added in: v7.5.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>URLSearchParams</code> API provides read and write access to the query of a
<code>URL</code>. The <code>URLSearchParams</code> class can also be used standalone with one of the
four following constructors.
The <code>URLSearchParams</code> class is also available on the global object.</p>
<p>The WHATWG <code>URLSearchParams</code> interface and the <a href="querystring.html"><code>querystring</code></a> module have
similar purpose, but the purpose of the <a href="querystring.html"><code>querystring</code></a> module is more
general, as it allows the customization of delimiter characters (<code>&#x26;</code> and <code>=</code>).
On the other hand, this API is designed purely for URL query strings.</p>
<pre><code class="language-js">const myURL = new URL('https://example.org/?abc=123');
console.log(myURL.searchParams.get('abc'));
// Prints 123

myURL.searchParams.append('abc', 'xyz');
console.log(myURL.href);
// Prints https://example.org/?abc=123&#x26;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&#x26;a=c

// newSearchParams.toString() is implicitly called
myURL.search = newSearchParams;
console.log(myURL.href);
// Prints https://example.org/?a=b&#x26;a=c
newSearchParams.delete('a');
console.log(myURL.href);
// Prints https://example.org/?a=b&#x26;a=c
</code></pre>
<h4>Constructor: <code>new URLSearchParams()</code><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: <code>new URLSearchParams(string)</code><span><a class="mark" href="#url_constructor_new_urlsearchparams_string" id="url_constructor_new_urlsearchparams_string">#</a></span></h4>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> A query string</li>
</ul>
<p>Parse the <code>string</code> as a query string, and use it to instantiate a new
<code>URLSearchParams</code> object. A leading <code>'?'</code>, if present, is ignored.</p>
<pre><code class="language-js">let params;

params = new URLSearchParams('user=abc&#x26;query=xyz');
console.log(params.get('user'));
// Prints 'abc'
console.log(params.toString());
// Prints 'user=abc&#x26;query=xyz'

params = new URLSearchParams('?user=abc&#x26;query=xyz');
console.log(params.toString());
// Prints 'user=abc&#x26;query=xyz'
</code></pre>
<h4>Constructor: <code>new URLSearchParams(obj)</code><span><a class="mark" href="#url_constructor_new_urlsearchparams_obj" id="url_constructor_new_urlsearchparams_obj">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v7.10.0, v6.13.0</span>
</div>
<ul>
<li><code>obj</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object representing a collection of key-value pairs</li>
</ul>
<p>Instantiate a new <code>URLSearchParams</code> object with a query hash map. The key and
value of each property of <code>obj</code> are always coerced to strings.</p>
<p>Unlike <a href="querystring.html"><code>querystring</code></a> module, duplicate keys in the form of array values are
not allowed. Arrays are stringified using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString"><code>array.toString()</code></a>, which simply
joins all array elements with commas.</p>
<pre><code class="language-js">const params = new URLSearchParams({
  user: 'abc',
  query: ['first', 'second']
});
console.log(params.getAll('query'));
// Prints [ 'first,second' ]
console.log(params.toString());
// Prints 'user=abc&#x26;query=first%2Csecond'
</code></pre>
<h4>Constructor: <code>new URLSearchParams(iterable)</code><span><a class="mark" href="#url_constructor_new_urlsearchparams_iterable" id="url_constructor_new_urlsearchparams_iterable">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v7.10.0, v6.13.0</span>
</div>
<ul>
<li><code>iterable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> An iterable object whose elements are key-value pairs</li>
</ul>
<p>Instantiate a new <code>URLSearchParams</code> object with an iterable map in a way that
is similar to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a>'s constructor. <code>iterable</code> can be an <code>Array</code> or any
iterable object. That means <code>iterable</code> can be another <code>URLSearchParams</code>, in
which case the constructor will simply create a clone of the provided
<code>URLSearchParams</code>. Elements of <code>iterable</code> are key-value pairs, and can
themselves be any iterable object.</p>
<p>Duplicate keys are allowed.</p>
<pre><code class="language-js">let params;

// Using an array
params = new URLSearchParams([
  ['user', 'abc'],
  ['query', 'first'],
  ['query', 'second']
]);
console.log(params.toString());
// Prints 'user=abc&#x26;query=first&#x26;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&#x26;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&#x26;query=first&#x26;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><code>urlSearchParams.append(name, value)</code><span><a class="mark" href="#url_urlsearchparams_append_name_value" id="url_urlsearchparams_append_name_value">#</a></span></h4>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Append a new name-value pair to the query string.</p>
<h4><code>urlSearchParams.delete(name)</code><span><a class="mark" href="#url_urlsearchparams_delete_name" id="url_urlsearchparams_delete_name">#</a></span></h4>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Remove all name-value pairs whose name is <code>name</code>.</p>
<h4><code>urlSearchParams.entries()</code><span><a class="mark" href="#url_urlsearchparams_entries" id="url_urlsearchparams_entries">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type">&#x3C;Iterator></a></li>
</ul>
<p>Returns an ES6 <code>Iterator</code> over each of the name-value pairs in the query.
Each item of the iterator is a JavaScript <code>Array</code>. The first item of the <code>Array</code>
is the <code>name</code>, the second item of the <code>Array</code> is the <code>value</code>.</p>
<p>Alias for <a href="#url_urlsearchparams_symbol_iterator"><code>urlSearchParams[@@iterator]()</code></a>.</p>
<h4><code>urlSearchParams.forEach(fn[, thisArg])</code><span><a class="mark" href="#url_urlsearchparams_foreach_fn_thisarg" id="url_urlsearchparams_foreach_fn_thisarg">#</a></span></h4>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked for each name-value pair in the query</li>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> To be used as <code>this</code> value for when <code>fn</code> is called</li>
</ul>
<p>Iterates over each name-value pair in the query and invokes the given function.</p>
<pre><code class="language-js">const myURL = new URL('https://example.org/?a=b&#x26;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><code>urlSearchParams.get(name)</code><span><a class="mark" href="#url_urlsearchparams_get_name" id="url_urlsearchparams_get_name">#</a></span></h4>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> or <code>null</code> if there is no name-value pair with the given
<code>name</code>.</li>
</ul>
<p>Returns the value of the first name-value pair whose name is <code>name</code>. If there
are no such pairs, <code>null</code> is returned.</p>
<h4><code>urlSearchParams.getAll(name)</code><span><a class="mark" href="#url_urlsearchparams_getall_name" id="url_urlsearchparams_getall_name">#</a></span></h4>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>Returns the values of all name-value pairs whose name is <code>name</code>. If there are
no such pairs, an empty array is returned.</p>
<h4><code>urlSearchParams.has(name)</code><span><a class="mark" href="#url_urlsearchparams_has_name" id="url_urlsearchparams_has_name">#</a></span></h4>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if there is at least one name-value pair whose name is <code>name</code>.</p>
<h4><code>urlSearchParams.keys()</code><span><a class="mark" href="#url_urlsearchparams_keys" id="url_urlsearchparams_keys">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type">&#x3C;Iterator></a></li>
</ul>
<p>Returns an ES6 <code>Iterator</code> over the names of each name-value pair.</p>
<pre><code class="language-js">const params = new URLSearchParams('foo=bar&#x26;foo=baz');
for (const name of params.keys()) {
  console.log(name);
}
// Prints:
//   foo
//   foo
</code></pre>
<h4><code>urlSearchParams.set(name, value)</code><span><a class="mark" href="#url_urlsearchparams_set_name_value" id="url_urlsearchparams_set_name_value">#</a></span></h4>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Sets the value in the <code>URLSearchParams</code> object associated with <code>name</code> to
<code>value</code>. If there are any pre-existing name-value pairs whose names are <code>name</code>,
set the first such pair's value to <code>value</code> and remove all others. If not,
append the name-value pair to the query string.</p>
<pre><code class="language-js">const params = new URLSearchParams();
params.append('foo', 'bar');
params.append('foo', 'baz');
params.append('abc', 'def');
console.log(params.toString());
// Prints foo=bar&#x26;foo=baz&#x26;abc=def

params.set('foo', 'def');
params.set('xyz', 'opq');
console.log(params.toString());
// Prints foo=def&#x26;abc=def&#x26;xyz=opq
</code></pre>
<h4><code>urlSearchParams.sort()</code><span><a class="mark" href="#url_urlsearchparams_sort" id="url_urlsearchparams_sort">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v7.7.0, v6.13.0</span>
</div>
<p>Sort all existing name-value pairs in-place by their names. Sorting is done
with a <a href="https://en.wikipedia.org/wiki/Sorting_algorithm#Stability">stable sorting algorithm</a>, so relative order between name-value pairs
with the same name is preserved.</p>
<p>This method can be used, in particular, to increase cache hits.</p>
<pre><code class="language-js">const params = new URLSearchParams('query[]=abc&#x26;type=search&#x26;query[]=123');
params.sort();
console.log(params.toString());
// Prints query%5B%5D=abc&#x26;query%5B%5D=123&#x26;type=search
</code></pre>
<h4><code>urlSearchParams.toString()</code><span><a class="mark" href="#url_urlsearchparams_tostring" id="url_urlsearchparams_tostring">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the search parameters serialized as a string, with characters
percent-encoded where necessary.</p>
<h4><code>urlSearchParams.values()</code><span><a class="mark" href="#url_urlsearchparams_values" id="url_urlsearchparams_values">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type">&#x3C;Iterator></a></li>
</ul>
<p>Returns an ES6 <code>Iterator</code> over the values of each name-value pair.</p>
<h4><code>urlSearchParams[Symbol.iterator]()</code><span><a class="mark" href="#url_urlsearchparams_symbol_iterator" id="url_urlsearchparams_symbol_iterator">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol" class="type">&#x3C;Iterator></a></li>
</ul>
<p>Returns an ES6 <code>Iterator</code> over each of the name-value pairs in the query string.
Each item of the iterator is a JavaScript <code>Array</code>. The first item of the <code>Array</code>
is the <code>name</code>, the second item of the <code>Array</code> is the <code>value</code>.</p>
<p>Alias for <a href="#url_urlsearchparams_entries"><code>urlSearchParams.entries()</code></a>.</p>
<pre><code class="language-js">const params = new URLSearchParams('foo=bar&#x26;xyz=baz');
for (const [name, value] of params) {
  console.log(name, value);
}
// Prints:
//   foo bar
//   xyz baz
</code></pre>
<h3><code>url.domainToASCII(domain)</code><span><a class="mark" href="#url_url_domaintoascii_domain" id="url_url_domaintoascii_domain">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.4.0, v6.13.0</span>
</div>
<ul>
<li><code>domain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the <a href="https://tools.ietf.org/html/rfc5891#section-4.4">Punycode</a> ASCII serialization of the <code>domain</code>. If <code>domain</code> is an
invalid domain, the empty string is returned.</p>
<p>It performs the inverse operation to <a href="#url_url_domaintounicode_domain"><code>url.domainToUnicode()</code></a>.</p>
<pre><code class="language-js">const url = require('url');
console.log(url.domainToASCII('español.com'));
// Prints xn--espaol-zwa.com
console.log(url.domainToASCII('中文.com'));
// Prints xn--fiq228c.com
console.log(url.domainToASCII('xn--iñvalid.com'));
// Prints an empty string
</code></pre>
<h3><code>url.domainToUnicode(domain)</code><span><a class="mark" href="#url_url_domaintounicode_domain" id="url_url_domaintounicode_domain">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.4.0, v6.13.0</span>
</div>
<ul>
<li><code>domain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the Unicode serialization of the <code>domain</code>. If <code>domain</code> is an invalid
domain, the empty string is returned.</p>
<p>It performs the inverse operation to <a href="#url_url_domaintoascii_domain"><code>url.domainToASCII()</code></a>.</p>
<pre><code class="language-js">const url = require('url');
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
// Prints español.com
console.log(url.domainToUnicode('xn--fiq228c.com'));
// Prints 中文.com
console.log(url.domainToUnicode('xn--iñvalid.com'));
// Prints an empty string
</code></pre>
<h3><code>url.fileURLToPath(url)</code><span><a class="mark" href="#url_url_fileurltopath_url" id="url_url_fileurltopath_url">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<ul>
<li><code>url</code> <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The file URL string or URL object to convert to a path.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The fully-resolved platform-specific Node.js file path.</li>
</ul>
<p>This function ensures the correct decodings of percent-encoded characters as
well as ensuring a cross-platform valid absolute path string.</p>
<pre><code class="language-js">new URL('file:///C:/path/').pathname;    // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');       // Correct:   C:\path\ (Windows)

new URL('file://nas/foo.txt').pathname;  // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt');     // Correct:   \\nas\foo.txt (Windows)

new URL('file:///你好.txt').pathname;    // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt');       // Correct:   /你好.txt (POSIX)

new URL('file:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:///hello world');    // Correct:   /hello world (POSIX)
</code></pre>
<h3><code>url.format(URL[, options])</code><span><a class="mark" href="#url_url_format_url_options" id="url_url_format_url_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v7.6.0</span>
</div>
<ul>
<li><code>URL</code> <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> A <a href="#url_the_whatwg_url_api">WHATWG URL</a> object</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>auth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if the serialized URL string should include the
username and password, <code>false</code> otherwise. <strong>Default:</strong> <code>true</code>.</li>
<li><code>fragment</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if the serialized URL string should include the
fragment, <code>false</code> otherwise. <strong>Default:</strong> <code>true</code>.</li>
<li><code>search</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if the serialized URL string should include the
search query, <code>false</code> otherwise. <strong>Default:</strong> <code>true</code>.</li>
<li><code>unicode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if Unicode characters appearing in the host
component of the URL string should be encoded directly as opposed to being
Punycode encoded. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns a customizable serialization of a URL <code>String</code> representation of a
<a href="#url_the_whatwg_url_api">WHATWG URL</a> object.</p>
<p>The URL object has both a <code>toString()</code> method and <code>href</code> property that return
string serializations of the URL. These are not, however, customizable in
any way. The <code>url.format(URL[, options])</code> method allows for basic customization
of the output.</p>
<pre><code class="language-js">const myURL = new URL('https://a:b@測試?abc#foo');

console.log(myURL.href);
// Prints https://a:b@xn--g6w251d/?abc#foo

console.log(myURL.toString());
// Prints https://a:b@xn--g6w251d/?abc#foo

console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://測試/?abc'
</code></pre>
<h3><code>url.pathToFileURL(path)</code><span><a class="mark" href="#url_url_pathtofileurl_path" id="url_url_pathtofileurl_path">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<ul>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The path to convert to a File URL.</li>
<li>Returns: <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> The file URL object.</li>
</ul>
<p>This function ensures that <code>path</code> is resolved absolutely, and that the URL
control characters are correctly encoded when converting into a File URL.</p>
<pre><code class="language-js">new URL(__filename);                // Incorrect: throws (POSIX)
new URL(__filename);                // Incorrect: C:\... (Windows)
pathToFileURL(__filename);          // Correct:   file:///... (POSIX)
pathToFileURL(__filename);          // Correct:   file:///C:/... (Windows)

new URL('/foo#1', 'file:');         // Incorrect: file:///foo#1
pathToFileURL('/foo#1');            // Correct:   file:///foo%231 (POSIX)

new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c
pathToFileURL('/some/path%.c');    // Correct:   file:///some/path%25.c (POSIX)
</code></pre>
<h2>Legacy URL API<span><a class="mark" href="#url_legacy_url_api" id="url_legacy_url_api">#</a></span></h2>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use the WHATWG URL API instead.</div><p></p>
<h3>Legacy <code>urlObject</code><span><a class="mark" href="#url_legacy_urlobject" id="url_legacy_urlobject">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>The Legacy URL API is deprecated. Use the WHATWG URL API.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The legacy <code>urlObject</code> (<code>require('url').Url</code>) is created and returned by the
<code>url.parse()</code> function.</p>
<h4><code>urlObject.auth</code><span><a class="mark" href="#url_urlobject_auth" id="url_urlobject_auth">#</a></span></h4>
<p>The <code>auth</code> property is the username and password portion of the URL, also
referred to as <em>userinfo</em>. This string subset follows the <code>protocol</code> and
double slashes (if present) and precedes the <code>host</code> component, delimited by <code>@</code>.
The string is either the username, or it is the username and password separated
by <code>:</code>.</p>
<p>For example: <code>'user:pass'</code>.</p>
<h4><code>urlObject.hash</code><span><a class="mark" href="#url_urlobject_hash" id="url_urlobject_hash">#</a></span></h4>
<p>The <code>hash</code> property is the fragment identifier portion of the URL including the
leading <code>#</code> character.</p>
<p>For example: <code>'#hash'</code>.</p>
<h4><code>urlObject.host</code><span><a class="mark" href="#url_urlobject_host" id="url_urlobject_host">#</a></span></h4>
<p>The <code>host</code> property is the full lower-cased host portion of the URL, including
the <code>port</code> if specified.</p>
<p>For example: <code>'sub.example.com:8080'</code>.</p>
<h4><code>urlObject.hostname</code><span><a class="mark" href="#url_urlobject_hostname" id="url_urlobject_hostname">#</a></span></h4>
<p>The <code>hostname</code> property is the lower-cased host name portion of the <code>host</code>
component <em>without</em> the <code>port</code> included.</p>
<p>For example: <code>'sub.example.com'</code>.</p>
<h4><code>urlObject.href</code><span><a class="mark" href="#url_urlobject_href" id="url_urlobject_href">#</a></span></h4>
<p>The <code>href</code> property is the full URL string that was parsed with both the
<code>protocol</code> and <code>host</code> components converted to lower-case.</p>
<p>For example: <code>'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</code>.</p>
<h4><code>urlObject.path</code><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><code>urlObject.pathname</code><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><code>urlObject.port</code><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><code>urlObject.protocol</code><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><code>urlObject.query</code><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><code>urlObject.search</code><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><code>urlObject.slashes</code><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><code>url.format(urlObject)</code><span><a class="mark" href="#url_url_format_urlobject" id="url_url_format_urlobject">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>The Legacy URL API is deprecated. Use the WHATWG URL API.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>URLs with a <code>file:</code> scheme will now always use the correct number of slashes regardless of <code>slashes</code> option. A false-y <code>slashes</code> option with no protocol is now also respected at all times.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>urlObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> A URL object (as returned by <code>url.parse()</code> or
constructed otherwise). If a string, it is converted to an object by passing
it to <code>url.parse()</code>.</li>
</ul>
<p>The <code>url.format()</code> method returns a formatted URL string derived from
<code>urlObject</code>.</p>
<pre><code class="language-js">url.format({
  protocol: 'https',
  hostname: 'example.com',
  pathname: '/some/path',
  query: {
    page: 1,
    format: 'json'
  }
});

// => 'https://example.com/some/path?page=1&#x26;format=json'
</code></pre>
<p>If <code>urlObject</code> is not an object or a string, <code>url.format()</code> will throw a
<a href="#errors_class_typeerror"><code>TypeError</code></a>.</p>
<p>The formatting process operates as follows:</p>
<ul>
<li>A new empty string <code>result</code> is created.</li>
<li>If <code>urlObject.protocol</code> is a string, it is appended as-is to <code>result</code>.</li>
<li>Otherwise, if <code>urlObject.protocol</code> is not <code>undefined</code> and is not a string, an
<a href="#errors_class_error"><code>Error</code></a> is thrown.</li>
<li>For all string values of <code>urlObject.protocol</code> that <em>do not end</em> with an ASCII
colon (<code>:</code>) character, the literal string <code>:</code> will be appended to <code>result</code>.</li>
<li>
<p>If either of the following conditions is true, then the literal string <code>//</code>
will be appended to <code>result</code>:</p>
<ul>
<li><code>urlObject.slashes</code> property is true;</li>
<li><code>urlObject.protocol</code> begins with <code>http</code>, <code>https</code>, <code>ftp</code>, <code>gopher</code>, or
<code>file</code>;</li>
</ul>
</li>
<li>If the value of the <code>urlObject.auth</code> property is truthy, and either
<code>urlObject.host</code> or <code>urlObject.hostname</code> are not <code>undefined</code>, the value of
<code>urlObject.auth</code> will be coerced into a string and appended to <code>result</code>
followed by the literal string <code>@</code>.</li>
<li>
<p>If the <code>urlObject.host</code> property is <code>undefined</code> then:</p>
<ul>
<li>If the <code>urlObject.hostname</code> is a string, it is appended to <code>result</code>.</li>
<li>Otherwise, if <code>urlObject.hostname</code> is not <code>undefined</code> and is not a string,
an <a href="#errors_class_error"><code>Error</code></a> is thrown.</li>
<li>
<p>If the <code>urlObject.port</code> property value is truthy, and <code>urlObject.hostname</code>
is not <code>undefined</code>:</p>
<ul>
<li>The literal string <code>:</code> is appended to <code>result</code>, and</li>
<li>The value of <code>urlObject.port</code> is coerced to a string and appended to
<code>result</code>.</li>
</ul>
</li>
</ul>
</li>
<li>Otherwise, if the <code>urlObject.host</code> property value is truthy, the value of
<code>urlObject.host</code> is coerced to a string and appended to <code>result</code>.</li>
<li>
<p>If the <code>urlObject.pathname</code> property is a string that is not an empty string:</p>
<ul>
<li>If the <code>urlObject.pathname</code> <em>does not start</em> with an ASCII forward slash
(<code>/</code>), then the literal string <code>'/'</code> is appended to <code>result</code>.</li>
<li>The value of <code>urlObject.pathname</code> is appended to <code>result</code>.</li>
</ul>
</li>
<li>Otherwise, if <code>urlObject.pathname</code> is not <code>undefined</code> and is not a string, an
<a href="#errors_class_error"><code>Error</code></a> is thrown.</li>
<li>If the <code>urlObject.search</code> property is <code>undefined</code> and if the <code>urlObject.query</code>
property is an <code>Object</code>, the literal string <code>?</code> is appended to <code>result</code>
followed by the output of calling the <a href="querystring.html"><code>querystring</code></a> module's <code>stringify()</code>
method passing the value of <code>urlObject.query</code>.</li>
<li>
<p>Otherwise, if <code>urlObject.search</code> is a string:</p>
<ul>
<li>If the value of <code>urlObject.search</code> <em>does not start</em> with the ASCII question
mark (<code>?</code>) character, the literal string <code>?</code> is appended to <code>result</code>.</li>
<li>The value of <code>urlObject.search</code> is appended to <code>result</code>.</li>
</ul>
</li>
<li>Otherwise, if <code>urlObject.search</code> is not <code>undefined</code> and is not a string, an
<a href="#errors_class_error"><code>Error</code></a> is thrown.</li>
<li>
<p>If the <code>urlObject.hash</code> property is a string:</p>
<ul>
<li>If the value of <code>urlObject.hash</code> <em>does not start</em> with the ASCII hash (<code>#</code>)
character, the literal string <code>#</code> is appended to <code>result</code>.</li>
<li>The value of <code>urlObject.hash</code> is appended to <code>result</code>.</li>
</ul>
</li>
<li>Otherwise, if the <code>urlObject.hash</code> property is not <code>undefined</code> and is not a
string, an <a href="#errors_class_error"><code>Error</code></a> is thrown.</li>
<li><code>result</code> is returned.</li>
</ul>
<h3><code>url.parse(urlString[, parseQueryString[, slashesDenoteHost]])</code><span><a class="mark" href="#url_url_parse_urlstring_parsequerystring_slashesdenotehost" id="url_url_parse_urlstring_parsequerystring_slashesdenotehost">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.14.0</td>
<td><p>The <code>pathname</code> property on the returned URL object is now <code>/</code> when there is no path and the protocol scheme is <code>ws:</code> or <code>wss:</code>.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The Legacy URL API is deprecated. Use the WHATWG URL API.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>search</code> property on the returned URL object is now <code>null</code> when no query string is present.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>urlString</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;boolean></a> If <code>true</code>, the <code>query</code> property will always
be set to an object returned by the <a href="querystring.html"><code>querystring</code></a> module's <code>parse()</code>
method. If <code>false</code>, the <code>query</code> property on the returned URL object will be an
unparsed, undecoded string. <strong>Default:</strong> <code>false</code>.</li>
<li><code>slashesDenoteHost</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, the first token after the literal
string <code>//</code> and preceding the next <code>/</code> will be interpreted as the <code>host</code>.
For instance, given <code>//foo/bar</code>, the result would be
<code>{host: 'foo', pathname: '/bar'}</code> rather than <code>{pathname: '//foo/bar'}</code>.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
<p>The <code>url.parse()</code> method takes a URL string, parses it, and returns a URL
object.</p>
<p>A <code>TypeError</code> is thrown if <code>urlString</code> is not a string.</p>
<p>A <code>URIError</code> is thrown if the <code>auth</code> property is present but cannot be decoded.</p>
<h3><code>url.resolve(from, to)</code><span><a class="mark" href="#url_url_resolve_from_to" id="url_url_resolve_from_to">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>The Legacy URL API is deprecated. Use the WHATWG URL API.</p></td></tr>
<tr><td>v6.6.0</td>
<td><p>The <code>auth</code> fields are now kept intact when <code>from</code> and <code>to</code> refer to the same host.</p></td></tr>
<tr><td>v6.5.0, v4.6.2</td>
<td><p>The <code>port</code> field is copied correctly now.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>The <code>auth</code> fields is cleared now the <code>to</code> parameter contains a hostname.</p></td></tr>
<tr><td>v0.1.25</td>
<td><p><span>Added in: v0.1.25</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>from</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> The HREF URL being resolved.</li>
</ul>
<p>The <code>url.resolve()</code> method resolves a target URL relative to a base URL in a
manner similar to that of a Web browser resolving an anchor tag HREF.</p>
<pre><code class="language-js">const url = require('url');
url.resolve('/one/two/three', 'four');         // '/one/two/four'
url.resolve('http://example.com/', '/one');    // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
</code></pre>
<p><a id="whatwg-percent-encoding"></a></p>
<h2>Percent-encoding in URLs<span><a class="mark" href="#url_percent_encoding_in_urls" id="url_percent_encoding_in_urls">#</a></span></h2>
<p>URLs are permitted to only contain a certain range of characters. Any character
falling outside of that range must be encoded. How such characters are encoded,
and which characters to encode depends entirely on where the character is
located within the structure of the URL.</p>
<h3>Legacy API<span><a class="mark" href="#url_legacy_api" id="url_legacy_api">#</a></span></h3>
<p>Within the Legacy API, spaces (<code>' '</code>) and the following characters will be
automatically escaped in the properties of URL objects:</p>
<pre><code class="language-text">&#x3C; > " ` \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 host name, the host name is encoded
using the <a href="https://tools.ietf.org/html/rfc5891#section-4.4">Punycode</a> algorithm. Note, however, that a host name <em>may</em> contain
<em>both</em> Punycode encoded and percent-encoded characters:</p>
<pre><code class="language-js">const myURL = new URL('https://%CF%80.example.com/foo');
console.log(myURL.href);
// Prints https://xn--1xa.example.com/foo
console.log(myURL.origin);
// Prints https://xn--1xa.example.com
</code></pre>
<h1>Util<span><a class="mark" href="#util_util" id="util_util">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>util</code> module supports the needs of Node.js internal APIs. Many of the
utilities are useful for application and module developers as well. To access
it:</p>
<pre><code class="language-js">const util = require('util');
</code></pre>
<h2><code>util.callbackify(original)</code><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">&#x3C;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">&#x3C;Function></a> a callback style function</li>
</ul>
<p>Takes an <code>async</code> function (or a function that returns a <code>Promise</code>) and returns a
function following the error-first callback style, i.e. taking
an <code>(err, value) => ...</code> callback as the last argument. In the callback, the
first argument will be the rejection reason (or <code>null</code> if the <code>Promise</code>
resolved), and the second argument will be the resolved value.</p>
<pre><code class="language-js">const util = require('util');

async function fn() {
  return 'hello world';
}
const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
  if (err) throw err;
  console.log(ret);
});
</code></pre>
<p>Will print:</p>
<pre><code class="language-text">hello world
</code></pre>
<p>The callback is executed asynchronously, and will have a limited stack trace.
If the callback throws, the process will emit an <a href="#process_event_uncaughtexception"><code>'uncaughtException'</code></a>
event, and if not handled will exit.</p>
<p>Since <code>null</code> has a special meaning as the first argument to a callback, if a
wrapped function rejects a <code>Promise</code> with a falsy value as a reason, the value
is wrapped in an <code>Error</code> with the original value stored in a field named
<code>reason</code>.</p>
<pre><code class="language-js">function fn() {
  return Promise.reject(null);
}
const callbackFunction = util.callbackify(fn);

callbackFunction((err, ret) => {
  // When the Promise was rejected with `null` it is wrapped with an Error and
  // the original value is stored in `reason`.
  err &#x26;&#x26; err.hasOwnProperty('reason') &#x26;&#x26; err.reason === null;  // true
});
</code></pre>
<h2><code>util.debuglog(section)</code><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">&#x3C;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">&#x3C;Function></a> The logging function</li>
</ul>
<p>The <code>util.debuglog()</code> method is used to create a function that conditionally
writes debug messages to <code>stderr</code> based on the existence of the <code>NODE_DEBUG</code>
environment variable. If the <code>section</code> name appears within the value of that
environment variable, then the returned function operates similar to
<a href="#console_console_error_data_args"><code>console.error()</code></a>. If not, then the returned function is a no-op.</p>
<pre><code class="language-js">const util = require('util');
const debuglog = util.debuglog('foo');

debuglog('hello from foo [%d]', 123);
</code></pre>
<p>If this program is run with <code>NODE_DEBUG=foo</code> in the environment, then
it will output something like:</p>
<pre><code class="language-console">FOO 3245: hello from foo [123]
</code></pre>
<p>where <code>3245</code> is the process id. If it is not run with that
environment variable set, then it will not print anything.</p>
<p>The <code>section</code> supports wildcard also:</p>
<pre><code class="language-js">const util = require('util');
const debuglog = util.debuglog('foo-bar');

debuglog('hi there, it\'s foo-bar [%d]', 2333);
</code></pre>
<p>if it is run with <code>NODE_DEBUG=foo*</code> in the environment, then it will output
something like:</p>
<pre><code class="language-console">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><code>util.deprecate(fn, msg[, code])</code><span><a class="mark" href="#util_util_deprecate_fn_msg_code" id="util_util_deprecate_fn_msg_code">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>Deprecation warnings are only emitted once for each code.</p></td></tr>
<tr><td>v0.8.0</td>
<td><p><span>Added in: v0.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The function that is being deprecated.</li>
<li><code>msg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> A warning message to display when the deprecated function is
invoked.</li>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> A deprecation code. See the <a href="#deprecations_list_of_deprecated_apis">list of deprecated APIs</a> for a
list of codes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The deprecated function wrapped to emit a warning.</li>
</ul>
<p>The <code>util.deprecate()</code> method wraps <code>fn</code> (which may be a function or class) in
such a way that it is marked as deprecated.</p>
<pre><code class="language-js">const util = require('util');

exports.obsoleteFunction = util.deprecate(() => {
  // Do something here.
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
</code></pre>
<p>When called, <code>util.deprecate()</code> will return a function that will emit a
<code>DeprecationWarning</code> using the <a href="#process_event_warning"><code>'warning'</code></a> event. The warning will
be emitted and printed to <code>stderr</code> the first time the returned function is
called. After the warning is emitted, the wrapped function is called without
emitting a warning.</p>
<p>If the same optional <code>code</code> is supplied in multiple calls to <code>util.deprecate()</code>,
the warning will be emitted only once for that <code>code</code>.</p>
<pre><code class="language-js">const util = require('util');

const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');
fn1(); // Emits a deprecation warning with code DEP0001
fn2(); // Does not emit a deprecation warning because it has the same code
</code></pre>
<p>If either the <code>--no-deprecation</code> or <code>--no-warnings</code> command line flags are
used, or if the <code>process.noDeprecation</code> property is set to <code>true</code> <em>prior</em> to
the first deprecation warning, the <code>util.deprecate()</code> method does nothing.</p>
<p>If the <code>--trace-deprecation</code> or <code>--trace-warnings</code> command line flags are set,
or the <code>process.traceDeprecation</code> property is set to <code>true</code>, a warning and a
stack trace are printed to <code>stderr</code> the first time the deprecated function is
called.</p>
<p>If the <code>--throw-deprecation</code> command line flag is set, or the
<code>process.throwDeprecation</code> property is set to <code>true</code>, then an exception will be
thrown when the deprecated function is called.</p>
<p>The <code>--throw-deprecation</code> command line flag and <code>process.throwDeprecation</code>
property take precedence over <code>--trace-deprecation</code> and
<code>process.traceDeprecation</code>.</p>
<h2><code>util.format(format[, ...args])</code><span><a class="mark" href="#util_util_format_format_args" id="util_util_format_format_args">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.11.0</td>
<td><p>The <code>%c</code> specifier is ignored now.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>The <code>format</code> argument is now only taken as such if it actually contains format specifiers.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>If the <code>format</code> argument is not a format string, the output string's formatting is no longer dependent on the type of the first argument. This change removes previously present quotes from strings that were being output when the first argument was not a string.</p></td></tr>
<tr><td>v11.4.0</td>
<td><p>The <code>%d</code>, <code>%f</code> and <code>%i</code> specifiers now support Symbols properly.</p></td></tr>
<tr><td>v11.4.0</td>
<td><p>The <code>%o</code> specifier's <code>depth</code> has default depth of 4 again.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The <code>%o</code> specifier's <code>depth</code> option will now fall back to the default depth.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p>The <code>%d</code> and <code>%i</code> specifiers now support BigInt.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p>The <code>%o</code> and <code>%O</code> specifiers are supported now.</p></td></tr>
<tr><td>v0.5.3</td>
<td><p><span>Added in: v0.5.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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 string which can contain zero or more format
specifiers. Each specifier is replaced with the converted value from the
corresponding argument. Supported specifiers are:</p>
<ul>
<li><code>%s</code>: <code>String</code> will be used to convert all values except <code>BigInt</code>, <code>Object</code>
and <code>-0</code>. <code>BigInt</code> values will be represented with an <code>n</code> and Objects that
have no user defined <code>toString</code> function are inspected using <code>util.inspect()</code>
with options <code>{ depth: 0, colors: false, compact: 3 }</code>.</li>
<li><code>%d</code>: <code>Number</code> will be used to convert all values except <code>BigInt</code> and
<code>Symbol</code>.</li>
<li><code>%i</code>: <code>parseInt(value, 10)</code> is used for all values except <code>BigInt</code> and
<code>Symbol</code>.</li>
<li><code>%f</code>: <code>parseFloat(value)</code> is used for all values expect <code>Symbol</code>.</li>
<li><code>%j</code>: JSON. Replaced with the string <code>'[Circular]'</code> if the argument contains
circular references.</li>
<li><code>%o</code>: <code>Object</code>. A string representation of an object with generic JavaScript
object formatting. Similar to <code>util.inspect()</code> with options
<code>{ showHidden: true, showProxy: true }</code>. This will show the full object
including non-enumerable properties and proxies.</li>
<li><code>%O</code>: <code>Object</code>. A string representation of an object with generic JavaScript
object formatting. Similar to <code>util.inspect()</code> without options. This will show
the full object not including non-enumerable properties and proxies.</li>
<li><code>%c</code>: <code>CSS</code>. This specifier is ignored and will skip any CSS passed in.</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">&#x3C;string></a> The formatted string</li>
</ul>
<p>If a specifier does not have a corresponding argument, it is not replaced:</p>
<pre><code class="language-js">util.format('%s:%s', 'foo');
// Returns: 'foo:%s'
</code></pre>
<p>Values that are not part of the format string are formatted using
<code>util.inspect()</code> if their type is not <code>string</code>.</p>
<p>If there are more arguments passed to the <code>util.format()</code> method than the
number of specifiers, the extra arguments are concatenated to the returned
string, separated by spaces:</p>
<pre><code class="language-js">util.format('%s:%s', 'foo', 'bar', 'baz');
// Returns: 'foo:bar baz'
</code></pre>
<p>If the first argument does not contain a valid format specifier, <code>util.format()</code>
returns a string that is the concatenation of all arguments separated by spaces:</p>
<pre><code class="language-js">util.format(1, 2, 3);
// Returns: '1 2 3'
</code></pre>
<p>If only one argument is passed to <code>util.format()</code>, it is returned as it is
without any formatting:</p>
<pre><code class="language-js">util.format('%% %s');
// Returns: '%% %s'
</code></pre>
<p><code>util.format()</code> is a synchronous method that is 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><code>util.formatWithOptions(inspectOptions, format[, ...args])</code><span><a class="mark" href="#util_util_formatwithoptions_inspectoptions_format_args" id="util_util_formatwithoptions_inspectoptions_format_args">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>inspectOptions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>format</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>This function is identical to <a href="#util_util_format_format_args"><code>util.format()</code></a>, except in that it takes
an <code>inspectOptions</code> argument which specifies options that are passed along to
<a href="#util_util_inspect_object_options"><code>util.inspect()</code></a>.</p>
<pre><code class="language-js">util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 });
// Returns 'See object { foo: 42 }', where `42` is colored as a number
// when printed to a terminal.
</code></pre>
<h2><code>util.getSystemErrorName(err)</code><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">&#x3C;number></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Returns the string name for a numeric error code that comes from a Node.js API.
The mapping between error codes and error names is platform-dependent.
See <a href="#errors_common_system_errors">Common System Errors</a> for the names of common errors.</p>
<pre><code class="language-js">fs.access('file/that/does/not/exist', (err) => {
  const name = util.getSystemErrorName(err.errno);
  console.error(name);  // ENOENT
});
</code></pre>
<h2><code>util.inherits(constructor, superConstructor)</code><span><a class="mark" href="#util_util_inherits_constructor_superconstructor" id="util_util_inherits_constructor_superconstructor">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.0.0</td>
<td><p>The <code>constructor</code> parameter can refer to an ES6 class now.</p></td></tr>
<tr><td>v0.3.0</td>
<td><p><span>Added in: v0.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>constructor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
<li><code>superConstructor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Usage of <code>util.inherits()</code> is discouraged. Please use the ES6 <code>class</code> and
<code>extends</code> keywords to get language level inheritance support. Also note
that the two styles are <a href="https://github.com/nodejs/node/issues/4179">semantically incompatible</a>.</p>
<p>Inherit the prototype methods from one <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a> into another. The
prototype of <code>constructor</code> will be set to a new object created from
<code>superConstructor</code>.</p>
<p>This mainly adds some input validation on top of
<code>Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)</code>.
As an additional convenience, <code>superConstructor</code> will be accessible
through the <code>constructor.super_</code> property.</p>
<pre><code class="language-js">const util = require('util');
const EventEmitter = require('events');

function MyStream() {
  EventEmitter.call(this);
}

util.inherits(MyStream, EventEmitter);

MyStream.prototype.write = function(data) {
  this.emit('data', data);
};

const stream = new MyStream();

console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true

stream.on('data', (data) => {
  console.log(`Received data: "${data}"`);
});
stream.write('It works!'); // Received data: "It works!"
</code></pre>
<p>ES6 example using <code>class</code> and <code>extends</code>:</p>
<pre><code class="language-js">const EventEmitter = require('events');

class MyStream extends EventEmitter {
  write(data) {
    this.emit('data', data);
  }
}

const stream = new MyStream();

stream.on('data', (data) => {
  console.log(`Received data: "${data}"`);
});
stream.write('With ES6');
</code></pre>
<h2><code>util.inspect(object[, options])</code><span><a class="mark" href="#util_util_inspect_object_options" id="util_util_inspect_object_options">#</a></span></h2>
<h2><code>util.inspect(object[, showHidden[, depth[, colors]]])</code><span><a class="mark" href="#util_util_inspect_object_showhidden_depth_colors" id="util_util_inspect_object_showhidden_depth_colors">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>The <code>maxStringLength</code> option is supported now.</p></td></tr>
<tr><td>v12.16.0</td>
<td><p>User defined prototype properties are inspected in case <code>showHidden</code> is <code>true</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>The <code>compact</code> options default is changed to <code>3</code> and the <code>breakLength</code> options default is changed to <code>80</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Internal properties no longer appear in the context argument of a custom inspection function.</p></td></tr>
<tr><td>v11.11.0</td>
<td><p>The <code>compact</code> option accepts numbers for a new output mode.</p></td></tr>
<tr><td>v11.7.0</td>
<td><p>ArrayBuffers now also show their binary contents.</p></td></tr>
<tr><td>v11.5.0</td>
<td><p>The <code>getters</code> option is supported now.</p></td></tr>
<tr><td>v11.4.0</td>
<td><p>The <code>depth</code> default changed back to <code>2</code>.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The <code>depth</code> default changed to <code>20</code>.</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>The inspection output is now limited to about 128 MB. Data above that size will not be fully inspected.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p>The <code>sorted</code> option is supported now.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p>Inspecting linked lists and similar objects is now possible up to the maximum call stack size.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>WeakMap</code> and <code>WeakSet</code> entries can now be inspected as well.</p></td></tr>
<tr><td>v9.9.0</td>
<td><p>The <code>compact</code> option is supported now.</p></td></tr>
<tr><td>v6.6.0</td>
<td><p>Custom inspection functions can now return <code>this</code>.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakLength</code> option is supported now.</p></td></tr>
<tr><td>v6.1.0</td>
<td><p>The <code>maxArrayLength</code> option is supported now; in particular, long arrays are truncated by default.</p></td></tr>
<tr><td>v6.1.0</td>
<td><p>The <code>showProxy</code> option is supported now.</p></td></tr>
<tr><td>v0.3.0</td>
<td><p><span>Added in: v0.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any JavaScript primitive or <code>Object</code>.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>showHidden</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, <code>object</code>'s non-enumerable symbols and
properties are included in the formatted result. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> entries are also included as well as user defined prototype
properties (excluding method properties). <strong>Default:</strong> <code>false</code>.</li>
<li><code>depth</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the number of times to recurse while formatting
<code>object</code>. This is useful for inspecting large objects. To recurse up to
the maximum call stack size pass <code>Infinity</code> or <code>null</code>.
<strong>Default:</strong> <code>2</code>.</li>
<li><code>colors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, the output is styled with ANSI color
codes. Colors are customizable. See <a href="#util_customizing_util_inspect_colors">Customizing <code>util.inspect</code> colors</a>.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>customInspect</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>false</code>,
<code>[util.inspect.custom](depth, opts)</code> functions are not invoked.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>showProxy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, <code>Proxy</code> inspection includes
the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#Terminology"><code>target</code> and <code>handler</code></a> objects. <strong>Default:</strong> <code>false</code>.</li>
<li><code>maxArrayLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the maximum number of <code>Array</code>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> elements to include when
formatting. Set to <code>null</code> or <code>Infinity</code> to show all elements. Set to <code>0</code> or
negative to show no elements. <strong>Default:</strong> <code>100</code>.</li>
<li><code>maxStringLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the maximum number of characters to
include when formatting. Set to <code>null</code> or <code>Infinity</code> to show all elements.
Set to <code>0</code> or negative to show no characters. <strong>Default:</strong> <code>Infinity</code>.</li>
<li><code>breakLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The length at which input values are split across
multiple lines. Set to <code>Infinity</code> to format the input as a single line
(in combination with <code>compact</code> set to <code>true</code> or any number >= <code>1</code>).
<strong>Default:</strong> <code>80</code>.</li>
<li><code>compact</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Setting this to <code>false</code> causes each object key
to be displayed on a new line. It will also add new lines to text that is
longer than <code>breakLength</code>. If set to a number, the most <code>n</code> inner elements
are united on a single line as long as all properties fit into
<code>breakLength</code>. Short array elements are also grouped together. No
text will be reduced below 16 characters, no matter the <code>breakLength</code> size.
For more information, see the example below. <strong>Default:</strong> <code>3</code>.</li>
<li><code>sorted</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> If set to <code>true</code> or a function, all properties
of an object, and <code>Set</code> and <code>Map</code> entries are sorted in the resulting
string. If set to <code>true</code> the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">default sort</a> is used. If set to a function,
it is used as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters">compare function</a>.</li>
<li><code>getters</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If set to <code>true</code>, getters are inspected. If set
to <code>'get'</code>, only getters without a corresponding setter are inspected. If
set to <code>'set'</code>, only getters with a corresponding setter are inspected.
This might cause side effects depending on the getter function.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The representation of <code>object</code>.</li>
</ul>
<p>The <code>util.inspect()</code> method returns a string representation of <code>object</code> that is
intended for debugging. The output of <code>util.inspect</code> may change at any time
and should not be depended upon programmatically. Additional <code>options</code> may be
passed that alter the result.
<code>util.inspect()</code> will use the constructor's name and/or <code>@@toStringTag</code> to make
an identifiable tag for an inspected value.</p>
<pre><code class="language-js">class Foo {
  get [Symbol.toStringTag]() {
    return 'bar';
  }
}

class Bar {}

const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } });

util.inspect(new Foo()); // 'Foo [bar] {}'
util.inspect(new Bar()); // 'Bar {}'
util.inspect(baz);       // '[foo] {}'
</code></pre>
<p>Circular references are marked as <code>'[Circular]'</code>:</p>
<pre><code class="language-js">const { inspect } = require('util');

const obj = {};
obj.a = [obj];
obj.b = {};
obj.b.inner = obj.b;
obj.b.obj = obj;

console.log(inspect(obj));
// {
//   a: [ [Circular] ],
//   b: { inner: [Circular], obj: [Circular] }
// }
</code></pre>
<p>The following example inspects all properties of the <code>util</code> object:</p>
<pre><code class="language-js">const util = require('util');

console.log(util.inspect(util, { showHidden: true, depth: null }));
</code></pre>
<p>The following example highlights the effect of the <code>compact</code> option:</p>
<pre><code class="language-js">const util = require('util');

const o = {
  a: [1, 2, [[
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' +
      'eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    'test',
    'foo']], 4],
  b: new Map([['za', 1], ['zb', 'test']])
};
console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 }));

// { 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>The <code>showHidden</code> option allows <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> entries to be
inspected. If there are more entries than <code>maxArrayLength</code>, there is no
guarantee which entries are displayed. That means retrieving the same
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> entries twice may result in different output. Furthermore, entries
with no remaining strong references may be garbage collected at any time.</p>
<pre><code class="language-js">const { inspect } = require('util');

const obj = { a: 1 };
const obj2 = { b: 2 };
const weakSet = new WeakSet([obj, obj2]);

console.log(inspect(weakSet, { showHidden: true }));
// WeakSet { { a: 1 }, { b: 2 } }
</code></pre>
<p>The <code>sorted</code> option ensures that an object's property insertion order does not
impact the result of <code>util.inspect()</code>.</p>
<pre><code class="language-js">const { inspect } = require('util');
const assert = require('assert');

const o1 = {
  b: [2, 3, 1],
  a: '`a` comes before `b`',
  c: new Set([2, 3, 1])
};
console.log(inspect(o1, { sorted: true }));
// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set { 1, 2, 3 } }
console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) }));
// { c: Set { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }

const o2 = {
  c: new Set([2, 1, 3]),
  a: '`a` comes before `b`',
  b: [2, 3, 1]
};
assert.strict.equal(
  inspect(o1, { sorted: true }),
  inspect(o2, { sorted: true })
);
</code></pre>
<p><code>util.inspect()</code> is a synchronous method intended for debugging. Its maximum
output length is approximately 128 MB. Inputs that result in longer output will
be truncated.</p>
<h3>Customizing <code>util.inspect</code> colors<span><a class="mark" href="#util_customizing_util_inspect_colors" id="util_customizing_util_inspect_colors">#</a></span></h3>

<p>Color output (if enabled) of <code>util.inspect</code> is customizable globally
via the <code>util.inspect.styles</code> and <code>util.inspect.colors</code> properties.</p>
<p><code>util.inspect.styles</code> is a map associating a style name to a color from
<code>util.inspect.colors</code>.</p>
<p>The default styles and associated colors are:</p>
<ul>
<li><code>bigint</code>: <code>yellow</code></li>
<li><code>boolean</code>: <code>yellow</code></li>
<li><code>date</code>: <code>magenta</code></li>
<li><code>module</code>: <code>underline</code></li>
<li><code>name</code>: (no styling)</li>
<li><code>null</code>: <code>bold</code></li>
<li><code>number</code>: <code>yellow</code></li>
<li><code>regexp</code>: <code>red</code></li>
<li><code>special</code>: <code>cyan</code> (e.g., <code>Proxies</code>)</li>
<li><code>string</code>: <code>green</code></li>
<li><code>symbol</code>: <code>green</code></li>
<li><code>undefined</code>: <code>grey</code></li>
</ul>
<p>Color styling uses ANSI control codes that may not be supported on all
terminals. To verify color support use <a href="#tty_writestream_hascolors_count_env"><code>tty.hasColors()</code></a>.</p>
<p>Predefined control codes are listed below (grouped as "Modifiers", "Foreground
colors", and "Background colors").</p>
<h4>Modifiers<span><a class="mark" href="#util_modifiers" id="util_modifiers">#</a></span></h4>
<p>Modifier support varies throughout different terminals. They will mostly be
ignored, if not supported.</p>
<ul>
<li><code>reset</code> - Resets all (color) modifiers to their defaults</li>
<li><strong>bold</strong> - Make text bold</li>
<li><em>italic</em> - Make text italic</li>
<li><span style="border-bottom: 1px;">underline</span> - Make text underlined</li>
<li><del>strikethrough</del> - Puts a horizontal line through the center of the text
(Alias: <code>strikeThrough</code>, <code>crossedout</code>, <code>crossedOut</code>)</li>
<li><code>hidden</code> - Prints the text, but makes it invisible (Alias: conceal)</li>
<li><span style="opacity: 0.5;">dim</span> - Decreased color intensity (Alias:
<code>faint</code>)</li>
<li><span style="border-top: 1px">overlined</span> - Make text overlined</li>
<li>blink - Hides and shows the text in an interval</li>
<li><span style="filter: invert(100%)">inverse</span> - Swap foreground and
background colors (Alias: <code>swapcolors</code>, <code>swapColors</code>)</li>
<li><span style="border-bottom: 1px double;">doubleunderline</span> - Make text
double underlined (Alias: <code>doubleUnderline</code>)</li>
<li><span style="border: 1px">framed</span> - Draw a frame around the text</li>
</ul>
<h4>Foreground colors<span><a class="mark" href="#util_foreground_colors" id="util_foreground_colors">#</a></span></h4>
<ul>
<li><code>black</code></li>
<li><code>red</code></li>
<li><code>green</code></li>
<li><code>yellow</code></li>
<li><code>blue</code></li>
<li><code>magenta</code></li>
<li><code>cyan</code></li>
<li><code>white</code></li>
<li><code>gray</code> (alias: <code>grey</code>, <code>blackBright</code>)</li>
<li><code>redBright</code></li>
<li><code>greenBright</code></li>
<li><code>yellowBright</code></li>
<li><code>blueBright</code></li>
<li><code>magentaBright</code></li>
<li><code>cyanBright</code></li>
<li><code>whiteBright</code></li>
</ul>
<h4>Background colors<span><a class="mark" href="#util_background_colors" id="util_background_colors">#</a></span></h4>
<ul>
<li><code>bgBlack</code></li>
<li><code>bgRed</code></li>
<li><code>bgGreen</code></li>
<li><code>bgYellow</code></li>
<li><code>bgBlue</code></li>
<li><code>bgMagenta</code></li>
<li><code>bgCyan</code></li>
<li><code>bgWhite</code></li>
<li><code>bgGray</code> (alias: <code>bgGrey</code>, <code>bgBlackBright</code>)</li>
<li><code>bgRedBright</code></li>
<li><code>bgGreenBright</code></li>
<li><code>bgYellowBright</code></li>
<li><code>bgBlueBright</code></li>
<li><code>bgMagentaBright</code></li>
<li><code>bgCyanBright</code></li>
<li><code>bgWhiteBright</code></li>
</ul>
<h3>Custom inspection functions on objects<span><a class="mark" href="#util_custom_inspection_functions_on_objects" id="util_custom_inspection_functions_on_objects">#</a></span></h3>

<p>Objects may also define their own
<a href="#util_util_inspect_custom"><code>[util.inspect.custom](depth, opts)</code></a> function,
which <code>util.inspect()</code> will invoke and use the result of when inspecting
the object:</p>
<pre><code class="language-js">const util = require('util');

class Box {
  constructor(value) {
    this.value = value;
  }

  [util.inspect.custom](depth, options) {
    if (depth &#x3C; 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&#x3C; ".
    const padding = ' '.repeat(5);
    const inner = util.inspect(this.value, newOptions)
                      .replace(/\n/g, `\n${padding}`);
    return `${options.stylize('Box', 'special')}&#x3C; ${inner} >`;
  }
}

const box = new Box(true);

util.inspect(box);
// Returns: "Box&#x3C; true >"
</code></pre>
<p>Custom <code>[util.inspect.custom](depth, opts)</code> functions typically return a string
but may return a value of any type that will be formatted accordingly by
<code>util.inspect()</code>.</p>
<pre><code class="language-js">const util = require('util');

const obj = { foo: 'this will not show up in the inspect() output' };
obj[util.inspect.custom] = (depth) => {
  return { bar: 'baz' };
};

util.inspect(obj);
// Returns: "{ bar: 'baz' }"
</code></pre>
<h3><code>util.inspect.custom</code><span><a class="mark" href="#util_util_inspect_custom" id="util_util_inspect_custom">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.12.0</td>
<td><p>This is now defined as a shared symbol.</p></td></tr>
<tr><td>v6.6.0</td>
<td><p><span>Added in: v6.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> that can be used to declare custom inspect functions.</li>
</ul>
<p>In addition to being accessible through <code>util.inspect.custom</code>, this
symbol is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for">registered globally</a> and can be
accessed in any environment as <code>Symbol.for('nodejs.util.inspect.custom')</code>.</p>
<pre><code class="language-js">const inspect = Symbol.for('nodejs.util.inspect.custom');

class Password {
  constructor(value) {
    this.value = value;
  }

  toString() {
    return 'xxxxxxxx';
  }

  [inspect]() {
    return `Password &#x3C;${this.toString()}>`;
  }
}

const password = new Password('r0sebud');
console.log(password);
// Prints Password &#x3C;xxxxxxxx>
</code></pre>
<p>See <a href="#util_custom_inspection_functions_on_objects">Custom inspection functions on Objects</a> for more details.</p>
<h3><code>util.inspect.defaultOptions</code><span><a class="mark" href="#util_util_inspect_defaultoptions" id="util_util_inspect_defaultoptions">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v6.4.0</span>
</div>
<p>The <code>defaultOptions</code> value allows customization of the default options used by
<code>util.inspect</code>. This is useful for functions like <code>console.log</code> or
<code>util.format</code> which implicitly call into <code>util.inspect</code>. It shall be set to an
object containing one or more valid <a href="#util_util_inspect_object_options"><code>util.inspect()</code></a> options. Setting
option properties directly is also supported.</p>
<pre><code class="language-js">const util = require('util');
const arr = Array(101).fill(0);

console.log(arr); // Logs the truncated array
util.inspect.defaultOptions.maxArrayLength = null;
console.log(arr); // logs the full array
</code></pre>
<h2><code>util.isDeepStrictEqual(val1, val2)</code><span><a class="mark" href="#util_util_isdeepstrictequal_val1_val2" id="util_util_isdeepstrictequal_val1_val2">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v9.0.0</span>
</div>
<ul>
<li><code>val1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>val2</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if there is deep strict equality between <code>val1</code> and <code>val2</code>.
Otherwise, returns <code>false</code>.</p>
<p>See <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a> for more information about deep strict
equality.</p>
<h2><code>util.promisify(original)</code><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">&#x3C;Function></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Takes a function following the common error-first callback style, i.e. taking
an <code>(err, value) => ...</code> callback as the last argument, and returns a version
that returns promises.</p>
<pre><code class="language-js">const util = require('util');
const fs = require('fs');

const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
  // Do something with `stats`
}).catch((error) => {
  // Handle the error.
});
</code></pre>
<p>Or, equivalently using <code>async function</code>s:</p>
<pre><code class="language-js">const util = require('util');
const fs = require('fs');

const stat = util.promisify(fs.stat);

async function callStat() {
  const stats = await stat('.');
  console.log(`This directory is owned by ${stats.uid}`);
}
</code></pre>
<p>If there is an <code>original[util.promisify.custom]</code> property present, <code>promisify</code>
will return its value, see <a href="#util_custom_promisified_functions">Custom promisified functions</a>.</p>
<p><code>promisify()</code> assumes that <code>original</code> is a function taking a callback as its
final argument in all cases. If <code>original</code> is not a function, <code>promisify()</code>
will throw an error. If <code>original</code> is a function but its last argument is not
an error-first callback, it will still be passed an error-first
callback as its last argument.</p>
<p>Using <code>promisify()</code> on class methods or other methods that use <code>this</code> may not
work as expected unless handled specially:</p>
<pre><code class="language-js">const util = require('util');

class Foo {
  constructor() {
    this.a = 42;
  }

  bar(callback) {
    callback(null, this.a);
  }
}

const foo = new Foo();

const naiveBar = util.promisify(foo.bar);
// TypeError: Cannot read property 'a' of undefined
// naiveBar().then(a => console.log(a));

naiveBar.call(foo).then((a) => console.log(a)); // '42'

const bindBar = naiveBar.bind(foo);
bindBar().then((a) => console.log(a)); // '42'
</code></pre>
<h3>Custom promisified functions<span><a class="mark" href="#util_custom_promisified_functions" id="util_custom_promisified_functions">#</a></span></h3>
<p>Using the <code>util.promisify.custom</code> symbol one can override the return value of
<a href="#util_util_promisify_original"><code>util.promisify()</code></a>:</p>
<pre><code class="language-js">const util = require('util');

function doSomething(foo, callback) {
  // ...
}

doSomething[util.promisify.custom] = (foo) => {
  return getPromiseSomehow();
};

const promisified = util.promisify(doSomething);
console.log(promisified === doSomething[util.promisify.custom]);
// prints 'true'
</code></pre>
<p>This can be useful for cases where the original function does not follow the
standard format of taking an error-first callback as the last argument.</p>
<p>For example, with a function that takes in
<code>(foo, onSuccessCallback, onErrorCallback)</code>:</p>
<pre><code class="language-js">doSomething[util.promisify.custom] = (foo) => {
  return new Promise((resolve, reject) => {
    doSomething(foo, resolve, reject);
  });
};
</code></pre>
<p>If <code>promisify.custom</code> is defined but is not a function, <code>promisify()</code> will
throw an error.</p>
<h3><code>util.promisify.custom</code><span><a class="mark" href="#util_util_promisify_custom" id="util_util_promisify_custom">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.16.2</td>
<td><p>This is now defined as a shared symbol.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p><span>Added in: v8.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> that can be used to declare custom promisified variants of functions,
see <a href="#util_custom_promisified_functions">Custom promisified functions</a>.</li>
</ul>
<p>In addition to being accessible through <code>util.promisify.custom</code>, this
symbol is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for">registered globally</a> and can be
accessed in any environment as <code>Symbol.for('nodejs.util.promisify.custom')</code>.</p>
<p>For example, with a function that takes in
<code>(foo, onSuccessCallback, onErrorCallback)</code>:</p>
<pre><code class="language-js">const kCustomPromisifiedSymbol = Symbol.for('nodejs.util.promisify.custom');

doSomething[kCustomPromisifiedSymbol] = (foo) => {
  return new Promise((resolve, reject) => {
    doSomething(foo, resolve, reject);
  });
};
</code></pre>
<h2>Class: <code>util.TextDecoder</code><span><a class="mark" href="#util_class_util_textdecoder" id="util_class_util_textdecoder">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v8.3.0</span>
</div>
<p>An implementation of the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a> <code>TextDecoder</code> API.</p>
<pre><code class="language-js">const decoder = new TextDecoder('shift_jis');
let string = '';
let buffer;
while (buffer = getNextChunkSomehow()) {
  string += decoder.decode(buffer, { stream: true });
}
string += decoder.decode(); // end-of-stream
</code></pre>
<h3>WHATWG supported encodings<span><a class="mark" href="#util_whatwg_supported_encodings" id="util_whatwg_supported_encodings">#</a></span></h3>
<p>Per the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a>, the encodings supported by the
<code>TextDecoder</code> API are outlined in the tables below. For each encoding,
one or more aliases may be used.</p>
<p>Different Node.js build configurations support different sets of encodings.
While a very basic set of encodings is supported even on Node.js builds without
ICU enabled, support for some encodings is provided only when Node.js is built
with ICU and using the full ICU data (see <a href="intl.html">Internationalization</a>).</p>
<h4>Encodings Supported Without ICU<span><a class="mark" href="#util_encodings_supported_without_icu" id="util_encodings_supported_without_icu">#</a></span></h4>

















<table><thead><tr><th>Encoding</th><th>Aliases</th></tr></thead><tbody><tr><td><code>'utf-8'</code></td><td><code>'unicode-1-1-utf-8'</code>, <code>'utf8'</code></td></tr><tr><td><code>'utf-16le'</code></td><td><code>'utf-16'</code></td></tr></tbody></table>
<h4>Encodings Supported by Default (With ICU)<span><a class="mark" href="#util_encodings_supported_by_default_with_icu" id="util_encodings_supported_by_default_with_icu">#</a></span></h4>





















<table><thead><tr><th>Encoding</th><th>Aliases</th></tr></thead><tbody><tr><td><code>'utf-8'</code></td><td><code>'unicode-1-1-utf-8'</code>, <code>'utf8'</code></td></tr><tr><td><code>'utf-16le'</code></td><td><code>'utf-16'</code></td></tr><tr><td><code>'utf-16be'</code></td><td></td></tr></tbody></table>
<h4>Encodings requiring full ICU data<span><a class="mark" href="#util_encodings_requiring_full_icu_data" id="util_encodings_requiring_full_icu_data">#</a></span></h4>

















































































































































<table><thead><tr><th>Encoding</th><th>Aliases</th></tr></thead><tbody><tr><td><code>'ibm866'</code></td><td><code>'866'</code>, <code>'cp866'</code>, <code>'csibm866'</code></td></tr><tr><td><code>'iso-8859-2'</code></td><td><code>'csisolatin2'</code>, <code>'iso-ir-101'</code>, <code>'iso8859-2'</code>, <code>'iso88592'</code>, <code>'iso_8859-2'</code>, <code>'iso_8859-2:1987'</code>, <code>'l2'</code>, <code>'latin2'</code></td></tr><tr><td><code>'iso-8859-3'</code></td><td><code>'csisolatin3'</code>, <code>'iso-ir-109'</code>, <code>'iso8859-3'</code>, <code>'iso88593'</code>, <code>'iso_8859-3'</code>, <code>'iso_8859-3:1988'</code>, <code>'l3'</code>, <code>'latin3'</code></td></tr><tr><td><code>'iso-8859-4'</code></td><td><code>'csisolatin4'</code>, <code>'iso-ir-110'</code>, <code>'iso8859-4'</code>, <code>'iso88594'</code>, <code>'iso_8859-4'</code>, <code>'iso_8859-4:1988'</code>, <code>'l4'</code>, <code>'latin4'</code></td></tr><tr><td><code>'iso-8859-5'</code></td><td><code>'csisolatincyrillic'</code>, <code>'cyrillic'</code>, <code>'iso-ir-144'</code>, <code>'iso8859-5'</code>, <code>'iso88595'</code>, <code>'iso_8859-5'</code>, <code>'iso_8859-5:1988'</code></td></tr><tr><td><code>'iso-8859-6'</code></td><td><code>'arabic'</code>, <code>'asmo-708'</code>, <code>'csiso88596e'</code>, <code>'csiso88596i'</code>, <code>'csisolatinarabic'</code>, <code>'ecma-114'</code>, <code>'iso-8859-6-e'</code>, <code>'iso-8859-6-i'</code>, <code>'iso-ir-127'</code>, <code>'iso8859-6'</code>, <code>'iso88596'</code>, <code>'iso_8859-6'</code>, <code>'iso_8859-6:1987'</code></td></tr><tr><td><code>'iso-8859-7'</code></td><td><code>'csisolatingreek'</code>, <code>'ecma-118'</code>, <code>'elot_928'</code>, <code>'greek'</code>, <code>'greek8'</code>, <code>'iso-ir-126'</code>, <code>'iso8859-7'</code>, <code>'iso88597'</code>, <code>'iso_8859-7'</code>, <code>'iso_8859-7:1987'</code>, <code>'sun_eu_greek'</code></td></tr><tr><td><code>'iso-8859-8'</code></td><td><code>'csiso88598e'</code>, <code>'csisolatinhebrew'</code>, <code>'hebrew'</code>, <code>'iso-8859-8-e'</code>, <code>'iso-ir-138'</code>, <code>'iso8859-8'</code>, <code>'iso88598'</code>, <code>'iso_8859-8'</code>, <code>'iso_8859-8:1988'</code>, <code>'visual'</code></td></tr><tr><td><code>'iso-8859-8-i'</code></td><td><code>'csiso88598i'</code>, <code>'logical'</code></td></tr><tr><td><code>'iso-8859-10'</code></td><td><code>'csisolatin6'</code>, <code>'iso-ir-157'</code>, <code>'iso8859-10'</code>, <code>'iso885910'</code>, <code>'l6'</code>, <code>'latin6'</code></td></tr><tr><td><code>'iso-8859-13'</code></td><td><code>'iso8859-13'</code>, <code>'iso885913'</code></td></tr><tr><td><code>'iso-8859-14'</code></td><td><code>'iso8859-14'</code>, <code>'iso885914'</code></td></tr><tr><td><code>'iso-8859-15'</code></td><td><code>'csisolatin9'</code>, <code>'iso8859-15'</code>, <code>'iso885915'</code>, <code>'iso_8859-15'</code>, <code>'l9'</code></td></tr><tr><td><code>'koi8-r'</code></td><td><code>'cskoi8r'</code>, <code>'koi'</code>, <code>'koi8'</code>, <code>'koi8_r'</code></td></tr><tr><td><code>'koi8-u'</code></td><td><code>'koi8-ru'</code></td></tr><tr><td><code>'macintosh'</code></td><td><code>'csmacintosh'</code>, <code>'mac'</code>, <code>'x-mac-roman'</code></td></tr><tr><td><code>'windows-874'</code></td><td><code>'dos-874'</code>, <code>'iso-8859-11'</code>, <code>'iso8859-11'</code>, <code>'iso885911'</code>, <code>'tis-620'</code></td></tr><tr><td><code>'windows-1250'</code></td><td><code>'cp1250'</code>, <code>'x-cp1250'</code></td></tr><tr><td><code>'windows-1251'</code></td><td><code>'cp1251'</code>, <code>'x-cp1251'</code></td></tr><tr><td><code>'windows-1252'</code></td><td><code>'ansi_x3.4-1968'</code>, <code>'ascii'</code>, <code>'cp1252'</code>, <code>'cp819'</code>, <code>'csisolatin1'</code>, <code>'ibm819'</code>, <code>'iso-8859-1'</code>, <code>'iso-ir-100'</code>, <code>'iso8859-1'</code>, <code>'iso88591'</code>, <code>'iso_8859-1'</code>, <code>'iso_8859-1:1987'</code>, <code>'l1'</code>, <code>'latin1'</code>, <code>'us-ascii'</code>, <code>'x-cp1252'</code></td></tr><tr><td><code>'windows-1253'</code></td><td><code>'cp1253'</code>, <code>'x-cp1253'</code></td></tr><tr><td><code>'windows-1254'</code></td><td><code>'cp1254'</code>, <code>'csisolatin5'</code>, <code>'iso-8859-9'</code>, <code>'iso-ir-148'</code>, <code>'iso8859-9'</code>, <code>'iso88599'</code>, <code>'iso_8859-9'</code>, <code>'iso_8859-9:1989'</code>, <code>'l5'</code>, <code>'latin5'</code>, <code>'x-cp1254'</code></td></tr><tr><td><code>'windows-1255'</code></td><td><code>'cp1255'</code>, <code>'x-cp1255'</code></td></tr><tr><td><code>'windows-1256'</code></td><td><code>'cp1256'</code>, <code>'x-cp1256'</code></td></tr><tr><td><code>'windows-1257'</code></td><td><code>'cp1257'</code>, <code>'x-cp1257'</code></td></tr><tr><td><code>'windows-1258'</code></td><td><code>'cp1258'</code>, <code>'x-cp1258'</code></td></tr><tr><td><code>'x-mac-cyrillic'</code></td><td><code>'x-mac-ukrainian'</code></td></tr><tr><td><code>'gbk'</code></td><td><code>'chinese'</code>, <code>'csgb2312'</code>, <code>'csiso58gb231280'</code>, <code>'gb2312'</code>, <code>'gb_2312'</code>, <code>'gb_2312-80'</code>, <code>'iso-ir-58'</code>, <code>'x-gbk'</code></td></tr><tr><td><code>'gb18030'</code></td><td></td></tr><tr><td><code>'big5'</code></td><td><code>'big5-hkscs'</code>, <code>'cn-big5'</code>, <code>'csbig5'</code>, <code>'x-x-big5'</code></td></tr><tr><td><code>'euc-jp'</code></td><td><code>'cseucpkdfmtjapanese'</code>, <code>'x-euc-jp'</code></td></tr><tr><td><code>'iso-2022-jp'</code></td><td><code>'csiso2022jp'</code></td></tr><tr><td><code>'shift_jis'</code></td><td><code>'csshiftjis'</code>, <code>'ms932'</code>, <code>'ms_kanji'</code>, <code>'shift-jis'</code>, <code>'sjis'</code>, <code>'windows-31j'</code>, <code>'x-sjis'</code></td></tr><tr><td><code>'euc-kr'</code></td><td><code>'cseuckr'</code>, <code>'csksc56011987'</code>, <code>'iso-ir-149'</code>, <code>'korean'</code>, <code>'ks_c_5601-1987'</code>, <code>'ks_c_5601-1989'</code>, <code>'ksc5601'</code>, <code>'ksc_5601'</code>, <code>'windows-949'</code></td></tr></tbody></table>
<p>The <code>'iso-8859-16'</code> encoding listed in the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a>
is not supported.</p>
<h3><code>new TextDecoder([encoding[, options]])</code><span><a class="mark" href="#util_new_textdecoder_encoding_options" id="util_new_textdecoder_encoding_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>The class is now available on the global object.</p></td></tr>
<tr><td>v8.3.0</td>
<td><p><span>Added in: v8.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Identifies the <code>encoding</code> that this <code>TextDecoder</code> instance
supports. <strong>Default:</strong> <code>'utf-8'</code>.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>fatal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if decoding failures are fatal. This option is only
supported when ICU is enabled (see <a href="intl.html">Internationalization</a>). <strong>Default:</strong>
<code>false</code>.</li>
<li><code>ignoreBOM</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, the <code>TextDecoder</code> will include the byte
order mark in the decoded result. When <code>false</code>, the byte order mark will
be removed from the output. This option is only used when <code>encoding</code> is
<code>'utf-8'</code>, <code>'utf-16be'</code> or <code>'utf-16le'</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Creates an new <code>TextDecoder</code> instance. The <code>encoding</code> may specify one of the
supported encodings or an alias.</p>
<p>The <code>TextDecoder</code> class is also available on the global object.</p>
<h3><code>textDecoder.decode([input[, options]])</code><span><a class="mark" href="#util_textdecoder_decode_input_options" id="util_textdecoder_decode_input_options">#</a></span></h3>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> An <code>ArrayBuffer</code>, <code>DataView</code> or
<code>TypedArray</code> instance containing the encoded data.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>stream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <code>true</code> if additional chunks of data are expected.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>Decodes the <code>input</code> and returns a string. If <code>options.stream</code> is <code>true</code>, any
incomplete byte sequences occurring at the end of the <code>input</code> are buffered
internally and emitted after the next call to <code>textDecoder.decode()</code>.</p>
<p>If <code>textDecoder.fatal</code> is <code>true</code>, decoding errors that occur will result in a
<code>TypeError</code> being thrown.</p>
<h3><code>textDecoder.encoding</code><span><a class="mark" href="#util_textdecoder_encoding" id="util_textdecoder_encoding">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The encoding supported by the <code>TextDecoder</code> instance.</p>
<h3><code>textDecoder.fatal</code><span><a class="mark" href="#util_textdecoder_fatal" id="util_textdecoder_fatal">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The value will be <code>true</code> if decoding errors result in a <code>TypeError</code> being
thrown.</p>
<h3><code>textDecoder.ignoreBOM</code><span><a class="mark" href="#util_textdecoder_ignorebom" id="util_textdecoder_ignorebom">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The value will be <code>true</code> if the decoding result will include the byte order
mark.</p>
<h2>Class: <code>util.TextEncoder</code><span><a class="mark" href="#util_class_util_textencoder" id="util_class_util_textencoder">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.0.0</td>
<td><p>The class is now available on the global object.</p></td></tr>
<tr><td>v8.3.0</td>
<td><p><span>Added in: v8.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An implementation of the <a href="https://encoding.spec.whatwg.org/">WHATWG Encoding Standard</a> <code>TextEncoder</code> API. All
instances of <code>TextEncoder</code> only support UTF-8 encoding.</p>
<pre><code class="language-js">const encoder = new TextEncoder();
const uint8array = encoder.encode('this is some data');
</code></pre>
<p>The <code>TextEncoder</code> class is also available on the global object.</p>
<h3><code>textEncoder.encode([input])</code><span><a class="mark" href="#util_textencoder_encode_input" id="util_textencoder_encode_input">#</a></span></h3>
<ul>
<li><code>input</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The text to encode. <strong>Default:</strong> an empty string.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
</ul>
<p>UTF-8 encodes the <code>input</code> string and returns a <code>Uint8Array</code> containing the
encoded bytes.</p>
<h3><code>textEncoder.encodeInto(src, dest)</code><span><a class="mark" href="#util_textencoder_encodeinto_src_dest" id="util_textencoder_encodeinto_src_dest">#</a></span></h3>
<ul>
<li><code>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The text to encode.</li>
<li><code>dest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> The array to hold the encode result.</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>read</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The read Unicode code units of src.</li>
<li><code>written</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The written UTF-8 bytes of dest.</li>
</ul>
</li>
</ul>
<p>UTF-8 encodes the <code>src</code> string to the <code>dest</code> Uint8Array and returns an object
containing the read Unicode code units and written UTF-8 bytes.</p>
<pre><code class="language-js">const encoder = new TextEncoder();
const src = 'this is some data';
const dest = new Uint8Array(10);
const { read, written } = encoder.encodeInto(src, dest);
</code></pre>
<h3><code>textEncoder.encoding</code><span><a class="mark" href="#util_textencoder_encoding" id="util_textencoder_encoding">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The encoding supported by the <code>TextEncoder</code> instance. Always set to <code>'utf-8'</code>.</p>
<h2><code>util.types</code><span><a class="mark" href="#util_util_types" id="util_util_types">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p><code>util.types</code> provides type checks for different kinds of built-in objects.
Unlike <code>instanceof</code> or <code>Object.prototype.toString.call(value)</code>, these checks do
not inspect properties of the object that are accessible from JavaScript (like
their prototype), and usually have the overhead of calling into C++.</p>
<p>The result generally does not make any guarantees about what kinds of
properties or behavior a value exposes in JavaScript. They are primarily
useful for addon developers who prefer to do type checking in JavaScript.</p>
<h3><code>util.types.isAnyArrayBuffer(value)</code><span><a class="mark" href="#util_util_types_isanyarraybuffer_value" id="util_util_types_isanyarraybuffer_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instance.</p>
<p>See also <a href="#util_util_types_isarraybuffer_value"><code>util.types.isArrayBuffer()</code></a> and
<a href="#util_util_types_issharedarraybuffer_value"><code>util.types.isSharedArrayBuffer()</code></a>.</p>
<pre><code class="language-js">util.types.isAnyArrayBuffer(new ArrayBuffer());  // Returns true
util.types.isAnyArrayBuffer(new SharedArrayBuffer());  // Returns true
</code></pre>
<h3><code>util.types.isArrayBufferView(value)</code><span><a class="mark" href="#util_util_types_isarraybufferview_value" id="util_util_types_isarraybufferview_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an instance of one of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>
views, such as typed array objects or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><code>DataView</code></a>. Equivalent to
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView"><code>ArrayBuffer.isView()</code></a>.</p>
<pre><code class="language-js">util.types.isArrayBufferView(new Int8Array());  // true
util.types.isArrayBufferView(Buffer.from('hello world')); // true
util.types.isArrayBufferView(new DataView(new ArrayBuffer(16)));  // true
util.types.isArrayBufferView(new ArrayBuffer());  // false
</code></pre>
<h3><code>util.types.isArgumentsObject(value)</code><span><a class="mark" href="#util_util_types_isargumentsobject_value" id="util_util_types_isargumentsobject_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an <code>arguments</code> object.</p>
<!-- eslint-disable prefer-rest-params -->
<pre><code class="language-js">function foo() {
  util.types.isArgumentsObject(arguments);  // Returns true
}
</code></pre>
<h3><code>util.types.isArrayBuffer(value)</code><span><a class="mark" href="#util_util_types_isarraybuffer_value" id="util_util_types_isarraybuffer_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> instance.
This does <em>not</em> include <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instances. Usually, it is
desirable to test for both; See <a href="#util_util_types_isanyarraybuffer_value"><code>util.types.isAnyArrayBuffer()</code></a> for that.</p>
<pre><code class="language-js">util.types.isArrayBuffer(new ArrayBuffer());  // Returns true
util.types.isArrayBuffer(new SharedArrayBuffer());  // Returns false
</code></pre>
<h3><code>util.types.isAsyncFunction(value)</code><span><a class="mark" href="#util_util_types_isasyncfunction_value" id="util_util_types_isasyncfunction_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async function</a>.
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.</p>
<pre><code class="language-js">util.types.isAsyncFunction(function foo() {});  // Returns false
util.types.isAsyncFunction(async function foo() {});  // Returns true
</code></pre>
<h3><code>util.types.isBigInt64Array(value)</code><span><a class="mark" href="#util_util_types_isbigint64array_value" id="util_util_types_isbigint64array_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a <code>BigInt64Array</code> instance.</p>
<pre><code class="language-js">util.types.isBigInt64Array(new BigInt64Array());   // Returns true
util.types.isBigInt64Array(new BigUint64Array());  // Returns false
</code></pre>
<h3><code>util.types.isBigUint64Array(value)</code><span><a class="mark" href="#util_util_types_isbiguint64array_value" id="util_util_types_isbiguint64array_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a <code>BigUint64Array</code> instance.</p>
<pre><code class="language-js">util.types.isBigUint64Array(new BigInt64Array());   // Returns false
util.types.isBigUint64Array(new BigUint64Array());  // Returns true
</code></pre>
<h3><code>util.types.isBooleanObject(value)</code><span><a class="mark" href="#util_util_types_isbooleanobject_value" id="util_util_types_isbooleanobject_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a boolean object, e.g. created
by <code>new Boolean()</code>.</p>
<pre><code class="language-js">util.types.isBooleanObject(false);  // Returns false
util.types.isBooleanObject(true);   // Returns false
util.types.isBooleanObject(new Boolean(false)); // Returns true
util.types.isBooleanObject(new Boolean(true));  // Returns true
util.types.isBooleanObject(Boolean(false)); // Returns false
util.types.isBooleanObject(Boolean(true));  // Returns false
</code></pre>
<h3><code>util.types.isBoxedPrimitive(value)</code><span><a class="mark" href="#util_util_types_isboxedprimitive_value" id="util_util_types_isboxedprimitive_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.11.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is any boxed primitive object, e.g. created
by <code>new Boolean()</code>, <code>new String()</code> or <code>Object(Symbol())</code>.</p>
<p>For example:</p>
<pre><code class="language-js">util.types.isBoxedPrimitive(false); // Returns false
util.types.isBoxedPrimitive(new Boolean(false)); // Returns true
util.types.isBoxedPrimitive(Symbol('foo')); // Returns false
util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true
util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true
</code></pre>
<h3><code>util.types.isDataView(value)</code><span><a class="mark" href="#util_util_types_isdataview_value" id="util_util_types_isdataview_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><code>DataView</code></a> instance.</p>
<pre><code class="language-js">const ab = new ArrayBuffer(20);
util.types.isDataView(new DataView(ab));  // Returns true
util.types.isDataView(new Float64Array());  // Returns false
</code></pre>
<p>See also <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView"><code>ArrayBuffer.isView()</code></a>.</p>
<h3><code>util.types.isDate(value)</code><span><a class="mark" href="#util_util_types_isdate_value" id="util_util_types_isdate_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date"><code>Date</code></a> instance.</p>
<pre><code class="language-js">util.types.isDate(new Date());  // Returns true
</code></pre>
<h3><code>util.types.isExternal(value)</code><span><a class="mark" href="#util_util_types_isexternal_value" id="util_util_types_isexternal_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a native <code>External</code> value.</p>
<p>A native <code>External</code> value is a special type of object that contains a
raw C++ pointer (<code>void*</code>) for access from native code, and has no other
properties. Such objects are created either by Node.js internals or native
addons. In JavaScript, they are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze">frozen</a> objects with a
<code>null</code> prototype.</p>
<pre><code class="language-c">#include &#x3C;js_native_api.h>
#include &#x3C;stdlib.h>
napi_value result;
static napi_value MyNapi(napi_env env, napi_callback_info info) {
  int* raw = (int*) malloc(1024);
  napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &#x26;result);
  if (status != napi_ok) {
    napi_throw_error(env, NULL, "napi_create_external failed");
    return NULL;
  }
  return result;
}
...
DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
...
</code></pre>
<pre><code class="language-js">const native = require('napi_addon.node');
const data = native.myNapi();
util.types.isExternal(data); // returns true
util.types.isExternal(0); // returns false
util.types.isExternal(new String('foo')); // returns false
</code></pre>
<p>For further information on <code>napi_create_external</code>, refer to
<a href="#n_api_napi_create_external"><code>napi_create_external()</code></a>.</p>
<h3><code>util.types.isFloat32Array(value)</code><span><a class="mark" href="#util_util_types_isfloat32array_value" id="util_util_types_isfloat32array_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array"><code>Float32Array</code></a> instance.</p>
<pre><code class="language-js">util.types.isFloat32Array(new ArrayBuffer());  // Returns false
util.types.isFloat32Array(new Float32Array());  // Returns true
util.types.isFloat32Array(new Float64Array());  // Returns false
</code></pre>
<h3><code>util.types.isFloat64Array(value)</code><span><a class="mark" href="#util_util_types_isfloat64array_value" id="util_util_types_isfloat64array_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array"><code>Float64Array</code></a> instance.</p>
<pre><code class="language-js">util.types.isFloat64Array(new ArrayBuffer());  // Returns false
util.types.isFloat64Array(new Uint8Array());  // Returns false
util.types.isFloat64Array(new Float64Array());  // Returns true
</code></pre>
<h3><code>util.types.isGeneratorFunction(value)</code><span><a class="mark" href="#util_util_types_isgeneratorfunction_value" id="util_util_types_isgeneratorfunction_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a generator function.
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.</p>
<pre><code class="language-js">util.types.isGeneratorFunction(function foo() {});  // Returns false
util.types.isGeneratorFunction(function* foo() {});  // Returns true
</code></pre>
<h3><code>util.types.isGeneratorObject(value)</code><span><a class="mark" href="#util_util_types_isgeneratorobject_value" id="util_util_types_isgeneratorobject_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a generator object as returned from a
built-in generator function.
This only reports back what the JavaScript engine is seeing;
in particular, the return value may not match the original source code if
a transpilation tool was used.</p>
<pre><code class="language-js">function* foo() {}
const generator = foo();
util.types.isGeneratorObject(generator);  // Returns true
</code></pre>
<h3><code>util.types.isInt8Array(value)</code><span><a class="mark" href="#util_util_types_isint8array_value" id="util_util_types_isint8array_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array"><code>Int8Array</code></a> instance.</p>
<pre><code class="language-js">util.types.isInt8Array(new ArrayBuffer());  // Returns false
util.types.isInt8Array(new Int8Array());  // Returns true
util.types.isInt8Array(new Float64Array());  // Returns false
</code></pre>
<h3><code>util.types.isInt16Array(value)</code><span><a class="mark" href="#util_util_types_isint16array_value" id="util_util_types_isint16array_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array"><code>Int16Array</code></a> instance.</p>
<pre><code class="language-js">util.types.isInt16Array(new ArrayBuffer());  // Returns false
util.types.isInt16Array(new Int16Array());  // Returns true
util.types.isInt16Array(new Float64Array());  // Returns false
</code></pre>
<h3><code>util.types.isInt32Array(value)</code><span><a class="mark" href="#util_util_types_isint32array_value" id="util_util_types_isint32array_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array"><code>Int32Array</code></a> instance.</p>
<pre><code class="language-js">util.types.isInt32Array(new ArrayBuffer());  // Returns false
util.types.isInt32Array(new Int32Array());  // Returns true
util.types.isInt32Array(new Float64Array());  // Returns false
</code></pre>
<h3><code>util.types.isMap(value)</code><span><a class="mark" href="#util_util_types_ismap_value" id="util_util_types_ismap_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> instance.</p>
<pre><code class="language-js">util.types.isMap(new Map());  // Returns true
</code></pre>
<h3><code>util.types.isMapIterator(value)</code><span><a class="mark" href="#util_util_types_ismapiterator_value" id="util_util_types_ismapiterator_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an iterator returned for a built-in
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"><code>Map</code></a> instance.</p>
<pre><code class="language-js">const map = new Map();
util.types.isMapIterator(map.keys());  // Returns true
util.types.isMapIterator(map.values());  // Returns true
util.types.isMapIterator(map.entries());  // Returns true
util.types.isMapIterator(map[Symbol.iterator]());  // Returns true
</code></pre>
<h3><code>util.types.isModuleNamespaceObject(value)</code><span><a class="mark" href="#util_util_types_ismodulenamespaceobject_value" id="util_util_types_ismodulenamespaceobject_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an instance of a <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects">Module Namespace Object</a>.</p>
<!-- eslint-skip -->
<pre><code class="language-js">import * as ns from './a.js';

util.types.isModuleNamespaceObject(ns);  // Returns true
</code></pre>
<h3><code>util.types.isNativeError(value)</code><span><a class="mark" href="#util_util_types_isnativeerror_value" id="util_util_types_isnativeerror_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an instance of a built-in <a href="#errors_class_error"><code>Error</code></a> type.</p>
<pre><code class="language-js">util.types.isNativeError(new Error());  // Returns true
util.types.isNativeError(new TypeError());  // Returns true
util.types.isNativeError(new RangeError());  // Returns true
</code></pre>
<h3><code>util.types.isNumberObject(value)</code><span><a class="mark" href="#util_util_types_isnumberobject_value" id="util_util_types_isnumberobject_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a number object, e.g. created
by <code>new Number()</code>.</p>
<pre><code class="language-js">util.types.isNumberObject(0);  // Returns false
util.types.isNumberObject(new Number(0));   // Returns true
</code></pre>
<h3><code>util.types.isPromise(value)</code><span><a class="mark" href="#util_util_types_ispromise_value" id="util_util_types_ispromise_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise"><code>Promise</code></a>.</p>
<pre><code class="language-js">util.types.isPromise(Promise.resolve(42));  // Returns true
</code></pre>
<h3><code>util.types.isProxy(value)</code><span><a class="mark" href="#util_util_types_isproxy_value" id="util_util_types_isproxy_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy"><code>Proxy</code></a> instance.</p>
<pre><code class="language-js">const target = {};
const proxy = new Proxy(target, {});
util.types.isProxy(target);  // Returns false
util.types.isProxy(proxy);  // Returns true
</code></pre>
<h3><code>util.types.isRegExp(value)</code><span><a class="mark" href="#util_util_types_isregexp_value" id="util_util_types_isregexp_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a regular expression object.</p>
<pre><code class="language-js">util.types.isRegExp(/abc/);  // Returns true
util.types.isRegExp(new RegExp('abc'));  // Returns true
</code></pre>
<h3><code>util.types.isSet(value)</code><span><a class="mark" href="#util_util_types_isset_value" id="util_util_types_isset_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a> instance.</p>
<pre><code class="language-js">util.types.isSet(new Set());  // Returns true
</code></pre>
<h3><code>util.types.isSetIterator(value)</code><span><a class="mark" href="#util_util_types_issetiterator_value" id="util_util_types_issetiterator_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is an iterator returned for a built-in
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</code></a> instance.</p>
<pre><code class="language-js">const set = new Set();
util.types.isSetIterator(set.keys());  // Returns true
util.types.isSetIterator(set.values());  // Returns true
util.types.isSetIterator(set.entries());  // Returns true
util.types.isSetIterator(set[Symbol.iterator]());  // Returns true
</code></pre>
<h3><code>util.types.isSharedArrayBuffer(value)</code><span><a class="mark" href="#util_util_types_issharedarraybuffer_value" id="util_util_types_issharedarraybuffer_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instance.
This does <em>not</em> include <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> instances. Usually, it is
desirable to test for both; See <a href="#util_util_types_isanyarraybuffer_value"><code>util.types.isAnyArrayBuffer()</code></a> for that.</p>
<pre><code class="language-js">util.types.isSharedArrayBuffer(new ArrayBuffer());  // Returns false
util.types.isSharedArrayBuffer(new SharedArrayBuffer());  // Returns true
</code></pre>
<h3><code>util.types.isStringObject(value)</code><span><a class="mark" href="#util_util_types_isstringobject_value" id="util_util_types_isstringobject_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a string object, e.g. created
by <code>new String()</code>.</p>
<pre><code class="language-js">util.types.isStringObject('foo');  // Returns false
util.types.isStringObject(new String('foo'));   // Returns true
</code></pre>
<h3><code>util.types.isSymbolObject(value)</code><span><a class="mark" href="#util_util_types_issymbolobject_value" id="util_util_types_issymbolobject_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a symbol object, created
by calling <code>Object()</code> on a <code>Symbol</code> primitive.</p>
<pre><code class="language-js">const symbol = Symbol('foo');
util.types.isSymbolObject(symbol);  // Returns false
util.types.isSymbolObject(Object(symbol));   // Returns true
</code></pre>
<h3><code>util.types.isTypedArray(value)</code><span><a class="mark" href="#util_util_types_istypedarray_value" id="util_util_types_istypedarray_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instance.</p>
<pre><code class="language-js">util.types.isTypedArray(new ArrayBuffer());  // Returns false
util.types.isTypedArray(new Uint8Array());  // Returns true
util.types.isTypedArray(new Float64Array());  // Returns true
</code></pre>
<p>See also <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView"><code>ArrayBuffer.isView()</code></a>.</p>
<h3><code>util.types.isUint8Array(value)</code><span><a class="mark" href="#util_util_types_isuint8array_value" id="util_util_types_isuint8array_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> instance.</p>
<pre><code class="language-js">util.types.isUint8Array(new ArrayBuffer());  // Returns false
util.types.isUint8Array(new Uint8Array());  // Returns true
util.types.isUint8Array(new Float64Array());  // Returns false
</code></pre>
<h3><code>util.types.isUint8ClampedArray(value)</code><span><a class="mark" href="#util_util_types_isuint8clampedarray_value" id="util_util_types_isuint8clampedarray_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray"><code>Uint8ClampedArray</code></a> instance.</p>
<pre><code class="language-js">util.types.isUint8ClampedArray(new ArrayBuffer());  // Returns false
util.types.isUint8ClampedArray(new Uint8ClampedArray());  // Returns true
util.types.isUint8ClampedArray(new Float64Array());  // Returns false
</code></pre>
<h3><code>util.types.isUint16Array(value)</code><span><a class="mark" href="#util_util_types_isuint16array_value" id="util_util_types_isuint16array_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array"><code>Uint16Array</code></a> instance.</p>
<pre><code class="language-js">util.types.isUint16Array(new ArrayBuffer());  // Returns false
util.types.isUint16Array(new Uint16Array());  // Returns true
util.types.isUint16Array(new Float64Array());  // Returns false
</code></pre>
<h3><code>util.types.isUint32Array(value)</code><span><a class="mark" href="#util_util_types_isuint32array_value" id="util_util_types_isuint32array_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array"><code>Uint32Array</code></a> instance.</p>
<pre><code class="language-js">util.types.isUint32Array(new ArrayBuffer());  // Returns false
util.types.isUint32Array(new Uint32Array());  // Returns true
util.types.isUint32Array(new Float64Array());  // Returns false
</code></pre>
<h3><code>util.types.isWeakMap(value)</code><span><a class="mark" href="#util_util_types_isweakmap_value" id="util_util_types_isweakmap_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap"><code>WeakMap</code></a> instance.</p>
<pre><code class="language-js">util.types.isWeakMap(new WeakMap());  // Returns true
</code></pre>
<h3><code>util.types.isWeakSet(value)</code><span><a class="mark" href="#util_util_types_isweakset_value" id="util_util_types_isweakset_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet"><code>WeakSet</code></a> instance.</p>
<pre><code class="language-js">util.types.isWeakSet(new WeakSet());  // Returns true
</code></pre>
<h3><code>util.types.isWebAssemblyCompiledModule(value)</code><span><a class="mark" href="#util_util_types_iswebassemblycompiledmodule_value" id="util_util_types_iswebassemblycompiledmodule_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the value is a built-in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module"><code>WebAssembly.Module</code></a> instance.</p>
<pre><code class="language-js">const module = new WebAssembly.Module(wasmBuffer);
util.types.isWebAssemblyCompiledModule(module);  // Returns true
</code></pre>
<h2>Deprecated APIs<span><a class="mark" href="#util_deprecated_apis" id="util_deprecated_apis">#</a></span></h2>
<p>The following APIs are deprecated and should no longer be used. Existing
applications and modules should be updated to find alternative approaches.</p>
<h3><code>util._extend(target, source)</code><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>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign"><code>Object.assign()</code></a> instead.</div><p></p>
<ul>
<li><code>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>source</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<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><code>util.isArray(object)</code><span><a class="mark" href="#util_util_isarray_object" id="util_util_isarray_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray"><code>Array.isArray()</code></a> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Alias for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray"><code>Array.isArray()</code></a>.</p>
<p>Returns <code>true</code> if the given <code>object</code> is an <code>Array</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isArray([]);
// Returns: true
util.isArray(new Array());
// Returns: true
util.isArray({});
// Returns: false
</code></pre>
<h3><code>util.isBoolean(object)</code><span><a class="mark" href="#util_util_isboolean_object" id="util_util_isboolean_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'boolean'</code> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Boolean</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isBoolean(1);
// Returns: false
util.isBoolean(0);
// Returns: false
util.isBoolean(false);
// Returns: true
</code></pre>
<h3><code>util.isBuffer(object)</code><span><a class="mark" href="#util_util_isbuffer_object" id="util_util_isbuffer_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#buffer_class_method_buffer_isbuffer_obj"><code>Buffer.isBuffer()</code></a> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Buffer</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isBuffer({ length: 0 });
// Returns: false
util.isBuffer([]);
// Returns: false
util.isBuffer(Buffer.from('hello world'));
// Returns: true
</code></pre>
<h3><code>util.isDate(object)</code><span><a class="mark" href="#util_util_isdate_object" id="util_util_isdate_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#util_util_types_isdate_value"><code>util.types.isDate()</code></a> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Date</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isDate(new Date());
// Returns: true
util.isDate(Date());
// false (without 'new' returns a String)
util.isDate({});
// Returns: false
</code></pre>
<h3><code>util.isError(object)</code><span><a class="mark" href="#util_util_iserror_object" id="util_util_iserror_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#util_util_types_isnativeerror_value"><code>util.types.isNativeError()</code></a> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is an <a href="#errors_class_error"><code>Error</code></a>. Otherwise, returns
<code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isError(new Error());
// Returns: true
util.isError(new TypeError());
// Returns: true
util.isError({ name: 'Error', message: 'an error occurred' });
// Returns: false
</code></pre>
<p>This method relies on <code>Object.prototype.toString()</code> behavior. It is
possible to obtain an incorrect result when the <code>object</code> argument manipulates
<code>@@toStringTag</code>.</p>
<pre><code class="language-js">const util = require('util');
const obj = { name: 'Error', message: 'an error occurred' };

util.isError(obj);
// Returns: false
obj[Symbol.toStringTag] = 'Error';
util.isError(obj);
// Returns: true
</code></pre>
<h3><code>util.isFunction(object)</code><span><a class="mark" href="#util_util_isfunction_object" id="util_util_isfunction_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'function'</code> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Function</code>. Otherwise, returns
<code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

function Foo() {}
const Bar = () => {};

util.isFunction({});
// Returns: false
util.isFunction(Foo);
// Returns: true
util.isFunction(Bar);
// Returns: true
</code></pre>
<h3><code>util.isNull(object)</code><span><a class="mark" href="#util_util_isnull_object" id="util_util_isnull_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>value === null</code> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is strictly <code>null</code>. Otherwise, returns
<code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isNull(0);
// Returns: false
util.isNull(undefined);
// Returns: false
util.isNull(null);
// Returns: true
</code></pre>
<h3><code>util.isNullOrUndefined(object)</code><span><a class="mark" href="#util_util_isnullorundefined_object" id="util_util_isnullorundefined_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use
<code>value === undefined || value === null</code> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is <code>null</code> or <code>undefined</code>. Otherwise,
returns <code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isNullOrUndefined(0);
// Returns: false
util.isNullOrUndefined(undefined);
// Returns: true
util.isNullOrUndefined(null);
// Returns: true
</code></pre>
<h3><code>util.isNumber(object)</code><span><a class="mark" href="#util_util_isnumber_object" id="util_util_isnumber_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'number'</code> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Number</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isNumber(false);
// Returns: false
util.isNumber(Infinity);
// Returns: true
util.isNumber(0);
// Returns: true
util.isNumber(NaN);
// Returns: true
</code></pre>
<h3><code>util.isObject(object)</code><span><a class="mark" href="#util_util_isobject_object" id="util_util_isobject_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated:
Use <code>value !== null &#x26;&#x26; typeof value === 'object'</code> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is strictly an <code>Object</code> <strong>and</strong> not a
<code>Function</code> (even though functions are objects in JavaScript).
Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isObject(5);
// Returns: false
util.isObject(null);
// Returns: false
util.isObject({});
// Returns: true
util.isObject(() => {});
// Returns: false
</code></pre>
<h3><code>util.isPrimitive(object)</code><span><a class="mark" href="#util_util_isprimitive_object" id="util_util_isprimitive_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use
<code>(typeof value !== 'object' &#x26;&#x26; typeof value !== 'function') || value === null</code>
instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a primitive type. Otherwise, returns
<code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isPrimitive(5);
// Returns: true
util.isPrimitive('foo');
// Returns: true
util.isPrimitive(false);
// Returns: true
util.isPrimitive(null);
// Returns: true
util.isPrimitive(undefined);
// Returns: true
util.isPrimitive({});
// Returns: false
util.isPrimitive(() => {});
// Returns: false
util.isPrimitive(/^$/);
// Returns: false
util.isPrimitive(new Date());
// Returns: false
</code></pre>
<h3><code>util.isRegExp(object)</code><span><a class="mark" href="#util_util_isregexp_object" id="util_util_isregexp_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>RegExp</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isRegExp(/some regexp/);
// Returns: true
util.isRegExp(new RegExp('another regexp'));
// Returns: true
util.isRegExp({});
// Returns: false
</code></pre>
<h3><code>util.isString(object)</code><span><a class="mark" href="#util_util_isstring_object" id="util_util_isstring_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'string'</code> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>string</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isString('');
// Returns: true
util.isString('foo');
// Returns: true
util.isString(String('foo'));
// Returns: true
util.isString(5);
// Returns: false
</code></pre>
<h3><code>util.isSymbol(object)</code><span><a class="mark" href="#util_util_issymbol_object" id="util_util_issymbol_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>typeof value === 'symbol'</code> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is a <code>Symbol</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

util.isSymbol(5);
// Returns: false
util.isSymbol('foo');
// Returns: false
util.isSymbol(Symbol('foo'));
// Returns: true
</code></pre>
<h3><code>util.isUndefined(object)</code><span><a class="mark" href="#util_util_isundefined_object" id="util_util_isundefined_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span><span>Deprecated since: v4.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <code>value === undefined</code> instead.</div><p></p>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>object</code> is <code>undefined</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">const util = require('util');

const foo = undefined;
util.isUndefined(5);
// Returns: false
util.isUndefined(foo);
// Returns: true
util.isUndefined(null);
// Returns: false
</code></pre>
<h3><code>util.log(string)</code><span><a class="mark" href="#util_util_log_string" id="util_util_log_string">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span><span>Deprecated since: v6.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use a third party module instead.</div><p></p>
<ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The <code>util.log()</code> method prints the given <code>string</code> to <code>stdout</code> with an included
timestamp.</p>
<pre><code class="language-js">const util = require('util');

util.log('Timestamped message.');
</code></pre>
<h1>V8<span><a class="mark" href="#v8_v8" id="v8_v8">#</a></span></h1>

<p>The <code>v8</code> module exposes APIs that are specific to the version of <a href="https://developers.google.com/v8/">V8</a>
built into the Node.js binary. It can be accessed using:</p>
<pre><code class="language-js">const v8 = require('v8');
</code></pre>
<p>The APIs and implementation are subject to change at any time.</p>
<h2><code>v8.cachedDataVersionTag()</code><span><a class="mark" href="#v8_v8_cacheddataversiontag" id="v8_v8_cacheddataversiontag">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Returns an integer representing a "version tag" derived from the V8 version,
command line flags and detected CPU features. This is useful for determining
whether a <a href="#vm_constructor_new_vm_script_code_options"><code>vm.Script</code></a> <code>cachedData</code> buffer is compatible with this instance
of V8.</p>
<h2><code>v8.getHeapSpaceStatistics()</code><span><a class="mark" href="#v8_v8_getheapspacestatistics" id="v8_v8_getheapspacestatistics">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.5.0</td>
<td><p>Support values exceeding the 32-bit unsigned integer range.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p><span>Added in: v6.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
<p>Returns statistics about the V8 heap spaces, i.e. the segments which make up
the V8 heap. Neither the ordering of heap spaces, nor the availability of a
heap space can be guaranteed as the statistics are provided via the V8
<a href="https://v8docs.nodesource.com/node-13.2/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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;number></a></li>
</ul>
<pre><code class="language-json">[
  {
    "space_name": "new_space",
    "space_size": 2063872,
    "space_used_size": 951112,
    "space_available_size": 80824,
    "physical_space_size": 2063872
  },
  {
    "space_name": "old_space",
    "space_size": 3090560,
    "space_used_size": 2493792,
    "space_available_size": 0,
    "physical_space_size": 3090560
  },
  {
    "space_name": "code_space",
    "space_size": 1260160,
    "space_used_size": 644256,
    "space_available_size": 960,
    "physical_space_size": 1260160
  },
  {
    "space_name": "map_space",
    "space_size": 1094160,
    "space_used_size": 201608,
    "space_available_size": 0,
    "physical_space_size": 1094160
  },
  {
    "space_name": "large_object_space",
    "space_size": 0,
    "space_used_size": 0,
    "space_available_size": 1490980608,
    "physical_space_size": 0
  }
]
</code></pre>
<h2><code>v8.getHeapSnapshot()</code><span><a class="mark" href="#v8_v8_getheapsnapshot" id="v8_v8_getheapsnapshot">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.13.0</span>
</div>
<ul>
<li>Returns: <a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a> A Readable Stream containing the V8 heap snapshot</li>
</ul>
<p>Generates a snapshot of the current V8 heap and returns a Readable
Stream that may be used to read the JSON serialized representation.
This JSON stream format is intended to be used with tools such as
Chrome DevTools. The JSON schema is undocumented and specific to the
V8 engine, and may change from one version of V8 to the next.</p>
<pre><code class="language-js">const stream = v8.getHeapSnapshot();
stream.pipe(process.stdout);
</code></pre>
<h2><code>v8.getHeapStatistics()</code><span><a class="mark" href="#v8_v8_getheapstatistics" id="v8_v8_getheapstatistics">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v7.5.0</td>
<td><p>Support values exceeding the 32-bit unsigned integer range.</p></td></tr>
<tr><td>v7.2.0</td>
<td><p>Added <code>malloced_memory</code>, <code>peak_malloced_memory</code>, and <code>does_zap_garbage</code>.</p></td></tr>
<tr><td>v1.0.0</td>
<td><p><span>Added in: v1.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns an object with the following properties:</p>
<ul>
<li><code>total_heap_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;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">&#x3C;number></a></li>
<li><code>number_of_native_contexts</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>number_of_detached_contexts</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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>
<p><code>number_of_native_contexts</code> The value of native_context is the number of the
top-level contexts currently active. Increase of this number over time indicates
a memory leak.</p>
<p><code>number_of_detached_contexts</code> The value of detached_context is the number
of contexts that were detached and not yet garbage collected. This number
being non-zero indicates a potential memory leak.</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  total_heap_size: 7326976,
  total_heap_size_executable: 4194304,
  total_physical_size: 7326976,
  total_available_size: 1152656,
  used_heap_size: 3476208,
  heap_size_limit: 1535115264,
  malloced_memory: 16384,
  peak_malloced_memory: 1127496,
  does_zap_garbage: 0,
  number_of_native_contexts: 1,
  number_of_detached_contexts: 0
}
</code></pre>
<h2><code>v8.getHeapCodeStatistics()</code><span><a class="mark" href="#v8_v8_getheapcodestatistics" id="v8_v8_getheapcodestatistics">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.8.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>Returns an object with the following properties:</p>
<ul>
<li><code>code_and_metadata_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>bytecode_and_metadata_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>external_script_source_size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
  code_and_metadata_size: 212208,
  bytecode_and_metadata_size: 161368,
  external_script_source_size: 1410794
}
</code></pre>
<h2><code>v8.setFlagsFromString(flags)</code><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">&#x3C;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>.</p>
<p>Usage:</p>
<pre><code class="language-js">// Print GC events to stdout for one minute.
const v8 = require('v8');
v8.setFlagsFromString('--trace_gc');
setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
</code></pre>
<h2><code>v8.writeHeapSnapshot([filename])</code><span><a class="mark" href="#v8_v8_writeheapsnapshot_filename" id="v8_v8_writeheapsnapshot_filename">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.13.0</span>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The file path where the V8 heap snapshot is to be
saved. If not specified, a file name with the pattern
<code>'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'</code> will be
generated, where <code>{pid}</code> will be the PID of the Node.js process,
<code>{thread_id}</code> will be <code>0</code> when <code>writeHeapSnapshot()</code> is called from
the main Node.js thread or the id of a worker thread.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The filename where the snapshot was saved.</li>
</ul>
<p>Generates a snapshot of the current V8 heap and writes it to a JSON
file. This file is intended to be used with tools such as Chrome
DevTools. The JSON schema is undocumented and specific to the V8
engine, and may change from one version of V8 to the next.</p>
<p>A heap snapshot is specific to a single V8 isolate. When using
<a href="worker_threads.html">worker threads</a>, a heap snapshot generated from the main thread will
not contain any information about the workers, and vice versa.</p>
<pre><code class="language-js">const { writeHeapSnapshot } = require('v8');
const {
  Worker,
  isMainThread,
  parentPort
} = require('worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);

  worker.once('message', (filename) => {
    console.log(`worker heapdump: ${filename}`);
    // Now get a heapdump for the main thread.
    console.log(`main thread heapdump: ${writeHeapSnapshot()}`);
  });

  // Tell the worker to create a heapdump.
  worker.postMessage('heapdump');
} else {
  parentPort.once('message', (message) => {
    if (message === 'heapdump') {
      // Generate a heapdump for the worker
      // and return the filename to the parent.
      parentPort.postMessage(writeHeapSnapshot());
    }
  });
}
</code></pre>
<h2>Serialization API<span><a class="mark" href="#v8_serialization_api" id="v8_serialization_api">#</a></span></h2>
<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>.</p>
<p>The format is backward-compatible (i.e. safe to store to disk).
Equal JavaScript values may result in different serialized output.</p>
<h3><code>v8.serialize(value)</code><span><a class="mark" href="#v8_v8_serialize_value" id="v8_v8_serialize_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;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><code>v8.deserialize(buffer)</code><span><a class="mark" href="#v8_v8_deserialize_buffer" id="v8_v8_deserialize_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> A buffer returned by <a href="#v8_v8_serialize_value"><code>serialize()</code></a>.</li>
</ul>
<p>Uses a <a href="#v8_class_v8_defaultdeserializer"><code>DefaultDeserializer</code></a> with default options to read a JS value
from a buffer.</p>
<h3>Class: <code>v8.Serializer</code><span><a class="mark" href="#v8_class_v8_serializer" id="v8_class_v8_serializer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<h4><code>new Serializer()</code><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><code>serializer.writeHeader()</code><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><code>serializer.writeValue(value)</code><span><a class="mark" href="#v8_serializer_writevalue_value" id="v8_serializer_writevalue_value">#</a></span></h4>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Serializes a JavaScript value and adds the serialized representation to the
internal buffer.</p>
<p>This throws an error if <code>value</code> cannot be serialized.</p>
<h4><code>serializer.releaseBuffer()</code><span><a class="mark" href="#v8_serializer_releasebuffer" id="v8_serializer_releasebuffer">#</a></span></h4>
<ul>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Returns the stored internal buffer. This serializer should not be used once
the buffer is released. Calling this method results in undefined behavior
if a previous write has failed.</p>
<h4><code>serializer.transferArrayBuffer(id, arrayBuffer)</code><span><a class="mark" href="#v8_serializer_transferarraybuffer_id_arraybuffer" id="v8_serializer_transferarraybuffer_id_arraybuffer">#</a></span></h4>
<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;ArrayBuffer></a> An <code>ArrayBuffer</code> instance.</li>
</ul>
<p>Marks an <code>ArrayBuffer</code> as having 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><code>serializer.writeUint32(value)</code><span><a class="mark" href="#v8_serializer_writeuint32_value" id="v8_serializer_writeuint32_value">#</a></span></h4>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Write a raw 32-bit unsigned integer.
For use inside of a custom <a href="#v8_serializer_writehostobject_object"><code>serializer._writeHostObject()</code></a>.</p>
<h4><code>serializer.writeUint64(hi, lo)</code><span><a class="mark" href="#v8_serializer_writeuint64_hi_lo" id="v8_serializer_writeuint64_hi_lo">#</a></span></h4>
<ul>
<li><code>hi</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>lo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Write a raw 64-bit unsigned integer, split into high and low 32-bit parts.
For use inside of a custom <a href="#v8_serializer_writehostobject_object"><code>serializer._writeHostObject()</code></a>.</p>
<h4><code>serializer.writeDouble(value)</code><span><a class="mark" href="#v8_serializer_writedouble_value" id="v8_serializer_writedouble_value">#</a></span></h4>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Write a JS <code>number</code> value.
For use inside of a custom <a href="#v8_serializer_writehostobject_object"><code>serializer._writeHostObject()</code></a>.</p>
<h4><code>serializer.writeRawBytes(buffer)</code><span><a class="mark" href="#v8_serializer_writerawbytes_buffer" id="v8_serializer_writerawbytes_buffer">#</a></span></h4>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a></li>
</ul>
<p>Write raw bytes into the serializer’s internal buffer. The deserializer
will require a way to compute the length of the buffer.
For use inside of a custom <a href="#v8_serializer_writehostobject_object"><code>serializer._writeHostObject()</code></a>.</p>
<h4><code>serializer._writeHostObject(object)</code><span><a class="mark" href="#v8_serializer_writehostobject_object" id="v8_serializer_writehostobject_object">#</a></span></h4>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>This method is called to write some kind of host object, i.e. an object created
by native C++ bindings. If it is not possible to serialize <code>object</code>, a suitable
exception should be thrown.</p>
<p>This method is not present on the <code>Serializer</code> class itself but can be provided
by subclasses.</p>
<h4><code>serializer._getDataCloneError(message)</code><span><a class="mark" href="#v8_serializer_getdatacloneerror_message" id="v8_serializer_getdatacloneerror_message">#</a></span></h4>
<ul>
<li><code>message</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>This method is called to generate error objects that will be thrown when an
object can not be cloned.</p>
<p>This method defaults to the <a href="#errors_class_error"><code>Error</code></a> constructor and can be overridden on
subclasses.</p>
<h4><code>serializer._getSharedArrayBufferId(sharedArrayBuffer)</code><span><a class="mark" href="#v8_serializer_getsharedarraybufferid_sharedarraybuffer" id="v8_serializer_getsharedarraybufferid_sharedarraybuffer">#</a></span></h4>
<ul>
<li><code>sharedArrayBuffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type">&#x3C;SharedArrayBuffer></a></li>
</ul>
<p>This method is called when the serializer is going to serialize a
<code>SharedArrayBuffer</code> object. It must return an unsigned 32-bit integer ID for
the object, using the same ID if this <code>SharedArrayBuffer</code> has already been
serialized. When deserializing, this ID will be passed to
<a href="#v8_deserializer_transferarraybuffer_id_arraybuffer"><code>deserializer.transferArrayBuffer()</code></a>.</p>
<p>If the object cannot be serialized, an exception should be thrown.</p>
<p>This method is not present on the <code>Serializer</code> class itself but can be provided
by subclasses.</p>
<h4><code>serializer._setTreatArrayBufferViewsAsHostObjects(flag)</code><span><a class="mark" href="#v8_serializer_settreatarraybufferviewsashostobjects_flag" id="v8_serializer_settreatarraybufferviewsashostobjects_flag">#</a></span></h4>
<ul>
<li><code>flag</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> <strong>Default:</strong> <code>false</code></li>
</ul>
<p>Indicate whether to treat <code>TypedArray</code> and <code>DataView</code> objects as
host objects, i.e. pass them to <a href="#v8_serializer_writehostobject_object"><code>serializer._writeHostObject()</code></a>.</p>
<h3>Class: <code>v8.Deserializer</code><span><a class="mark" href="#v8_class_v8_deserializer" id="v8_class_v8_deserializer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<h4><code>new Deserializer(buffer)</code><span><a class="mark" href="#v8_new_deserializer_buffer" id="v8_new_deserializer_buffer">#</a></span></h4>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> A buffer returned by
<a href="#v8_serializer_releasebuffer"><code>serializer.releaseBuffer()</code></a>.</li>
</ul>
<p>Creates a new <code>Deserializer</code> object.</p>
<h4><code>deserializer.readHeader()</code><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><code>deserializer.readValue()</code><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><code>deserializer.transferArrayBuffer(id, arrayBuffer)</code><span><a class="mark" href="#v8_deserializer_transferarraybuffer_id_arraybuffer" id="v8_deserializer_transferarraybuffer_id_arraybuffer">#</a></span></h4>
<ul>
<li><code>id</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer" class="type">&#x3C;SharedArrayBuffer></a> An <code>ArrayBuffer</code> instance.</li>
</ul>
<p>Marks an <code>ArrayBuffer</code> as having 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><code>deserializer.getWireFormatVersion()</code><span><a class="mark" href="#v8_deserializer_getwireformatversion" id="v8_deserializer_getwireformatversion">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Reads the underlying wire format version. Likely mostly to be useful to
legacy code reading old wire format versions. May not be called before
<code>.readHeader()</code>.</p>
<h4><code>deserializer.readUint32()</code><span><a class="mark" href="#v8_deserializer_readuint32" id="v8_deserializer_readuint32">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>Read a raw 32-bit unsigned integer and return it.
For use inside of a custom <a href="#v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h4><code>deserializer.readUint64()</code><span><a class="mark" href="#v8_deserializer_readuint64" id="v8_deserializer_readuint64">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer[]></a></li>
</ul>
<p>Read a raw 64-bit unsigned integer and return it as an array <code>[hi, lo]</code>
with two 32-bit unsigned integer entries.
For use inside of a custom <a href="#v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h4><code>deserializer.readDouble()</code><span><a class="mark" href="#v8_deserializer_readdouble" id="v8_deserializer_readdouble">#</a></span></h4>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Read a JS <code>number</code> value.
For use inside of a custom <a href="#v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h4><code>deserializer.readRawBytes(length)</code><span><a class="mark" href="#v8_deserializer_readrawbytes_length" id="v8_deserializer_readrawbytes_length">#</a></span></h4>
<ul>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Read raw bytes from the deserializer’s internal buffer. The <code>length</code> parameter
must correspond to the length of the buffer that was passed to
<a href="#v8_serializer_writerawbytes_buffer"><code>serializer.writeRawBytes()</code></a>.
For use inside of a custom <a href="#v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h4><code>deserializer._readHostObject()</code><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: <code>v8.DefaultSerializer</code><span><a class="mark" href="#v8_class_v8_defaultserializer" id="v8_class_v8_defaultserializer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>A subclass of <a href="#v8_class_v8_serializer"><code>Serializer</code></a> that serializes <code>TypedArray</code>
(in particular <a href="buffer.html"><code>Buffer</code></a>) and <code>DataView</code> objects as host objects, and only
stores the part of their underlying <code>ArrayBuffer</code>s that they are referring to.</p>
<h3>Class: <code>v8.DefaultDeserializer</code><span><a class="mark" href="#v8_class_v8_defaultdeserializer" id="v8_class_v8_defaultdeserializer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>A subclass of <a href="#v8_class_v8_deserializer"><code>Deserializer</code></a> corresponding to the format written by
<a href="#v8_class_v8_defaultserializer"><code>DefaultSerializer</code></a>.</p>
<h1>VM (executing JavaScript)<span><a class="mark" href="#vm_vm_executing_javascript" id="vm_vm_executing_javascript">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>

<p>The <code>vm</code> module enables compiling and running code within V8 Virtual
Machine contexts. <strong>The <code>vm</code> module is not a security mechanism. Do
not use it to run untrusted code</strong>.</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 different V8 Context. This means
invoked code has a different global object than the invoking code.</p>
<p>One can provide the context by <a href="#vm_what_does_it_mean_to_contextify_an_object"><em>contextifying</em></a> an
object. The invoked code treats any property in the context like a
global variable. Any changes to global variables caused by the invoked
code are reflected in the context object.</p>
<pre><code class="language-js">const vm = require('vm');

const x = 1;

const context = { x: 2 };
vm.createContext(context); // Contextify the object.

const code = 'x += 40; var y = 17;';
// `x` and `y` are global variables in the context.
// Initially, x has the value 2 because that is the value of context.x.
vm.runInContext(code, context);

console.log(context.x); // 42
console.log(context.y); // 17

console.log(x); // 1; y is not defined.
</code></pre>
<h2>Class: <code>vm.Script</code><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 contexts.</p>
<h3>Constructor: <code>new vm.Script(code[, options])</code><span><a class="mark" href="#vm_constructor_new_vm_script_code_options" id="vm_constructor_new_vm_script_code_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.6.0</td>
<td><p>The <code>produceCachedData</code> is deprecated in favour of <code>script.createCachedData()</code></p></td></tr>
<tr><td>v5.7.0</td>
<td><p>The <code>cachedData</code> and <code>produceCachedData</code> options are supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The JavaScript code to compile.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the column number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>cachedData</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. When supplied, the <code>cachedDataRejected</code> value will be set to
either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li>
<li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code> and no <code>cachedData</code> is present, V8
will attempt to produce code cache data for <code>code</code>. Upon success, a
<code>Buffer</code> with V8's code cache data will be produced and stored in the
<code>cachedData</code> property of the returned <code>vm.Script</code> instance.
The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code>
depending on whether code cache data is produced successfully.
This option is <strong>deprecated</strong> in favor of <code>script.createCachedData()</code>.
<strong>Default:</strong> <code>false</code>.</li>
<li>
<p><code>importModuleDynamically</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called during evaluation of this module
when <code>import()</code> is called. If this option is not specified, calls to
<code>import()</code> will reject with <a href="#ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.
This option is part of the experimental modules API, and should not be
considered stable.</p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> specifier passed to <code>import()</code></li>
<li><code>module</code> <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a></li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects" class="type">&#x3C;Module Namespace Object></a> | <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a> Returning a <code>vm.Module</code> is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain <code>then</code> function exports.</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<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><code>script.createCachedData()</code><span><a class="mark" href="#vm_script_createcacheddata" id="vm_script_createcacheddata">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Creates a code cache that can be used with the Script constructor's
<code>cachedData</code> option. Returns a Buffer. This method may be called at any
time and any number of times.</p>
<pre><code class="language-js">const script = new vm.Script(`
function add(a, b) {
  return a + b;
}

const x = add(1, 2);
`);

const cacheWithoutX = script.createCachedData();

script.runInThisContext();

const cacheWithX = script.createCachedData();
</code></pre>
<h3><code>script.runInContext(contextifiedObject[, options])</code><span><a class="mark" href="#vm_script_runincontext_contextifiedobject_options" id="vm_script_runincontext_contextifiedobject_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextifiedObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> A <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object as returned by the
<code>vm.createContext()</code> method.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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 terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>Runs the compiled code contained by the <code>vm.Script</code> object within the given
<code>contextifiedObject</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>context</code> object.</p>
<pre><code class="language-js">const vm = require('vm');

const context = {
  animal: 'cat',
  count: 2
};

const script = new vm.Script('count += 1; name = "kitty";');

vm.createContext(context);
for (let i = 0; i &#x3C; 10; ++i) {
  script.runInContext(context);
}

console.log(context);
// Prints: { 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><code>script.runInNewContext([contextObject[, options]])</code><span><a class="mark" href="#vm_script_runinnewcontext_contextobject_options" id="vm_script_runinnewcontext_contextobject_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object that will be <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a>. If
<code>undefined</code>, a new object will be created.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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 terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. <strong>Default:</strong> <code>false</code>.</li>
<li><code>contextName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">Origin</a> corresponding to the newly
created context for display purposes. The origin should be formatted like a
URL, but with only the scheme, host, and port (if necessary), like the
value of the <a href="#url_url_origin"><code>url.origin</code></a> property of a <a href="#url_class_url"><code>URL</code></a> object. Most notably,
this string should omit the trailing slash, as that denotes a path.
<strong>Default:</strong> <code>''</code>.</li>
<li>
<p><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any calls to <code>eval</code> or function
constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
<li><code>wasm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any attempt to compile a WebAssembly
module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>First contextifies the given <code>contextObject</code>, runs the compiled code contained
by the <code>vm.Script</code> object within the created context, 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>context</code>.</p>
<pre><code class="language-js">const vm = require('vm');

const script = new vm.Script('globalVar = "set"');

const contexts = [{}, {}, {}];
contexts.forEach((context) => {
  script.runInNewContext(context);
});

console.log(contexts);
// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
</code></pre>
<h3><code>script.runInThisContext([options])</code><span><a class="mark" href="#vm_script_runinthiscontext_options" id="vm_script_runinthiscontext_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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 terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>Runs the compiled code contained by the <code>vm.Script</code> within the context of the
current <code>global</code> object. Running code does not have access to local scope, but
<em>does</em> have access to the current <code>global</code> object.</p>
<p>The following example compiles code that increments a <code>global</code> variable then
executes that code multiple times:</p>
<pre><code class="language-js">const vm = require('vm');

global.globalVar = 0;

const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });

for (let i = 0; i &#x3C; 1000; ++i) {
  script.runInThisContext();
}

console.log(globalVar);

// 1000
</code></pre>
<h2>Class: <code>vm.Module</code><span><a class="mark" href="#vm_class_vm_module" id="vm_class_vm_module">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p><em>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</em></p>
<p>The <code>vm.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://www.ecma-international.org/ecma-262/#sec-abstract-module-records">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. The use of
'async' functions can help with manipulating <code>vm.Module</code> objects.</p>
<p>Using a <code>vm.Module</code> object requires three distinct steps: creation/parsing,
linking, and evaluation. These three steps are illustrated in the following
example.</p>
<p>This implementation lies at a lower level than the <a href="#esm_ecmascript_modules">ECMAScript Module
loader</a>. There is also no way to interact with the Loader yet, though
support is planned.</p>
<pre><code class="language-js">const vm = require('vm');

const contextifiedObject = vm.createContext({ secret: 42 });

(async () => {
  // Step 1
  //
  // Create a Module by constructing a new `vm.SourceTextModule` object. This
  // parses the provided source text, throwing a `SyntaxError` if anything goes
  // wrong. By default, a Module is created in the top context. But here, we
  // specify `contextifiedObject` as the context this Module belongs to.
  //
  // Here, we attempt to obtain the default export from the module "foo", and
  // put it into local binding "secret".

  const bar = new vm.SourceTextModule(`
    import s from 'foo';
    s;
  `, { context: contextifiedObject });

  // Step 2
  //
  // "Link" the imported dependencies of this Module to it.
  //
  // The provided linking callback (the "linker") accepts two arguments: the
  // parent module (`bar` in this case) and the string that is the specifier of
  // the imported module. The callback is expected to return a Module that
  // corresponds to the provided specifier, with certain requirements documented
  // in `module.link()`.
  //
  // If linking has not started for the returned Module, the same linker
  // callback will be called on the returned Module.
  //
  // Even top-level Modules without dependencies must be explicitly linked. The
  // callback provided would never be called, however.
  //
  // The link() method returns a Promise that will be resolved when all the
  // Promises returned by the linker resolve.
  //
  // Note: This is a contrived example in that the linker function creates a new
  // "foo" module every time it is called. In a full-fledged module system, a
  // cache would probably be used to avoid duplicated modules.

  async function linker(specifier, referencingModule) {
    if (specifier === 'foo') {
      return new vm.SourceTextModule(`
        // The "secret" variable refers to the global variable we added to
        // "contextifiedObject" when creating the context.
        export default secret;
      `, { context: referencingModule.context });

      // Using `contextifiedObject` instead of `referencingModule.context`
      // here would work as well.
    }
    throw new Error(`Unable to resolve dependency: ${specifier}`);
  }
  await bar.link(linker);

  // Step 3
  //
  // 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><code>module.dependencySpecifiers</code><span><a class="mark" href="#vm_module_dependencyspecifiers" id="vm_module_dependencyspecifiers">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>The specifiers of all dependencies of this module. The returned array is frozen
to disallow any changes to it.</p>
<p>Corresponds to the <code>[[RequestedModules]]</code> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>s in
the ECMAScript specification.</p>
<h3><code>module.error</code><span><a class="mark" href="#vm_module_error" id="vm_module_error">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>If the <code>module.status</code> is <code>'errored'</code>, this property contains the exception
thrown by the module during evaluation. If the status is anything else,
accessing this property will result in a thrown exception.</p>
<p>The value <code>undefined</code> cannot be used for cases where there is not a thrown
exception due to possible ambiguity with <code>throw undefined;</code>.</p>
<p>Corresponds to the <code>[[EvaluationError]]</code> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>s
in the ECMAScript specification.</p>
<h3><code>module.evaluate([options])</code><span><a class="mark" href="#vm_module_evaluate_options" id="vm_module_evaluate_options">#</a></span></h3>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to evaluate
before terminating execution. If execution is interrupted, an <a href="#errors_class_error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code>, the execution will be terminated when
<code>SIGINT</code> (Ctrl+C) is received. Existing handlers for the event that have
been attached via <code>process.on('SIGINT')</code> will be disabled during script
execution, but will continue to work after that. If execution is
interrupted, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Evaluate the module.</p>
<p>This must be called after the module has been linked; 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.es/ecma262/#sec-moduleevaluation">Evaluate() concrete method</a> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module
Record</a>s in the ECMAScript specification.</p>
<h3><code>module.link(linker)</code><span><a class="mark" href="#vm_module_link_linker" id="vm_module_link_linker">#</a></span></h3>
<ul>
<li>
<p><code>linker</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></p>
<ul>
<li>
<p><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The specifier of the requested module:</p>
<!-- eslint-skip -->
<pre><code class="language-js">import foo from 'foo';
//              ^^^^^ the module specifier
</code></pre>
</li>
<li>
<p><code>referencingModule</code> <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a> The <code>Module</code> object <code>link()</code> is called on.</p>
</li>
<li>
<p>Returns: <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></p>
</li>
</ul>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></p>
</li>
</ul>
<p>Link module dependencies. This method must be called before evaluation, and
can only be called once per module.</p>
<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>status</code> must not be <code>'errored'</code>.</li>
</ul>
<p>If the returned <code>Module</code>'s <code>status</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.es/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.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> is synchronous.</li>
</ul>
<p>The actual <a href="https://tc39.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation used during module
linking 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.es/ecma262/#sec-hostresolveimportedmodule">HostResolveImportedModule</a> implementation is fully synchronous per
specification.</p>
<p>Corresponds to the <a href="https://tc39.es/ecma262/#sec-moduledeclarationlinking">Link() concrete method</a> field of <a href="https://tc39.es/ecma262/#sec-cyclic-module-records">Cyclic Module
Record</a>s in the ECMAScript specification.</p>
<h3><code>module.namespace</code><span><a class="mark" href="#vm_module_namespace" id="vm_module_namespace">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>The namespace object of the module. This is only available after linking
(<code>module.link()</code>) has completed.</p>
<p>Corresponds to the <a href="https://tc39.es/ecma262/#sec-getmodulenamespace">GetModuleNamespace</a> abstract operation in the ECMAScript
specification.</p>
<h3><code>module.status</code><span><a class="mark" href="#vm_module_status" id="vm_module_status">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The current status of the module. Will be one of:</p>
<ul>
<li>
<p><code>'unlinked'</code>: <code>module.link()</code> has not yet been called.</p>
</li>
<li>
<p><code>'linking'</code>: <code>module.link()</code> has been called, but not all Promises returned
by the linker function have been resolved yet.</p>
</li>
<li>
<p><code>'linked'</code>: The module has been linked successfully, and all of its
dependencies are linked, 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.es/ecma262/#sec-cyclic-module-records">Cyclic Module Record</a>'s <code>[[Status]]</code> field. <code>'errored'</code> corresponds to
<code>'evaluated'</code> in the specification, but with <code>[[EvaluationError]]</code> set to a
value that is not <code>undefined</code>.</p>
<h3><code>module.identifier</code><span><a class="mark" href="#vm_module_identifier" id="vm_module_identifier">#</a></span></h3>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The identifier of the current module, as set in the constructor.</p>
<h2>Class: <code>vm.SourceTextModule</code><span><a class="mark" href="#vm_class_vm_sourcetextmodule" id="vm_class_vm_sourcetextmodule">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p><em>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</em></p>
<ul>
<li>Extends: <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a></li>
</ul>
<p>The <code>vm.SourceTextModule</code> class provides the <a href="https://tc39.es/ecma262/#sec-source-text-module-records">Source Text Module Record</a> as
defined in the ECMAScript specification.</p>
<h3>Constructor: <code>new vm.SourceTextModule(code[, options])</code><span><a class="mark" href="#vm_constructor_new_vm_sourcetextmodule_code_options" id="vm_constructor_new_vm_sourcetextmodule_code_options">#</a></span></h3>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> JavaScript Module code to parse</li>
<li>
<p><code>options</code></p>
<ul>
<li><code>identifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> String used in stack traces.
<strong>Default:</strong> <code>'vm:module(i)'</code> where <code>i</code> is a context-specific ascending
index.</li>
<li><code>cachedData</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. The <code>code</code> must be the same as the module from which this
<code>cachedData</code> was created.</li>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object as returned by the
<code>vm.createContext()</code> method, to compile and evaluate this <code>Module</code> in.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the line number offset that is displayed
in stack traces produced by this <code>Module</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the column number offset that is
displayed in stack traces produced by this <code>Module</code>. <strong>Default:</strong> <code>0</code>.</li>
<li>
<p><code>initializeImportMeta</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called during evaluation of this <code>Module</code>
to initialize the <code>import.meta</code>.</p>
<ul>
<li><code>meta</code> <a href="#esm_import_meta" class="type">&#x3C;import.meta></a></li>
<li><code>module</code> <a href="#vm_class_vm_sourcetextmodule" class="type">&#x3C;vm.SourceTextModule></a></li>
</ul>
</li>
<li>
<p><code>importModuleDynamically</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called during evaluation of this module
when <code>import()</code> is called. If this option is not specified, calls to
<code>import()</code> will reject with <a href="#ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.</p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> specifier passed to <code>import()</code></li>
<li><code>module</code> <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a></li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects" class="type">&#x3C;Module Namespace Object></a> | <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a> Returning a <code>vm.Module</code> is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain <code>then</code> function exports.</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>Creates a new <code>SourceTextModule</code> instance.</p>
<p>Properties assigned to the <code>import.meta</code> object that are objects may
allow the module to access information outside the specified <code>context</code>. Use
<code>vm.runInContext()</code> to create objects in a specific context.</p>
<pre><code class="language-js">const vm = require('vm');

const contextifiedObject = vm.createContext({ secret: 42 });

(async () => {
  const module = new vm.SourceTextModule(
    'Object.getPrototypeOf(import.meta.prop).secret = secret;',
    {
      initializeImportMeta(meta) {
        // Note: this object is created in the top context. As such,
        // Object.getPrototypeOf(import.meta.prop) points to the
        // Object.prototype in the top context rather than that in
        // the contextified object.
        meta.prop = {};
      }
    });
  // Since module has no dependencies, the linker function will never be called.
  await module.link(() => {});
  await module.evaluate();

  // Now, Object.prototype.secret will be equal to 42.
  //
  // To fix this problem, replace
  //     meta.prop = {};
  // above with
  //     meta.prop = vm.runInContext('{}', contextifiedObject);
})();
</code></pre>
<h3><code>sourceTextModule.createCachedData()</code><span><a class="mark" href="#vm_sourcetextmodule_createcacheddata" id="vm_sourcetextmodule_createcacheddata">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li>Returns: <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Creates a code cache that can be used with the SourceTextModule constructor's
<code>cachedData</code> option. Returns a Buffer. This method may be called any number
of times before the module has been evaluated.</p>
<pre><code class="language-js">// Create an initial module
const module = new vm.SourceTextModule('const a = 1;');

// Create cached data from this module
const cachedData = module.createCachedData();

// Create a new module using the cached data. The code must be the same.
const module2 = new vm.SourceTextModule('const a = 1;', { cachedData });
</code></pre>
<h2>Class: <code>vm.SyntheticModule</code><span><a class="mark" href="#vm_class_vm_syntheticmodule" id="vm_class_vm_syntheticmodule">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p><em>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</em></p>
<ul>
<li>Extends: <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a></li>
</ul>
<p>The <code>vm.SyntheticModule</code> class provides the <a href="https://heycam.github.io/webidl/#synthetic-module-records">Synthetic Module Record</a> as
defined in the WebIDL specification. The purpose of synthetic modules is to
provide a generic interface for exposing non-JavaScript sources to ECMAScript
module graphs.</p>
<pre><code class="language-js">const vm = require('vm');

const source = '{ "a": 1 }';
const module = new vm.SyntheticModule(['default'], function() {
  const obj = JSON.parse(source);
  this.setExport('default', obj);
});

// Use `module` in linking...
</code></pre>
<h3>Constructor: <code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code><span><a class="mark" href="#vm_constructor_new_vm_syntheticmodule_exportnames_evaluatecallback_options" id="vm_constructor_new_vm_syntheticmodule_exportnames_evaluatecallback_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li><code>exportNames</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Array of names that will be exported from the module.</li>
<li><code>evaluateCallback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called when the module is evaluated.</li>
<li>
<p><code>options</code></p>
<ul>
<li><code>identifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> String used in 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">&#x3C;Object></a> The <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object as returned by the
<code>vm.createContext()</code> method, to compile and evaluate this <code>Module</code> in.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>SyntheticModule</code> instance.</p>
<p>Objects assigned to the exports of this instance may allow importers of
the module to access information outside the specified <code>context</code>. Use
<code>vm.runInContext()</code> to create objects in a specific context.</p>
<h3><code>syntheticModule.setExport(name, value)</code><span><a class="mark" href="#vm_syntheticmodule_setexport_name_value" id="vm_syntheticmodule_setexport_name_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.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">&#x3C;string></a> Name of the export to set.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The value to set the export to.</li>
</ul>
<p>This method is used after the module is linked to set the values of exports. If
it is called before the module is linked, an <a href="#ERR_VM_MODULE_STATUS"><code>ERR_VM_MODULE_STATUS</code></a> error
will be thrown.</p>
<pre><code class="language-js">const vm = require('vm');

(async () => {
  const m = new vm.SyntheticModule(['x'], () => {
    m.setExport('x', 1);
  });

  await m.link(() => {});
  await m.evaluate();

  assert.strictEqual(m.namespace.x, 1);
})();
</code></pre>
<h2><code>vm.compileFunction(code[, params[, options]])</code><span><a class="mark" href="#vm_vm_compilefunction_code_params_options" id="vm_vm_compilefunction_code_params_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.10.0</span>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The body of the function to compile.</li>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> An array of strings containing all parameters for the
function.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>''</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the column number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>cachedData</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source.</li>
<li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Specifies whether to produce new cache data.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>parsingContext</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object in which the said
function should be compiled in.</li>
<li><code>contextExtensions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> An array containing a collection of context
extensions (objects wrapping the current scope) to be applied while
compiling. <strong>Default:</strong> <code>[]</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Compiles the given code into the provided context (if no context is
supplied, the current context is used), and returns it wrapped inside a
function with the given <code>params</code>.</p>
<h2><code>vm.createContext([contextObject[, options]])</code><span><a class="mark" href="#vm_vm_createcontext_contextobject_options" id="vm_vm_createcontext_contextobject_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The first argument can no longer be a function.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>codeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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">&#x3C;Object></a></p>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">Origin</a> corresponding to the newly created
context for display purposes. The origin should be formatted like a URL,
but with only the scheme, host, and port (if necessary), like the value of
the <a href="#url_url_origin"><code>url.origin</code></a> property of a <a href="#url_class_url"><code>URL</code></a> object. Most notably, this
string should omit the trailing slash, as that denotes a path.
<strong>Default:</strong> <code>''</code>.</li>
<li>
<p><code>codeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any calls to <code>eval</code> or function
constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
<li><code>wasm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any attempt to compile a WebAssembly
module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> contextified object.</li>
</ul>
<p>If given a <code>contextObject</code>, the <code>vm.createContext()</code> method will <a href="#vm_what_does_it_mean_to_contextify_an_object">prepare
that object</a> so that it can be used in calls to
<a href="#vm_vm_runincontext_code_contextifiedobject_options"><code>vm.runInContext()</code></a> or <a href="#vm_script_runincontext_contextifiedobject_options"><code>script.runInContext()</code></a>. Inside such scripts,
the <code>contextObject</code> will be the global object, retaining all of its existing
properties but also having the built-in objects and functions any standard
<a href="https://es5.github.io/#x15.1">global object</a> has. Outside of scripts run by the vm module, global variables
will remain unchanged.</p>
<pre><code class="language-js">const vm = require('vm');

global.globalVar = 3;

const context = { globalVar: 1 };
vm.createContext(context);

vm.runInContext('globalVar *= 2;', context);

console.log(context);
// Prints: { globalVar: 2 }

console.log(global.globalVar);
// Prints: 3
</code></pre>
<p>If <code>contextObject</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> object will be returned.</p>
<p>The <code>vm.createContext()</code> method is primarily useful for creating a single
context that can be used to run multiple scripts. For instance, if emulating a
web browser, the method can be used to create a single context representing a
window's global object, then run all <code>&#x3C;script></code> tags together within that
context.</p>
<p>The provided <code>name</code> and <code>origin</code> of the context are made visible through the
Inspector API.</p>
<h2><code>vm.isContext(object)</code><span><a class="mark" href="#vm_vm_iscontext_object" id="vm_vm_iscontext_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.7</span>
</div>
<ul>
<li><code>object</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Returns <code>true</code> if the given <code>oject</code> object has been <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> using
<a href="#vm_vm_createcontext_contextobject_options"><code>vm.createContext()</code></a>.</p>
<h2><code>vm.runInContext(code, contextifiedObject[, options])</code><span><a class="mark" href="#vm_vm_runincontext_code_contextifiedobject_options" id="vm_vm_runincontext_code_contextifiedobject_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The JavaScript code to compile and run.</li>
<li><code>contextifiedObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object that will be used
as the <code>global</code> when the <code>code</code> is compiled and run.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the column number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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 terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. <strong>Default:</strong> <code>false</code>.</li>
<li><code>cachedData</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. When supplied, the <code>cachedDataRejected</code> value will be set to
either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li>
<li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code> and no <code>cachedData</code> is present, V8
will attempt to produce code cache data for <code>code</code>. Upon success, a
<code>Buffer</code> with V8's code cache data will be produced and stored in the
<code>cachedData</code> property of the returned <code>vm.Script</code> instance.
The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code>
depending on whether code cache data is produced successfully.
This option is <strong>deprecated</strong> in favor of <code>script.createCachedData()</code>.
<strong>Default:</strong> <code>false</code>.</li>
<li>
<p><code>importModuleDynamically</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called during evaluation of this module
when <code>import()</code> is called. If this option is not specified, calls to
<code>import()</code> will reject with <a href="#ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.
This option is part of the experimental modules API, and should not be
considered stable.</p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> specifier passed to <code>import()</code></li>
<li><code>module</code> <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a></li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects" class="type">&#x3C;Module Namespace Object></a> | <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a> Returning a <code>vm.Module</code> is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain <code>then</code> function exports.</li>
</ul>
</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>The <code>vm.runInContext()</code> method compiles <code>code</code>, runs it within the context of
the <code>contextifiedObject</code>, then returns the result. Running code does not have
access to the local scope. The <code>contextifiedObject</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_contextobject_options"><code>vm.createContext()</code></a> method.</p>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<p>The following example compiles and executes different scripts using a single
<a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a> object:</p>
<pre><code class="language-js">const vm = require('vm');

const contextObject = { globalVar: 1 };
vm.createContext(contextObject);

for (let i = 0; i &#x3C; 10; ++i) {
  vm.runInContext('globalVar *= 2;', contextObject);
}
console.log(contextObject);
// Prints: { globalVar: 1024 }
</code></pre>
<h2><code>vm.runInNewContext(code[, contextObject[, options]])</code><span><a class="mark" href="#vm_vm_runinnewcontext_code_contextobject_options" id="vm_vm_runinnewcontext_code_contextobject_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>contextCodeGeneration</code> option is supported now.</p></td></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The JavaScript code to compile and run.</li>
<li><code>contextObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object that will be <a href="#vm_what_does_it_mean_to_contextify_an_object">contextified</a>. If
<code>undefined</code>, a new object will be created.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the column number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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 terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. <strong>Default:</strong> <code>false</code>.</li>
<li><code>contextName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;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">&#x3C;string></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">Origin</a> corresponding to the newly
created context for display purposes. The origin should be formatted like a
URL, but with only the scheme, host, and port (if necessary), like the
value of the <a href="#url_url_origin"><code>url.origin</code></a> property of a <a href="#url_class_url"><code>URL</code></a> object. Most notably,
this string should omit the trailing slash, as that denotes a path.
<strong>Default:</strong> <code>''</code>.</li>
<li>
<p><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>strings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any calls to <code>eval</code> or function
constructors (<code>Function</code>, <code>GeneratorFunction</code>, etc) will throw an
<code>EvalError</code>. <strong>Default:</strong> <code>true</code>.</li>
<li><code>wasm</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If set to false any attempt to compile a WebAssembly
module will throw a <code>WebAssembly.CompileError</code>. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li><code>cachedData</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. When supplied, the <code>cachedDataRejected</code> value will be set to
either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li>
<li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code> and no <code>cachedData</code> is present, V8
will attempt to produce code cache data for <code>code</code>. Upon success, a
<code>Buffer</code> with V8's code cache data will be produced and stored in the
<code>cachedData</code> property of the returned <code>vm.Script</code> instance.
The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code>
depending on whether code cache data is produced successfully.
This option is <strong>deprecated</strong> in favor of <code>script.createCachedData()</code>.
<strong>Default:</strong> <code>false</code>.</li>
<li>
<p><code>importModuleDynamically</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called during evaluation of this module
when <code>import()</code> is called. If this option is not specified, calls to
<code>import()</code> will reject with <a href="#ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.
This option is part of the experimental modules API, and should not be
considered stable.</p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> specifier passed to <code>import()</code></li>
<li><code>module</code> <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a></li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects" class="type">&#x3C;Module Namespace Object></a> | <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a> Returning a <code>vm.Module</code> is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain <code>then</code> function exports.</li>
</ul>
</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p>The <code>vm.runInNewContext()</code> first contextifies the given <code>contextObject</code> (or
creates a new <code>contextObject</code> if passed as <code>undefined</code>), compiles the <code>code</code>,
runs it within the created context, then returns the result. Running code
does not have access to the local scope.</p>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<p>The following example compiles and executes code that increments a global
variable and sets a new one. These globals are contained in the <code>contextObject</code>.</p>
<pre><code class="language-js">const vm = require('vm');

const contextObject = {
  animal: 'cat',
  count: 2
};

vm.runInNewContext('count += 1; name = "kitty"', contextObject);
console.log(contextObject);
// Prints: { animal: 'cat', count: 3, name: 'kitty' }
</code></pre>
<h2><code>vm.runInThisContext(code[, options])</code><span><a class="mark" href="#vm_vm_runinthiscontext_code_options" id="vm_vm_runinthiscontext_code_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.3.0</td>
<td><p>The <code>breakOnSigint</code> option is supported now.</p></td></tr>
<tr><td>v0.3.1</td>
<td><p><span>Added in: v0.3.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>code</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The JavaScript code to compile and run.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Specifies the filename used in stack traces produced
by this script. <strong>Default:</strong> <code>'evalmachine.&#x3C;anonymous>'</code>.</li>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the line number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>columnOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies the column number offset that is displayed
in stack traces produced by this script. <strong>Default:</strong> <code>0</code>.</li>
<li><code>displayErrors</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code>, if an <a href="#errors_class_error"><code>Error</code></a> occurs
while compiling the <code>code</code>, the line of code causing the error is attached
to the stack trace. <strong>Default:</strong> <code>true</code>.</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Specifies the number of milliseconds to execute <code>code</code>
before terminating execution. If execution is terminated, an <a href="#errors_class_error"><code>Error</code></a>
will be thrown. This value must be a strictly positive integer.</li>
<li><code>breakOnSigint</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;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 terminated, an <a href="#errors_class_error"><code>Error</code></a> will be thrown. <strong>Default:</strong> <code>false</code>.</li>
<li><code>cachedData</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> Provides an optional <code>Buffer</code> or
<code>TypedArray</code>, or <code>DataView</code> with V8's code cache data for the supplied
source. When supplied, the <code>cachedDataRejected</code> value will be set to
either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.</li>
<li><code>produceCachedData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When <code>true</code> and no <code>cachedData</code> is present, V8
will attempt to produce code cache data for <code>code</code>. Upon success, a
<code>Buffer</code> with V8's code cache data will be produced and stored in the
<code>cachedData</code> property of the returned <code>vm.Script</code> instance.
The <code>cachedDataProduced</code> value will be set to either <code>true</code> or <code>false</code>
depending on whether code cache data is produced successfully.
This option is <strong>deprecated</strong> in favor of <code>script.createCachedData()</code>.
<strong>Default:</strong> <code>false</code>.</li>
<li>
<p><code>importModuleDynamically</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Called during evaluation of this module
when <code>import()</code> is called. If this option is not specified, calls to
<code>import()</code> will reject with <a href="#ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.
This option is part of the experimental modules API, and should not be
considered stable.</p>
<ul>
<li><code>specifier</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> specifier passed to <code>import()</code></li>
<li><code>module</code> <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a></li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects" class="type">&#x3C;Module Namespace Object></a> | <a href="#vm_class_vm_module" class="type">&#x3C;vm.Module></a> Returning a <code>vm.Module</code> is
recommended in order to take advantage of error tracking, and to avoid
issues with namespaces that contain <code>then</code> function exports.</li>
</ul>
</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the result of the very last statement executed in the script.</li>
</ul>
<p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it within the context of the
current <code>global</code> and returns the result. Running code does not have access to
local scope, but does have access to the current <code>global</code> object.</p>
<p>If <code>options</code> is a string, then it specifies the filename.</p>
<p>The following example illustrates using both <code>vm.runInThisContext()</code> and
the JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> function to run the same code:</p>
<!-- eslint-disable prefer-const -->
<pre><code class="language-js">const vm = require('vm');
let localVar = 'initial value';

const vmResult = vm.runInThisContext('localVar = "vm";');
console.log(`vmResult: '${vmResult}', localVar: '${localVar}'`);
// Prints: vmResult: 'vm', localVar: 'initial value'

const evalResult = eval('localVar = "eval";');
console.log(`evalResult: '${evalResult}', localVar: '${localVar}'`);
// Prints: evalResult: 'eval', localVar: 'eval'
</code></pre>
<p>Because <code>vm.runInThisContext()</code> does not have access to the local scope,
<code>localVar</code> is unchanged. In contrast, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> <em>does</em> have access to the
local scope, so the value <code>localVar</code> is changed. In this way
<code>vm.runInThisContext()</code> is much like an <a href="https://es5.github.io/#x10.4.2">indirect <code>eval()</code> call</a>, e.g.
<code>(0,eval)('code')</code>.</p>
<h2>Example: Running an HTTP server within a VM<span><a class="mark" href="#vm_example_running_an_http_server_within_a_vm" id="vm_example_running_an_http_server_within_a_vm">#</a></span></h2>
<p>When using either <a href="#vm_script_runinthiscontext_options"><code>script.runInThisContext()</code></a> or
<a href="#vm_vm_runinthiscontext_code_options"><code>vm.runInThisContext()</code></a>, the code is executed within the current V8 global
context. The code passed to this VM context will have its own isolated scope.</p>
<p>In order to run a simple web server using the <code>http</code> module the code passed to
the context must either call <code>require('http')</code> on its own, or have a reference
to the <code>http</code> module passed to it. For instance:</p>
<pre><code class="language-js">'use strict';
const vm = require('vm');

const code = `
((require) => {
  const http = require('http');

  http.createServer((request, response) => {
    response.writeHead(200, { 'Content-Type': 'text/plain' });
    response.end('Hello World\\n');
  }).listen(8124);

  console.log('Server running at http://127.0.0.1:8124/');
})`;

vm.runInThisContext(code)(require);
</code></pre>
<p>The <code>require()</code> in the above case shares the state with the context it is
passed from. This may introduce risks when untrusted code is executed, e.g.
altering objects in the context in unwanted ways.</p>
<h2>What does it mean to "contextify" an object?<span><a class="mark" href="#vm_what_does_it_mean_to_contextify_an_object" id="vm_what_does_it_mean_to_contextify_an_object">#</a></span></h2>
<p>All JavaScript executed within Node.js runs within the scope of a "context".
According to the <a href="https://v8.dev/docs/embed#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>contextObject</code> argument
(or a newly-created object if <code>contextObject</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>contextObject</code> is what this document refers to as
"contextifying" the object.</p>
<h2>Timeout limitations when using <code>process.nextTick()</code>, promises, and <code>queueMicrotask()</code><span><a class="mark" href="#vm_timeout_limitations_when_using_process_nexttick_promises_and_queuemicrotask" id="vm_timeout_limitations_when_using_process_nexttick_promises_and_queuemicrotask">#</a></span></h2>
<p>Because of the internal mechanics of how the <code>process.nextTick()</code> queue and
the microtask queue that underlies Promises are implemented within V8 and
Node.js, it is possible for code running within a context to "escape" the
<code>timeout</code> set using <code>vm.runInContext()</code>, <code>vm.runInNewContext()</code>, and
<code>vm.runInThisContext()</code>.</p>
<p>For example, the following code executed by <code>vm.runInNewContext()</code> with a
timeout of 5 milliseconds schedules an infinite loop to run after a promise
resolves. The scheduled loop is never interrupted by the timeout:</p>
<pre><code class="language-js">const vm = require('vm');

function loop() {
  while (1) console.log(Date.now());
}

vm.runInNewContext(
  'Promise.resolve().then(loop);',
  { loop, console },
  { timeout: 5 }
);
</code></pre>
<p>This issue also occurs when the <code>loop()</code> call is scheduled using
the <code>process.nextTick()</code> and <code>queueMicrotask()</code> functions.</p>
<p>This issue occurs because all contexts share the same microtask and nextTick
queues.</p>
<h1>WebAssembly System Interface (WASI)<span><a class="mark" href="#wasi_webassembly_system_interface_wasi" id="wasi_webassembly_system_interface_wasi">#</a></span></h1>

<p></p><div class="api_stability api_stability_1"><a href="#documentation_stability_index">Stability: 1</a> - Experimental</div><p></p>
<p>The WASI API provides an implementation of the <a href="https://wasi.dev/">WebAssembly System Interface</a>
specification. WASI gives sandboxed WebAssembly applications access to the
underlying operating system via a collection of POSIX-like functions.</p>
<pre><code class="language-js">'use strict';
const fs = require('fs');
const { WASI } = require('wasi');
const wasi = new WASI({
  args: process.argv,
  env: process.env,
  preopens: {
    '/sandbox': '/some/real/path/that/wasm/can/access'
  }
});
const importObject = { wasi_snapshot_preview1: wasi.wasiImport };

(async () => {
  const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm'));
  const instance = await WebAssembly.instantiate(wasm, importObject);

  wasi.start(instance);
})();
</code></pre>
<p>To run the above example, create a new WebAssembly text format file named
<code>demo.wat</code>:</p>
<pre><code class="language-text">(module
    ;; Import the required fd_write WASI function which will write the given io vectors to stdout
    ;; The function signature for fd_write is:
    ;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written
    (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))

    (memory 1)
    (export "memory" (memory 0))

    ;; Write 'hello world\n' to memory at an offset of 8 bytes
    ;; Note the trailing newline which is required for the text to appear
    (data (i32.const 8) "hello world\n")

    (func $main (export "_start")
        ;; Creating a new io vector within linear memory
        (i32.store (i32.const 0) (i32.const 8))  ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string
        (i32.store (i32.const 4) (i32.const 12))  ;; iov.iov_len - The length of the 'hello world\n' string

        (call $fd_write
            (i32.const 1) ;; file_descriptor - 1 for stdout
            (i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0
            (i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.
            (i32.const 20) ;; nwritten - A place in memory to store the number of bytes written
        )
        drop ;; Discard the number of bytes written from the top of the stack
    )
)
</code></pre>
<p>Use <a href="https://github.com/WebAssembly/wabt">wabt</a> to compile <code>.wat</code> to <code>.wasm</code></p>
<pre><code class="language-console">$ wat2wasm demo.wat
</code></pre>
<p>The <code>--experimental-wasi-unstable-preview1</code> and <code>--experimental-wasm-bigint</code>
CLI arguments are needed for this example to run.</p>
<h2>Class: <code>WASI</code><span><a class="mark" href="#wasi_class_wasi" id="wasi_class_wasi">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<p>The <code>WASI</code> class provides the WASI system call API and additional convenience
methods for working with WASI-based applications. Each <code>WASI</code> instance
represents a distinct sandbox environment. For security purposes, each <code>WASI</code>
instance must have its command line arguments, environment variables, and
sandbox directory structure configured explicitly.</p>
<h3><code>new WASI([options])</code><span><a class="mark" href="#wasi_new_wasi_options" id="wasi_new_wasi_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> An array of strings that the WebAssembly application will
see as command line arguments. The first argument is the virtual path to the
WASI command itself. <strong>Default:</strong> <code>[]</code>.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object similar to <code>process.env</code> that the WebAssembly
application will see as its environment. <strong>Default:</strong> <code>{}</code>.</li>
<li><code>preopens</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> This object represents the WebAssembly application's
sandbox directory structure. The string keys of <code>preopens</code> are treated as
directories within the sandbox. The corresponding values in <code>preopens</code> are
the real paths to those directories on the host machine.</li>
<li><code>returnOnExit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> By default, WASI applications terminate the Node.js
process via the <code>__wasi_proc_exit()</code> function. Setting this option to <code>true</code>
causes <code>wasi.start()</code> to return the exit code rather than terminate the
process. <strong>Default:</strong> <code>false</code>.</li>
<li><code>stdin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The file descriptor used as standard input in the
WebAssembly application. <strong>Default:</strong> <code>0</code>.</li>
<li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The file descriptor used as standard output in the
WebAssembly application. <strong>Default:</strong> <code>1</code>.</li>
<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The file descriptor used as standard error in the
WebAssembly application. <strong>Default:</strong> <code>2</code>.</li>
</ul>
</li>
</ul>
<h3><code>wasi.start(instance)</code><span><a class="mark" href="#wasi_wasi_start_instance" id="wasi_wasi_start_instance">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li><code>instance</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance" class="type">&#x3C;WebAssembly.Instance></a></li>
</ul>
<p>Attempt to begin execution of <code>instance</code> as a WASI command by invoking its
<code>_start()</code> export. If <code>instance</code> does not contain a <code>_start()</code> export, or if
<code>instance</code> contains an <code>_initialize()</code> export, then an exception is thrown.</p>
<p><code>start()</code> requires that <code>instance</code> exports a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory"><code>WebAssembly.Memory</code></a> named
<code>memory</code>. If <code>instance</code> does not have a <code>memory</code> export an exception is thrown.</p>
<p>If <code>start()</code> is called more than once, an exception is thrown.</p>
<h3><code>wasi.wasiImport</code><span><a class="mark" href="#wasi_wasi_wasiimport" id="wasi_wasi_wasiimport">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p><code>wasiImport</code> is an object that implements the WASI system call API. This object
should be passed as the <code>wasi_snapshot_preview1</code> import during the instantiation
of a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance"><code>WebAssembly.Instance</code></a>.</p>
<h1>Worker threads<span><a class="mark" href="#worker_threads_worker_threads" id="worker_threads_worker_threads">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>worker_threads</code> module enables the use of threads that execute JavaScript
in parallel. To access it:</p>
<pre><code class="language-js">const worker = require('worker_threads');
</code></pre>
<p>Workers (threads) are useful for performing CPU-intensive JavaScript operations.
They will not help much with I/O-intensive work. Node.js’s built-in asynchronous
I/O operations are more efficient than Workers can be.</p>
<p>Unlike <code>child_process</code> or <code>cluster</code>, <code>worker_threads</code> can share memory. They do
so by transferring <code>ArrayBuffer</code> instances or sharing <code>SharedArrayBuffer</code>
instances.</p>
<pre><code class="language-js">const {
  Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

if (isMainThread) {
  module.exports = function parseJSAsync(script) {
    return new Promise((resolve, reject) => {
      const worker = new Worker(__filename, {
        workerData: script
      });
      worker.on('message', resolve);
      worker.on('error', reject);
      worker.on('exit', (code) => {
        if (code !== 0)
          reject(new Error(`Worker stopped with exit code ${code}`));
      });
    });
  };
} else {
  const { parse } = require('some-js-parsing-library');
  const script = workerData;
  parentPort.postMessage(parse(script));
}
</code></pre>
<p>The above example spawns a Worker thread for each <code>parse()</code> call. In actual
practice, use a pool of Workers instead for these kinds of tasks. Otherwise, the
overhead of creating Workers would likely exceed their benefit.</p>
<p>When implementing a worker pool, use the <a href="#async_hooks_class_asyncresource"><code>AsyncResource</code></a> API to inform
diagnostic tools (e.g. in order to provide asynchronous stack traces) about the
correlation between tasks and their outcomes. See
<a href="#async-resource-worker-pool">"Using <code>AsyncResource</code> for a <code>Worker</code> thread pool"</a>
in the <code>async_hooks</code> documentation for an example implementation.</p>
<p>Worker threads inherit non-process-specific options by default. Refer to
<a href="#worker_threads_new_worker_filename_options"><code>Worker constructor options</code></a> to know how to customize worker thread options,
specifically <code>argv</code> and <code>execArgv</code> options.</p>
<h2><code>worker.isMainThread</code><span><a class="mark" href="#worker_threads_worker_ismainthread" id="worker_threads_worker_ismainthread">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Is <code>true</code> if this code is not running inside of a <a href="#worker_threads_class_worker"><code>Worker</code></a> thread.</p>
<pre><code class="language-js">const { Worker, isMainThread } = require('worker_threads');

if (isMainThread) {
  // This re-loads the current file inside a Worker instance.
  new Worker(__filename);
} else {
  console.log('Inside Worker!');
  console.log(isMainThread);  // Prints 'false'.
}
</code></pre>
<h2><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code><span><a class="mark" href="#worker_threads_worker_movemessageporttocontext_port_contextifiedsandbox" id="worker_threads_worker_movemessageporttocontext_port_contextifiedsandbox">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.13.0</span>
</div>
<ul>
<li>
<p><code>port</code> <a href="#worker_threads_class_messageport" class="type">&#x3C;MessagePort></a> The message port which will be transferred.</p>
</li>
<li>
<p><code>contextifiedSandbox</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;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.</p>
</li>
<li>
<p>Returns: <a href="#worker_threads_class_messageport" class="type">&#x3C;MessagePort></a></p>
</li>
</ul>
<p>Transfer a <code>MessagePort</code> to a different <a href="vm.html"><code>vm</code></a> Context. The original <code>port</code>
object will be rendered unusable, and the returned <code>MessagePort</code> instance will
take its place.</p>
<p>The returned <code>MessagePort</code> will be an object in the target context, and will
inherit from its global <code>Object</code> class. Objects passed to the
<a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage"><code>port.onmessage()</code></a> listener will also be created in the target context
and inherit from its global <code>Object</code> class.</p>
<p>However, the created <code>MessagePort</code> will no longer inherit from
<a href="events.html"><code>EventEmitter</code></a>, and only <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/onmessage"><code>port.onmessage()</code></a> can be used to receive
events using it.</p>
<h2><code>worker.parentPort</code><span><a class="mark" href="#worker_threads_worker_parentport" id="worker_threads_worker_parentport">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="#worker_threads_class_messageport" class="type">&#x3C;MessagePort></a></li>
</ul>
<p>If this thread was spawned as a <a href="#worker_threads_class_worker"><code>Worker</code></a>, this will be a <a href="#worker_threads_class_messageport"><code>MessagePort</code></a>
allowing communication with the parent thread. Messages sent using
<code>parentPort.postMessage()</code> will be available in the parent thread
using <code>worker.on('message')</code>, and messages sent from the parent thread
using <code>worker.postMessage()</code> will be available in this thread using
<code>parentPort.on('message')</code>.</p>
<pre><code class="language-js">const { Worker, isMainThread, parentPort } = require('worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename);
  worker.once('message', (message) => {
    console.log(message);  // Prints 'Hello, world!'.
  });
  worker.postMessage('Hello, world!');
} else {
  // When a message from the parent thread is received, send it back:
  parentPort.once('message', (message) => {
    parentPort.postMessage(message);
  });
}
</code></pre>
<h2><code>worker.receiveMessageOnPort(port)</code><span><a class="mark" href="#worker_threads_worker_receivemessageonport_port" id="worker_threads_worker_receivemessageonport_port">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.3.0</span>
</div>
<ul>
<li>
<p><code>port</code> <a href="#worker_threads_class_messageport" class="type">&#x3C;MessagePort></a></p>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></p>
</li>
</ul>
<p>Receive a single message from a given <code>MessagePort</code>. If no message is available,
<code>undefined</code> is returned, otherwise an object with a single <code>message</code> property
that contains the message payload, corresponding to the oldest message in the
<code>MessagePort</code>’s queue.</p>
<pre><code class="language-js">const { MessageChannel, receiveMessageOnPort } = require('worker_threads');
const { port1, port2 } = new MessageChannel();
port1.postMessage({ hello: 'world' });

console.log(receiveMessageOnPort(port2));
// Prints: { message: { hello: 'world' } }
console.log(receiveMessageOnPort(port2));
// Prints: undefined
</code></pre>
<p>When this function is used, no <code>'message'</code> event will be emitted and the
<code>onmessage</code> listener will not be invoked.</p>
<h2><code>worker.resourceLimits</code><span><a class="mark" href="#worker_threads_worker_resourcelimits" id="worker_threads_worker_resourcelimits">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
<p>Provides the set of JS engine resource constraints inside this Worker thread.
If the <code>resourceLimits</code> option was passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor,
this matches its values.</p>
<p>If this is used in the main thread, its value is an empty object.</p>
<h2><code>worker.SHARE_ENV</code><span><a class="mark" href="#worker_threads_worker_share_env" id="worker_threads_worker_share_env">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.14.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a></li>
</ul>
<p>A special value that can be passed as the <code>env</code> option of the <a href="#worker_threads_class_worker"><code>Worker</code></a>
constructor, to indicate that the current thread and the Worker thread should
share read and write access to the same set of environment variables.</p>
<pre><code class="language-js">const { Worker, SHARE_ENV } = require('worker_threads');
new Worker('process.env.SET_IN_WORKER = "foo"', { eval: true, env: SHARE_ENV })
  .on('exit', () => {
    console.log(process.env.SET_IN_WORKER);  // Prints 'foo'.
  });
</code></pre>
<h2><code>worker.threadId</code><span><a class="mark" href="#worker_threads_worker_threadid" id="worker_threads_worker_threadid">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>An integer identifier for the current thread. On the corresponding worker object
(if there is any), it is available as <a href="#worker_threads_worker_threadid_1"><code>worker.threadId</code></a>.
This value is unique for each <a href="#worker_threads_class_worker"><code>Worker</code></a> instance inside a single process.</p>
<h2><code>worker.workerData</code><span><a class="mark" href="#worker_threads_worker_workerdata" id="worker_threads_worker_workerdata">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>An arbitrary JavaScript value that contains a clone of the data passed
to this thread’s <code>Worker</code> constructor.</p>
<p>The data is cloned as if using <a href="#worker_threads_port_postmessage_value_transferlist"><code>postMessage()</code></a>,
according to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p>
<pre><code class="language-js">const { Worker, isMainThread, workerData } = require('worker_threads');

if (isMainThread) {
  const worker = new Worker(__filename, { workerData: 'Hello, world!' });
} else {
  console.log(workerData);  // Prints 'Hello, world!'.
}
</code></pre>
<h2>Class: <code>MessageChannel</code><span><a class="mark" href="#worker_threads_class_messagechannel" id="worker_threads_class_messagechannel">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Instances of the <code>worker.MessageChannel</code> class represent an asynchronous,
two-way communications channel.
The <code>MessageChannel</code> has no methods of its own. <code>new MessageChannel()</code>
yields an object with <code>port1</code> and <code>port2</code> properties, which refer to linked
<a href="#worker_threads_class_messageport"><code>MessagePort</code></a> instances.</p>
<pre><code class="language-js">const { MessageChannel } = require('worker_threads');

const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log('received', message));
port2.postMessage({ foo: 'bar' });
// Prints: received { foo: 'bar' } from the `port1.on('message')` listener
</code></pre>
<h2>Class: <code>MessagePort</code><span><a class="mark" href="#worker_threads_class_messageport" id="worker_threads_class_messageport">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li>Extends: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Instances of the <code>worker.MessagePort</code> class represent one end of an
asynchronous, two-way communications channel. It can be used to transfer
structured data, memory regions and other <code>MessagePort</code>s between different
<a href="#worker_threads_class_worker"><code>Worker</code></a>s.</p>
<p>With the exception of <code>MessagePort</code>s being <a href="events.html"><code>EventEmitter</code></a>s rather
than <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget"><code>EventTarget</code></a>s, this implementation matches <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort">browser <code>MessagePort</code></a>s.</p>
<h3>Event: <code>'close'</code><span><a class="mark" href="#worker_threads_event_close" id="worker_threads_event_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>The <code>'close'</code> event is emitted once either side of the channel has been
disconnected.</p>
<pre><code class="language-js">const { MessageChannel } = require('worker_threads');
const { port1, port2 } = new MessageChannel();

// Prints:
//   foobar
//   closed!
port2.on('message', (message) => console.log(message));
port2.on('close', () => console.log('closed!'));

port1.postMessage('foobar');
port1.close();
</code></pre>
<h3>Event: <code>'message'</code><span><a class="mark" href="#worker_threads_event_message" id="worker_threads_event_message">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The transmitted value</li>
</ul>
<p>The <code>'message'</code> event is emitted for any incoming message, containing the cloned
input of <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a>.</p>
<p>Listeners on this event will receive a clone of the <code>value</code> parameter as passed
to <code>postMessage()</code> and no further arguments.</p>
<h3><code>port.close()</code><span><a class="mark" href="#worker_threads_port_close" id="worker_threads_port_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Disables further sending of messages on either side of the connection.
This method can be called when no further communication will happen over this
<code>MessagePort</code>.</p>
<p>The <a href="#worker_threads_event_close"><code>'close'</code> event</a> will be emitted on both <code>MessagePort</code> instances that
are part of the channel.</p>
<h3><code>port.postMessage(value[, transferList])</code><span><a class="mark" href="#worker_threads_port_postmessage_value_transferlist" id="worker_threads_port_postmessage_value_transferlist">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
<p>Sends a JavaScript value to the receiving side of this channel.
<code>value</code> will be transferred in a way which is compatible with
the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>.</p>
<p>In particular, the significant differences to <code>JSON</code> are:</p>
<ul>
<li><code>value</code> may contain circular references.</li>
<li><code>value</code> may contain instances of builtin JS types such as <code>RegExp</code>s,
<code>BigInt</code>s, <code>Map</code>s, <code>Set</code>s, etc.</li>
<li><code>value</code> may contain typed arrays, both using <code>ArrayBuffer</code>s
and <code>SharedArrayBuffer</code>s.</li>
<li><code>value</code> may contain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Module"><code>WebAssembly.Module</code></a> instances.</li>
<li><code>value</code> may not contain native (C++-backed) objects other than <code>MessagePort</code>s.</li>
</ul>
<pre><code class="language-js">const { MessageChannel } = require('worker_threads');
const { port1, port2 } = new MessageChannel();

port1.on('message', (message) => console.log(message));

const circularData = {};
circularData.foo = circularData;
// Prints: { foo: [Circular] }
port2.postMessage(circularData);
</code></pre>
<p><code>transferList</code> may be a list of <code>ArrayBuffer</code> and <code>MessagePort</code> objects.
After transferring, they will not be usable on the sending side of the channel
anymore (even if they are not contained in <code>value</code>). Unlike with
<a href="child_process.html">child processes</a>, transferring handles such as network sockets is currently
not supported.</p>
<p>If <code>value</code> contains <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a> instances, those will be accessible
from either thread. They cannot be listed in <code>transferList</code>.</p>
<p><code>value</code> may still contain <code>ArrayBuffer</code> instances that are not in
<code>transferList</code>; in that case, the underlying memory is copied rather than moved.</p>
<pre><code class="language-js">const { MessageChannel } = require('worker_threads');
const { port1, port2 } = new MessageChannel();

port1.on('message', (message) => console.log(message));

const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
// This posts a copy of `uint8Array`:
port2.postMessage(uint8Array);
// This does not copy data, but renders `uint8Array` unusable:
port2.postMessage(uint8Array, [ uint8Array.buffer ]);

// The memory for the `sharedUint8Array` will be accessible from both the
// original and the copy received by `.on('message')`:
const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
port2.postMessage(sharedUint8Array);

// This transfers a freshly created message port to the receiver.
// This can be used, for example, to create communication channels between
// multiple `Worker` threads that are children of the same parent thread.
const otherChannel = new MessageChannel();
port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
</code></pre>
<p>Because the object cloning uses the structured clone algorithm,
non-enumerable properties, property accessors, and object prototypes are
not preserved. In particular, <a href="buffer.html"><code>Buffer</code></a> objects will be read as
plain <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>s on the receiving side.</p>
<p>The message object will be cloned immediately, and can be modified after
posting without having side effects.</p>
<p>For more information on the serialization and deserialization mechanisms
behind this API, see the <a href="#v8_serialization_api">serialization API of the <code>v8</code> module</a>.</p>
<h4>Considerations when transferring TypedArrays and Buffers<span><a class="mark" href="#worker_threads_considerations_when_transferring_typedarrays_and_buffers" id="worker_threads_considerations_when_transferring_typedarrays_and_buffers">#</a></span></h4>
<p>All <code>TypedArray</code> and <code>Buffer</code> instances are views over an underlying
<code>ArrayBuffer</code>. That is, it is the <code>ArrayBuffer</code> that actually stores
the raw data while the <code>TypedArray</code> and <code>Buffer</code> objects provide a
way of viewing and manipulating the data. It is possible and common
for multiple views to be created over the same <code>ArrayBuffer</code> instance.
Great care must be taken when using a transfer list to transfer an
<code>ArrayBuffer</code> as doing so will cause all <code>TypedArray</code> and <code>Buffer</code>
instances that share that same <code>ArrayBuffer</code> to become unusable.</p>
<pre><code class="language-js">const ab = new ArrayBuffer(10);

const u1 = new Uint8Array(ab);
const u2 = new Uint16Array(ab);

console.log(u2.length);  // prints 5

port.postMessage(u1, [u1.buffer]);

console.log(u2.length);  // prints 0
</code></pre>
<p>For <code>Buffer</code> instances, specifically, whether the underlying
<code>ArrayBuffer</code> can be transferred or cloned depends entirely on how
instances were created, which often cannot be reliably determined.</p>
<p>Depending on how a <code>Buffer</code> instance was created, it may or may
not own its underlying <code>ArrayBuffer</code>. An <code>ArrayBuffer</code> must not
be transferred unless it is known that the <code>Buffer</code> instance
owns it. In particular, for <code>Buffer</code>s created from the internal
<code>Buffer</code> pool (using, for instance <code>Buffer.from()</code> or <code>Buffer.alloc()</code>),
transferring them is not possible and they will always be cloned,
which sends a copy of the entire <code>Buffer</code> pool.
This behavior may come with unintended higher memory
usage and possible security concerns.</p>
<p>See <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe()</code></a> for more details on <code>Buffer</code> pooling.</p>
<p>The <code>ArrayBuffer</code>s for <code>Buffer</code> instances created using
<code>Buffer.alloc()</code> or <code>Buffer.allocUnsafeSlow()</code> can always be
transferred but doing so will render all other existing views of
those <code>ArrayBuffer</code>s unusable.</p>
<h3><code>port.ref()</code><span><a class="mark" href="#worker_threads_port_ref" id="worker_threads_port_ref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed port will
<em>not</em> let the program exit if it's the only active handle left (the default
behavior). If the port is <code>ref()</code>ed, calling <code>ref()</code> again will have no effect.</p>
<p>If listeners are attached or removed using <code>.on('message')</code>, the port will
be <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether
listeners for the event exist.</p>
<h3><code>port.start()</code><span><a class="mark" href="#worker_threads_port_start" id="worker_threads_port_start">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Starts receiving messages on this <code>MessagePort</code>. When using this port
as an event emitter, this will be called automatically once <code>'message'</code>
listeners are attached.</p>
<p>This method exists for parity with the Web <code>MessagePort</code> API. In Node.js,
it is only useful for ignoring messages when no event listener is present.
Node.js also diverges in its handling of <code>.onmessage</code>. Setting it will
automatically call <code>.start()</code>, but unsetting it will let messages queue up
until a new handler is set or the port is discarded.</p>
<h3><code>port.unref()</code><span><a class="mark" href="#worker_threads_port_unref" id="worker_threads_port_unref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Calling <code>unref()</code> on a port will allow the thread to exit if this is the only
active handle in the event system. If the port is already <code>unref()</code>ed calling
<code>unref()</code> again will have no effect.</p>
<p>If listeners are attached or removed using <code>.on('message')</code>, the port will
be <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether
listeners for the event exist.</p>
<h2>Class: <code>Worker</code><span><a class="mark" href="#worker_threads_class_worker" id="worker_threads_class_worker">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li>Extends: <a href="#events_class_eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>The <code>Worker</code> class represents an independent JavaScript execution thread.
Most Node.js APIs are available inside of it.</p>
<p>Notable differences inside a Worker environment are:</p>
<ul>
<li>The <a href="#process_process_stdin"><code>process.stdin</code></a>, <a href="#process_process_stdout"><code>process.stdout</code></a> and <a href="#process_process_stderr"><code>process.stderr</code></a>
may be redirected by the parent thread.</li>
<li>The <a href="#worker_threads_worker_ismainthread"><code>require('worker_threads').isMainThread</code></a> property is set to <code>false</code>.</li>
<li>The <a href="#worker_threads_worker_parentport"><code>require('worker_threads').parentPort</code></a> message port is available.</li>
<li><a href="#process_process_exit_code"><code>process.exit()</code></a> does not stop the whole program, just the single thread,
and <a href="#process_process_abort"><code>process.abort()</code></a> is not available.</li>
<li><a href="#process_process_chdir_directory"><code>process.chdir()</code></a> and <code>process</code> methods that set group or user ids
are not available.</li>
<li><a href="#process_process_env"><code>process.env</code></a> is a copy of the parent thread's environment variables,
unless otherwise specified. Changes to one copy will not be visible in other
threads, and will not be visible to native add-ons (unless
<a href="#worker_threads_worker_share_env"><code>worker.SHARE_ENV</code></a> has been passed as the <code>env</code> option to the
<a href="#worker_threads_class_worker"><code>Worker</code></a> constructor).</li>
<li><a href="#process_process_title"><code>process.title</code></a> cannot be modified.</li>
<li>Signals will not be delivered through <a href="#process_signal_events"><code>process.on('...')</code></a>.</li>
<li>Execution may stop at any point as a result of <a href="#worker_threads_worker_terminate"><code>worker.terminate()</code></a>
being invoked.</li>
<li>IPC channels from parent processes are not accessible.</li>
<li>The <a href="tracing.html"><code>trace_events</code></a> module is not supported.</li>
<li>Native add-ons can only be loaded from multiple threads if they fulfill
<a href="#addons_worker_support">certain conditions</a>.</li>
</ul>
<p>Creating <code>Worker</code> instances inside of other <code>Worker</code>s is possible.</p>
<p>Like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API">Web Workers</a> and the <a href="cluster.html"><code>cluster</code> module</a>, two-way communication can be
achieved through inter-thread message passing. Internally, a <code>Worker</code> has a
built-in pair of <a href="#worker_threads_class_messageport"><code>MessagePort</code></a>s that are already associated with each other
when the <code>Worker</code> is created. While the <code>MessagePort</code> object on the parent side
is not directly exposed, its functionalities are exposed through
<a href="#worker_threads_worker_postmessage_value_transferlist"><code>worker.postMessage()</code></a> and the <a href="#worker_threads_event_message_1"><code>worker.on('message')</code></a> event
on the <code>Worker</code> object for the parent thread.</p>
<p>To create custom messaging channels (which is encouraged over using the default
global channel because it facilitates separation of concerns), users can create
a <code>MessageChannel</code> object on either thread and pass one of the
<code>MessagePort</code>s on that <code>MessageChannel</code> to the other thread through a
pre-existing channel, such as the global one.</p>
<p>See <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> for more information on how messages are passed,
and what kind of JavaScript values can be successfully transported through
the thread barrier.</p>
<pre><code class="language-js">const assert = require('assert');
const {
  Worker, MessageChannel, MessagePort, isMainThread, parentPort
} = require('worker_threads');
if (isMainThread) {
  const worker = new Worker(__filename);
  const subChannel = new MessageChannel();
  worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]);
  subChannel.port2.on('message', (value) => {
    console.log('received:', value);
  });
} else {
  parentPort.once('message', (value) => {
    assert(value.hereIsYourPort instanceof MessagePort);
    value.hereIsYourPort.postMessage('the worker is sending this');
    value.hereIsYourPort.close();
  });
}
</code></pre>
<h3><code>new Worker(filename[, options])</code><span><a class="mark" href="#worker_threads_new_worker_filename_options" id="worker_threads_new_worker_filename_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.17.0</td>
<td><p>The <code>transferList</code> option was introduced.</p></td></tr>
<tr><td>v12.17.0</td>
<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>resourceLimits</code> option was introduced.</p></td></tr>
<tr><td>v12.16.0</td>
<td><p>The <code>argv</code> option was introduced.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>filename</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#url_the_whatwg_url_api" class="type">&#x3C;URL></a> The path to the Worker’s main script or module. Must
be either an absolute path or a relative path (i.e. relative to the
current working directory) starting with <code>./</code> or <code>../</code>, or a WHATWG <code>URL</code>
object using <code>file:</code> protocol.
If <code>options.eval</code> is <code>true</code>, this is a string containing JavaScript code
rather than a path.</li>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>argv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any[]></a> List of arguments which would be stringified and appended to
<code>process.argv</code> in the worker. This is mostly similar to the <code>workerData</code>
but the values will be available on the global <code>process.argv</code> as if they
were passed as CLI options to the script.</li>
<li><code>env</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> If set, specifies the initial value of <code>process.env</code> inside
the Worker thread. As a special value, <a href="#worker_threads_worker_share_env"><code>worker.SHARE_ENV</code></a> may be used
to specify that the parent thread and the child thread should share their
environment variables; in that case, changes to one thread’s <code>process.env</code>
object will affect the other thread as well. <strong>Default:</strong> <code>process.env</code>.</li>
<li><code>eval</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If <code>true</code> and the first argument is a <code>string</code>, interpret
the first argument to the constructor as a script that is executed once the
worker is online.</li>
<li><code>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> List of node CLI options passed to the worker.
V8 options (such as <code>--max-old-space-size</code>) and options that affect the
process (such as <code>--title</code>) are not supported. If set, this will be provided
as <a href="#process_process_execargv"><code>process.execArgv</code></a> inside the worker. By default, options will be
inherited from the parent thread.</li>
<li><code>stdin</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If this is set to <code>true</code>, then <code>worker.stdin</code> will
provide a writable stream whose contents will appear as <code>process.stdin</code>
inside the Worker. By default, no data is provided.</li>
<li><code>stdout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If this is set to <code>true</code>, then <code>worker.stdout</code> will
not automatically be piped through to <code>process.stdout</code> in the parent.</li>
<li><code>stderr</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If this is set to <code>true</code>, then <code>worker.stderr</code> will
not automatically be piped through to <code>process.stderr</code> in the parent.</li>
<li><code>workerData</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any JavaScript value that will be cloned and made
available as <a href="#worker_threads_worker_workerdata"><code>require('worker_threads').workerData</code></a>. The cloning will
occur as described in the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>, and an error
will be thrown if the object cannot be cloned (e.g. because it contains
<code>function</code>s).</li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a> If one or more <code>MessagePort</code>-like objects
are passed in <code>workerData</code>, a <code>transferList</code> is required for those
items or <a href="#errors_err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a> will be thrown.
See <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> for more information.</li>
<li>
<p><code>resourceLimits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An optional set of resource limits for the new
JS engine instance. Reaching these limits will lead to termination of the
<code>Worker</code> instance. These limits only affect the JS engine, and no external
data, including no <code>ArrayBuffer</code>s. Even if these limits are set, the process
may still abort if it encounters a global out-of-memory situation.</p>
<ul>
<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The maximum size of the main heap in MB.</li>
<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The maximum size of a heap space for
recently created objects.</li>
<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The size of a pre-allocated memory range
used for generated code.</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3>Event: <code>'error'</code><span><a class="mark" href="#worker_threads_event_error" id="worker_threads_event_error">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a></li>
</ul>
<p>The <code>'error'</code> event is emitted if the worker thread throws an uncaught
exception. In that case, the worker will be terminated.</p>
<h3>Event: <code>'exit'</code><span><a class="mark" href="#worker_threads_event_exit" id="worker_threads_event_exit">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>exitCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>The <code>'exit'</code> event is emitted once the worker has stopped. If the worker
exited by calling <a href="#process_process_exit_code"><code>process.exit()</code></a>, the <code>exitCode</code> parameter will be the
passed exit code. If the worker was terminated, the <code>exitCode</code> parameter will
be <code>1</code>.</p>
<p>This is the final event emitted by any <code>Worker</code> instance.</p>
<h3>Event: <code>'message'</code><span><a class="mark" href="#worker_threads_event_message_1" id="worker_threads_event_message_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The transmitted value</li>
</ul>
<p>The <code>'message'</code> event is emitted when the worker thread has invoked
<a href="#worker_threads_worker_postmessage_value_transferlist"><code>require('worker_threads').parentPort.postMessage()</code></a>.
See the <a href="#worker_threads_event_message"><code>port.on('message')</code></a> event for more details.</p>
<p>All messages sent from the worker thread will be emitted before the
<a href="#worker_threads_event_exit"><code>'exit'</code> event</a> is emitted on the <code>Worker</code> object.</p>
<h3>Event: <code>'online'</code><span><a class="mark" href="#worker_threads_event_online" id="worker_threads_event_online">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>The <code>'online'</code> event is emitted when the worker thread has started executing
JavaScript code.</p>
<h3><code>worker.getHeapSnapshot()</code><span><a class="mark" href="#worker_threads_worker_getheapsnapshot" id="worker_threads_worker_getheapsnapshot">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.17.0</span>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> A promise for a Readable Stream containing
a V8 heap snapshot</li>
</ul>
<p>Returns a readable stream for a V8 snapshot of the current state of the Worker.
See <a href="#v8_v8_getheapsnapshot"><code>v8.getHeapSnapshot()</code></a> for more details.</p>
<p>If the Worker thread is no longer running, which may occur before the
<a href="#worker_threads_event_exit"><code>'exit'</code> event</a> is emitted, the returned <code>Promise</code> will be rejected
immediately with an <a href="#ERR_WORKER_NOT_RUNNING"><code>ERR_WORKER_NOT_RUNNING</code></a> error.</p>
<h3><code>worker.postMessage(value[, transferList])</code><span><a class="mark" href="#worker_threads_worker_postmessage_value_transferlist" id="worker_threads_worker_postmessage_value_transferlist">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>transferList</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
<p>Send a message to the worker that will be received via
<a href="#worker_threads_event_message"><code>require('worker_threads').parentPort.on('message')</code></a>.
See <a href="#worker_threads_port_postmessage_value_transferlist"><code>port.postMessage()</code></a> for more details.</p>
<h3><code>worker.ref()</code><span><a class="mark" href="#worker_threads_worker_ref" id="worker_threads_worker_ref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Opposite of <code>unref()</code>, calling <code>ref()</code> on a previously <code>unref()</code>ed worker will
<em>not</em> let the program exit if it's the only active handle left (the default
behavior). If the worker is <code>ref()</code>ed, calling <code>ref()</code> again will have
no effect.</p>
<h3><code>worker.resourceLimits</code><span><a class="mark" href="#worker_threads_worker_resourcelimits_1" id="worker_threads_worker_resourcelimits_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v12.16.0</span>
</div>
<ul>
<li>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>maxYoungGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>maxOldGenerationSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>codeRangeSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
<p>Provides the set of JS engine resource constraints for this Worker thread.
If the <code>resourceLimits</code> option was passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor,
this matches its values.</p>
<p>If the worker has stopped, the return value is an empty object.</p>
<h3><code>worker.stderr</code><span><a class="mark" href="#worker_threads_worker_stderr" id="worker_threads_worker_stderr">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>This is a readable stream which contains data written to <a href="#process_process_stderr"><code>process.stderr</code></a>
inside the worker thread. If <code>stderr: true</code> was not passed to the
<a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, then data will be piped to the parent thread's
<a href="#process_process_stderr"><code>process.stderr</code></a> stream.</p>
<h3><code>worker.stdin</code><span><a class="mark" href="#worker_threads_worker_stdin" id="worker_threads_worker_stdin">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> | <a href="#stream_class_stream_writable" class="type">&#x3C;stream.Writable></a></li>
</ul>
<p>If <code>stdin: true</code> was passed to the <a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, this is a
writable stream. The data written to this stream will be made available in
the worker thread as <a href="#process_process_stdin"><code>process.stdin</code></a>.</p>
<h3><code>worker.stdout</code><span><a class="mark" href="#worker_threads_worker_stdout" id="worker_threads_worker_stdout">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="#stream_class_stream_readable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>This is a readable stream which contains data written to <a href="#process_process_stdout"><code>process.stdout</code></a>
inside the worker thread. If <code>stdout: true</code> was not passed to the
<a href="#worker_threads_class_worker"><code>Worker</code></a> constructor, then data will be piped to the parent thread's
<a href="#process_process_stdout"><code>process.stdout</code></a> stream.</p>
<h3><code>worker.terminate()</code><span><a class="mark" href="#worker_threads_worker_terminate" id="worker_threads_worker_terminate">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v12.5.0</td>
<td><p>This function now returns a Promise. Passing a callback is deprecated, and was useless up to this version, as the Worker was actually terminated synchronously. Terminating is now a fully asynchronous operation.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Stop all JavaScript execution in the worker thread as soon as possible.
Returns a Promise for the exit code that is fulfilled when the
<a href="#worker_threads_event_exit"><code>'exit'</code> event</a> is emitted.</p>
<h3><code>worker.threadId</code><span><a class="mark" href="#worker_threads_worker_threadid_1" id="worker_threads_worker_threadid_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
</ul>
<p>An integer identifier for the referenced thread. Inside the worker thread,
it is available as <a href="#worker_threads_worker_threadid"><code>require('worker_threads').threadId</code></a>.
This value is unique for each <code>Worker</code> instance inside a single process.</p>
<h3><code>worker.unref()</code><span><a class="mark" href="#worker_threads_worker_unref" id="worker_threads_worker_unref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Calling <code>unref()</code> on a worker will allow the thread to exit if this is the only
active handle in the event system. If the worker is already <code>unref()</code>ed calling
<code>unref()</code> again will have no effect.</p>
<h1>Zlib<span><a class="mark" href="#zlib_zlib" id="zlib_zlib">#</a></span></h1>

<p></p><div class="api_stability api_stability_2"><a href="#documentation_stability_index">Stability: 2</a> - Stable</div><p></p>
<p>The <code>zlib</code> module provides compression functionality implemented using Gzip,
Deflate/Inflate, and Brotli.</p>
<p>To access it:</p>
<pre><code class="language-js">const zlib = require('zlib');
</code></pre>
<p>Compression and decompression are built around the Node.js <a href="stream.md">Streams API</a>.</p>
<p>Compressing or decompressing a stream (such as a file) can be accomplished by
piping the source stream through a <code>zlib</code> <code>Transform</code> stream into a destination
stream:</p>
<pre><code class="language-js">const { createGzip } = require('zlib');
const { pipeline } = require('stream');
const {
  createReadStream,
  createWriteStream
} = require('fs');

const gzip = createGzip();
const source = createReadStream('input.txt');
const destination = createWriteStream('input.txt.gz');

pipeline(source, gzip, destination, (err) => {
  if (err) {
    console.error('An error occurred:', err);
    process.exitCode = 1;
  }
});

// Or, Promisified

const { promisify } = require('util');
const pipe = promisify(pipeline);

async function do_gzip(input, output) {
  const gzip = createGzip();
  const source = createReadStream(input);
  const destination = createWriteStream(output);
  await pipe(source, gzip, destination);
}

do_gzip('input.txt', 'input.txt.gz')
  .catch((err) => {
    console.error('An error occurred:', err);
    process.exitCode = 1;
  });
</code></pre>
<p>It is also possible to compress or decompress data in a single step:</p>
<pre><code class="language-js">const { deflate, unzip } = require('zlib');

const input = '.................................';
deflate(input, (err, buffer) => {
  if (err) {
    console.error('An error occurred:', err);
    process.exitCode = 1;
  }
  console.log(buffer.toString('base64'));
});

const buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');
unzip(buffer, (err, buffer) => {
  if (err) {
    console.error('An error occurred:', err);
    process.exitCode = 1;
  }
  console.log(buffer.toString());
});

// Or, Promisified

const { promisify } = require('util');
const do_unzip = promisify(unzip);

do_unzip(buffer)
  .then((buf) => console.log(buf.toString()))
  .catch((err) => {
    console.error('An error occurred:', err);
    process.exitCode = 1;
  });
</code></pre>
<h2>Threadpool usage and performance considerations<span><a class="mark" href="#zlib_threadpool_usage_and_performance_considerations" id="zlib_threadpool_usage_and_performance_considerations">#</a></span></h2>
<p>All <code>zlib</code> APIs, except those that are explicitly synchronous, use the Node.js
internal threadpool. This can lead to surprising effects and performance
limitations in some applications.</p>
<p>Creating and using a large number of zlib objects simultaneously can cause
significant memory fragmentation.</p>
<pre><code class="language-js">const zlib = require('zlib');

const payload = Buffer.from('This is some data');

// WARNING: DO NOT DO THIS!
for (let i = 0; i &#x3C; 30000; ++i) {
  zlib.deflate(payload, (err, buffer) => {});
}
</code></pre>
<p>In the preceding example, 30,000 deflate instances are created concurrently.
Because of how some operating systems handle memory allocation and
deallocation, this may lead to to significant memory fragmentation.</p>
<p>It is strongly recommended that the results of compression
operations be cached to avoid duplication of effort.</p>
<h2>Compressing HTTP requests and responses<span><a class="mark" href="#zlib_compressing_http_requests_and_responses" id="zlib_compressing_http_requests_and_responses">#</a></span></h2>
<p>The <code>zlib</code> module can be used to implement support for the <code>gzip</code>, <code>deflate</code>
and <code>br</code> content-encoding mechanisms defined by
<a href="https://tools.ietf.org/html/rfc7230#section-4.2">HTTP</a>.</p>
<p>The HTTP <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3"><code>Accept-Encoding</code></a> header is used within an http request to identify
the compression encodings accepted by the client. The <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11"><code>Content-Encoding</code></a>
header is used to identify the compression encodings actually applied to a
message.</p>
<p>The examples given below are drastically simplified to show the basic concept.
Using <code>zlib</code> encoding can be expensive, and the results ought to be cached.
See <a href="#zlib_memory_usage_tuning">Memory usage tuning</a> for more information on the speed/memory/compression
tradeoffs involved in <code>zlib</code> usage.</p>
<pre><code class="language-js">// Client request example
const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
const { pipeline } = require('stream');

const request = http.get({ host: 'example.com',
                           path: '/',
                           port: 80,
                           headers: { 'Accept-Encoding': 'br,gzip,deflate' } });
request.on('response', (response) => {
  const output = fs.createWriteStream('example.com_index.html');

  const onError = (err) => {
    if (err) {
      console.error('An error occurred:', err);
      process.exitCode = 1;
    }
  };

  switch (response.headers['content-encoding']) {
    case 'br':
      pipeline(response, zlib.createBrotliDecompress(), output, onError);
      break;
    // Or, just use zlib.createUnzip() to handle both of the following cases:
    case 'gzip':
      pipeline(response, zlib.createGunzip(), output, onError);
      break;
    case 'deflate':
      pipeline(response, zlib.createInflate(), output, onError);
      break;
    default:
      pipeline(response, output, onError);
      break;
  }
});
</code></pre>
<pre><code class="language-js">// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
const { pipeline } = require('stream');

http.createServer((request, response) => {
  const raw = fs.createReadStream('index.html');
  // Store both a compressed and an uncompressed version of the resource.
  response.setHeader('Vary', 'Accept-Encoding');
  let acceptEncoding = request.headers['accept-encoding'];
  if (!acceptEncoding) {
    acceptEncoding = '';
  }

  const onError = (err) => {
    if (err) {
      // If an error occurs, there's not much we can do because
      // the server has already sent the 200 response code and
      // some amount of data has already been sent to the client.
      // The best we can do is terminate the response immediately
      // and log the error.
      response.end();
      console.error('An error occurred:', err);
    }
  };

  // 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' });
    pipeline(raw, zlib.createDeflate(), response, onError);
  } else if (/\bgzip\b/.test(acceptEncoding)) {
    response.writeHead(200, { 'Content-Encoding': 'gzip' });
    pipeline(raw, zlib.createGzip(), response, onError);
  } else if (/\bbr\b/.test(acceptEncoding)) {
    response.writeHead(200, { 'Content-Encoding': 'br' });
    pipeline(raw, zlib.createBrotliCompress(), response, onError);
  } else {
    response.writeHead(200, {});
    pipeline(raw, response, onError);
  }
}).listen(1337);
</code></pre>
<p>By default, the <code>zlib</code> methods will throw an error when decompressing
truncated data. However, if it is known that the data is incomplete, or
the desire is to inspect only the beginning of a compressed file, it is
possible to suppress the default error handling by changing the flushing
method that is used to decompress the last chunk of input data:</p>
<pre><code class="language-js">// This is a truncated version of the buffer from the above examples
const buffer = Buffer.from('eJzT0yMA', 'base64');

zlib.unzip(
  buffer,
  // For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.
  { finishFlush: zlib.constants.Z_SYNC_FLUSH },
  (err, buffer) => {
    if (err) {
      console.error('An error occurred:', err);
      process.exitCode = 1;
    }
    console.log(buffer.toString());
  });
</code></pre>
<p>This will not change the behavior in other error-throwing situations, e.g.
when the input data has an invalid format. Using this method, it will not be
possible to determine whether the input ended prematurely or lacks the
integrity checks, making it necessary to manually check that the
decompressed result is valid.</p>
<h2>Memory usage tuning<span><a class="mark" href="#zlib_memory_usage_tuning" id="zlib_memory_usage_tuning">#</a></span></h2>

<h3>For zlib-based streams<span><a class="mark" href="#zlib_for_zlib_based_streams" id="zlib_for_zlib_based_streams">#</a></span></h3>
<p>From <code>zlib/zconf.h</code>, modified for Node.js usage:</p>
<p>The memory requirements for deflate are (in bytes):</p>
<!-- eslint-disable semi -->
<pre><code class="language-js">(1 &#x3C;&#x3C; (windowBits + 2)) + (1 &#x3C;&#x3C; (memLevel + 9))
</code></pre>
<p>That is: 128K for <code>windowBits</code> = 15 + 128K for <code>memLevel</code> = 8
(default values) plus a few kilobytes for small objects.</p>
<p>For example, to reduce the default memory requirements from 256K to 128K, the
options should be set to:</p>
<pre><code class="language-js">const options = { windowBits: 14, memLevel: 7 };
</code></pre>
<p>This will, however, generally degrade compression.</p>
<p>The memory requirements for inflate are (in bytes) <code>1 &#x3C;&#x3C; windowBits</code>.
That is, 32K for <code>windowBits</code> = 15 (default value) plus a few kilobytes
for small objects.</p>
<p>This is in addition to a single internal output slab buffer of size
<code>chunkSize</code>, which defaults to 16K.</p>
<p>The speed of <code>zlib</code> compression is affected most dramatically by the
<code>level</code> setting. A higher level will result in better compression, but
will take longer to complete. A lower level will result in less
compression, but will be much faster.</p>
<p>In general, greater memory usage options will mean that Node.js has to make
fewer calls to <code>zlib</code> because it will be able to process more data on
each <code>write</code> operation. So, this is another factor that affects the
speed, at the cost of memory usage.</p>
<h3>For Brotli-based streams<span><a class="mark" href="#zlib_for_brotli_based_streams" id="zlib_for_brotli_based_streams">#</a></span></h3>
<p>There are equivalents to the zlib options for Brotli-based streams, although
these options have different ranges than the zlib ones:</p>
<ul>
<li>zlib’s <code>level</code> option matches Brotli’s <code>BROTLI_PARAM_QUALITY</code> option.</li>
<li>zlib’s <code>windowBits</code> option matches Brotli’s <code>BROTLI_PARAM_LGWIN</code> option.</li>
</ul>
<p>See <a href="#zlib_brotli_constants">below</a> for more details on Brotli-specific options.</p>
<h2>Flushing<span><a class="mark" href="#zlib_flushing" id="zlib_flushing">#</a></span></h2>
<p>Calling <a href="#zlib_zlib_flush_kind_callback"><code>.flush()</code></a> on a compression stream will make <code>zlib</code> return as much
output as currently possible. This may come at the cost of degraded compression
quality, but can be useful when data needs to be available as soon as possible.</p>
<p>In the following example, <code>flush()</code> is used to write a compressed partial
HTTP response to the client:</p>
<pre><code class="language-js">const zlib = require('zlib');
const http = require('http');
const { pipeline } = require('stream');

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();
  let i;

  pipeline(output, response, (err) => {
    if (err) {
      // If an error occurs, there's not much we can do because
      // the server has already sent the 200 response code and
      // some amount of data has already been sent to the client.
      // The best we can do is terminate the response immediately
      // and log the error.
      clearInterval(i);
      response.end();
      console.error('An error occurred:', err);
    }
  });

  i = setInterval(() => {
    output.write(`The current time is ${Date()}\n`, () => {
      // The data has been passed to zlib, but the compression algorithm may
      // have decided to buffer the data for more efficient compression.
      // Calling .flush() will make the data available as soon as the client
      // is ready to receive it.
      output.flush();
    });
  }, 1000);
}).listen(1337);
</code></pre>
<h2>Constants<span><a class="mark" href="#zlib_constants" id="zlib_constants">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>

<h3>zlib constants<span><a class="mark" href="#zlib_zlib_constants" id="zlib_zlib_constants">#</a></span></h3>
<p>All of the constants defined in <code>zlib.h</code> are also defined on
<code>require('zlib').constants</code>. In the normal course of operations, it will not be
necessary to use these constants. They are documented so that their presence is
not surprising. This section is taken almost directly from the
<a href="https://zlib.net/manual.html#Constants">zlib documentation</a>.</p>
<p>Previously, the constants were available directly from <code>require('zlib')</code>, for
instance <code>zlib.Z_NO_FLUSH</code>. Accessing the constants directly from the module is
currently still possible but is deprecated.</p>
<p>Allowed flush values.</p>
<ul>
<li><code>zlib.constants.Z_NO_FLUSH</code></li>
<li><code>zlib.constants.Z_PARTIAL_FLUSH</code></li>
<li><code>zlib.constants.Z_SYNC_FLUSH</code></li>
<li><code>zlib.constants.Z_FULL_FLUSH</code></li>
<li><code>zlib.constants.Z_FINISH</code></li>
<li><code>zlib.constants.Z_BLOCK</code></li>
<li><code>zlib.constants.Z_TREES</code></li>
</ul>
<p>Return codes for the compression/decompression functions. Negative
values are errors, positive values are used for special but normal
events.</p>
<ul>
<li><code>zlib.constants.Z_OK</code></li>
<li><code>zlib.constants.Z_STREAM_END</code></li>
<li><code>zlib.constants.Z_NEED_DICT</code></li>
<li><code>zlib.constants.Z_ERRNO</code></li>
<li><code>zlib.constants.Z_STREAM_ERROR</code></li>
<li><code>zlib.constants.Z_DATA_ERROR</code></li>
<li><code>zlib.constants.Z_MEM_ERROR</code></li>
<li><code>zlib.constants.Z_BUF_ERROR</code></li>
<li><code>zlib.constants.Z_VERSION_ERROR</code></li>
</ul>
<p>Compression levels.</p>
<ul>
<li><code>zlib.constants.Z_NO_COMPRESSION</code></li>
<li><code>zlib.constants.Z_BEST_SPEED</code></li>
<li><code>zlib.constants.Z_BEST_COMPRESSION</code></li>
<li><code>zlib.constants.Z_DEFAULT_COMPRESSION</code></li>
</ul>
<p>Compression strategy.</p>
<ul>
<li><code>zlib.constants.Z_FILTERED</code></li>
<li><code>zlib.constants.Z_HUFFMAN_ONLY</code></li>
<li><code>zlib.constants.Z_RLE</code></li>
<li><code>zlib.constants.Z_FIXED</code></li>
<li><code>zlib.constants.Z_DEFAULT_STRATEGY</code></li>
</ul>
<h3>Brotli constants<span><a class="mark" href="#zlib_brotli_constants" id="zlib_brotli_constants">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.7.0</span>
</div>
<p>There are several options and other constants available for Brotli-based
streams:</p>
<h4>Flush operations<span><a class="mark" href="#zlib_flush_operations" id="zlib_flush_operations">#</a></span></h4>
<p>The following values are valid flush operations for Brotli-based streams:</p>
<ul>
<li><code>zlib.constants.BROTLI_OPERATION_PROCESS</code> (default for all operations)</li>
<li><code>zlib.constants.BROTLI_OPERATION_FLUSH</code> (default when calling <code>.flush()</code>)</li>
<li><code>zlib.constants.BROTLI_OPERATION_FINISH</code> (default for the last chunk)</li>
<li>
<p><code>zlib.constants.BROTLI_OPERATION_EMIT_METADATA</code></p>
<ul>
<li>This particular operation may be hard to use in a Node.js context,
as the streaming layer makes it hard to know which data will end up
in this frame. Also, there is currently no way to consume this data through
the Node.js API.</li>
</ul>
</li>
</ul>
<h4>Compressor options<span><a class="mark" href="#zlib_compressor_options" id="zlib_compressor_options">#</a></span></h4>
<p>There are several options that can be set on Brotli encoders, affecting
compression efficiency and speed. Both the keys and the values can be accessed
as properties of the <code>zlib.constants</code> object.</p>
<p>The most important options are:</p>
<ul>
<li>
<p><code>BROTLI_PARAM_MODE</code></p>
<ul>
<li><code>BROTLI_MODE_GENERIC</code> (default)</li>
<li><code>BROTLI_MODE_TEXT</code>, adjusted for UTF-8 text</li>
<li><code>BROTLI_MODE_FONT</code>, adjusted for WOFF 2.0 fonts</li>
</ul>
</li>
<li>
<p><code>BROTLI_PARAM_QUALITY</code></p>
<ul>
<li>Ranges from <code>BROTLI_MIN_QUALITY</code> to <code>BROTLI_MAX_QUALITY</code>,
with a default of <code>BROTLI_DEFAULT_QUALITY</code>.</li>
</ul>
</li>
<li>
<p><code>BROTLI_PARAM_SIZE_HINT</code></p>
<ul>
<li>Integer value representing the expected input size;
defaults to <code>0</code> for an unknown input size.</li>
</ul>
</li>
</ul>
<p>The following flags can be set for advanced control over the compression
algorithm and memory usage tuning:</p>
<ul>
<li>
<p><code>BROTLI_PARAM_LGWIN</code></p>
<ul>
<li>Ranges from <code>BROTLI_MIN_WINDOW_BITS</code> to <code>BROTLI_MAX_WINDOW_BITS</code>,
with a default of <code>BROTLI_DEFAULT_WINDOW</code>, or up to
<code>BROTLI_LARGE_MAX_WINDOW_BITS</code> if the <code>BROTLI_PARAM_LARGE_WINDOW</code> flag
is set.</li>
</ul>
</li>
<li>
<p><code>BROTLI_PARAM_LGBLOCK</code></p>
<ul>
<li>Ranges from <code>BROTLI_MIN_INPUT_BLOCK_BITS</code> to <code>BROTLI_MAX_INPUT_BLOCK_BITS</code>.</li>
</ul>
</li>
<li>
<p><code>BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING</code></p>
<ul>
<li>Boolean flag that decreases compression ratio in favour of
decompression speed.</li>
</ul>
</li>
<li>
<p><code>BROTLI_PARAM_LARGE_WINDOW</code></p>
<ul>
<li>Boolean flag enabling “Large Window Brotli” mode (not compatible with the
Brotli format as standardized in <a href="https://www.rfc-editor.org/rfc/rfc7932.txt">RFC 7932</a>).</li>
</ul>
</li>
<li>
<p><code>BROTLI_PARAM_NPOSTFIX</code></p>
<ul>
<li>Ranges from <code>0</code> to <code>BROTLI_MAX_NPOSTFIX</code>.</li>
</ul>
</li>
<li>
<p><code>BROTLI_PARAM_NDIRECT</code></p>
<ul>
<li>Ranges from <code>0</code> to <code>15 &#x3C;&#x3C; NPOSTFIX</code> in steps of <code>1 &#x3C;&#x3C; NPOSTFIX</code>.</li>
</ul>
</li>
</ul>
<h4>Decompressor options<span><a class="mark" href="#zlib_decompressor_options" id="zlib_decompressor_options">#</a></span></h4>
<p>These advanced options are available for controlling decompression:</p>
<ul>
<li>
<p><code>BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION</code></p>
<ul>
<li>Boolean flag that affects internal memory allocation patterns.</li>
</ul>
</li>
<li>
<p><code>BROTLI_DECODER_PARAM_LARGE_WINDOW</code></p>
<ul>
<li>Boolean flag enabling “Large Window Brotli” mode (not compatible with the
Brotli format as standardized in <a href="https://www.rfc-editor.org/rfc/rfc7932.txt">RFC 7932</a>).</li>
</ul>
</li>
</ul>
<h2>Class: <code>Options</code><span><a class="mark" href="#zlib_class_options" id="zlib_class_options">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>dictionary</code> option can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>dictionary</code> option can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v5.11.0</td>
<td><p>The <code>finishFlush</code> option is supported now.</p></td></tr>
<tr><td>v0.11.1</td>
<td><p><span>Added in: v0.11.1</span></p></td></tr>
</tbody></table>
</details>
</div>

<p>Each zlib-based class takes an <code>options</code> object. No options are required.</p>
<p>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">&#x3C;integer></a> <strong>Default:</strong> <code>zlib.constants.Z_NO_FLUSH</code></li>
<li><code>finishFlush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>zlib.constants.Z_FINISH</code></li>
<li><code>chunkSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>16 * 1024</code></li>
<li><code>windowBits</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>level</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;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">&#x3C;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">&#x3C;integer></a> (compression only)</li>
<li><code>dictionary</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;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">&#x3C;boolean></a> (If <code>true</code>, returns an object with <code>buffer</code> and <code>engine</code>.)</li>
</ul>
<p>See the <a href="https://zlib.net/manual.html#Advanced"><code>deflateInit2</code> and <code>inflateInit2</code></a> documentation for more
information.</p>
<h2>Class: <code>BrotliOptions</code><span><a class="mark" href="#zlib_class_brotlioptions" id="zlib_class_brotlioptions">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.7.0</span>
</div>

<p>Each Brotli-based class takes an <code>options</code> object. All options are optional.</p>
<ul>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>zlib.constants.BROTLI_OPERATION_PROCESS</code></li>
<li><code>finishFlush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>zlib.constants.BROTLI_OPERATION_FINISH</code></li>
<li><code>chunkSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> <strong>Default:</strong> <code>16 * 1024</code></li>
<li><code>params</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Key-value object containing indexed <a href="#zlib_brotli_constants">Brotli parameters</a>.</li>
</ul>
<p>For example:</p>
<pre><code class="language-js">const stream = zlib.createBrotliCompress({
  chunkSize: 32 * 1024,
  params: {
    [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
    [zlib.constants.BROTLI_PARAM_QUALITY]: 4,
    [zlib.constants.BROTLI_PARAM_SIZE_HINT]: fs.statSync(inputFile).size
  }
});
</code></pre>
<h2>Class: <code>zlib.BrotliCompress</code><span><a class="mark" href="#zlib_class_zlib_brotlicompress" id="zlib_class_zlib_brotlicompress">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.7.0</span>
</div>
<p>Compress data using the Brotli algorithm.</p>
<h2>Class: <code>zlib.BrotliDecompress</code><span><a class="mark" href="#zlib_class_zlib_brotlidecompress" id="zlib_class_zlib_brotlidecompress">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.7.0</span>
</div>
<p>Decompress data using the Brotli algorithm.</p>
<h2>Class: <code>zlib.Deflate</code><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: <code>zlib.DeflateRaw</code><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: <code>zlib.Gunzip</code><span><a class="mark" href="#zlib_class_zlib_gunzip" id="zlib_class_zlib_gunzip">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>Trailing garbage at the end of the input stream will now result in an <code>'error'</code> event.</p></td></tr>
<tr><td>v5.9.0</td>
<td><p>Multiple concatenated gzip file members are supported now.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>A truncated input stream will now result in an <code>'error'</code> event.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Decompress a gzip stream.</p>
<h2>Class: <code>zlib.Gzip</code><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: <code>zlib.Inflate</code><span><a class="mark" href="#zlib_class_zlib_inflate" id="zlib_class_zlib_inflate">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v5.0.0</td>
<td><p>A truncated input stream will now result in an <code>'error'</code> event.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Decompress a deflate stream.</p>
<h2>Class: <code>zlib.InflateRaw</code><span><a class="mark" href="#zlib_class_zlib_inflateraw" id="zlib_class_zlib_inflateraw">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.8.0</td>
<td><p>Custom dictionaries are now supported by <code>InflateRaw</code>.</p></td></tr>
<tr><td>v5.0.0</td>
<td><p>A truncated input stream will now result in an <code>'error'</code> event.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Decompress a raw deflate stream.</p>
<h2>Class: <code>zlib.Unzip</code><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: <code>zlib.ZlibBase</code><span><a class="mark" href="#zlib_class_zlib_zlibbase" id="zlib_class_zlib_zlibbase">#</a></span></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v11.7.0</td>
<td><p>This class was renamed from <code>Zlib</code> to <code>ZlibBase</code>.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Not exported by the <code>zlib</code> module. It is documented here because it is the base
class of the compressor/decompressor classes.</p>
<p>This class inherits from <a href="#stream_class_stream_transform"><code>stream.Transform</code></a>, allowing <code>zlib</code> objects to be
used in pipes and similar stream operations.</p>
<h3><code>zlib.bytesRead</code><span><a class="mark" href="#zlib_zlib_bytesread" id="zlib_zlib_bytesread">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v8.1.0</span><span>Deprecated since: v10.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#documentation_stability_index">Stability: 0</a> - Deprecated: Use <a href="#zlib_zlib_byteswritten"><code>zlib.bytesWritten</code></a> instead.</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Deprecated alias for <a href="#zlib_zlib_byteswritten"><code>zlib.bytesWritten</code></a>. This original name was chosen
because it also made sense to interpret the value as the number of bytes
read by the engine, but is inconsistent with other streams in Node.js that
expose values under these names.</p>
<h3><code>zlib.bytesWritten</code><span><a class="mark" href="#zlib_zlib_byteswritten" id="zlib_zlib_byteswritten">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The <code>zlib.bytesWritten</code> property specifies the number of bytes written to
the engine, before the bytes are processed (compressed or decompressed,
as appropriate for the derived class).</p>
<h3><code>zlib.close([callback])</code><span><a class="mark" href="#zlib_zlib_close_callback" id="zlib_zlib_close_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Close the underlying handle.</p>
<h3><code>zlib.flush([kind, ]callback)</code><span><a class="mark" href="#zlib_zlib_flush_kind_callback" id="zlib_zlib_flush_kind_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>kind</code> <strong>Default:</strong> <code>zlib.constants.Z_FULL_FLUSH</code> for zlib-based streams,
<code>zlib.constants.BROTLI_OPERATION_FLUSH</code> for Brotli-based streams.</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>Flush pending data. Don't call this frivolously, premature flushes negatively
impact the effectiveness of the compression algorithm.</p>
<p>Calling this only flushes data from the internal <code>zlib</code> state, and does not
perform flushing of any kind on the streams level. Rather, it behaves like a
normal call to <code>.write()</code>, i.e. it will be queued up behind other pending
writes and will only produce output when data is being read from the stream.</p>
<h3><code>zlib.params(level, strategy, callback)</code><span><a class="mark" href="#zlib_zlib_params_level_strategy_callback" id="zlib_zlib_params_level_strategy_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><code>level</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>strategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>This function is only available for zlib-based streams, i.e. not Brotli.</p>
<p>Dynamically update the compression level and compression strategy.
Only applicable to deflate algorithm.</p>
<h3><code>zlib.reset()</code><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><code>zlib.constants</code><span><a class="mark" href="#zlib_zlib_constants_1" id="zlib_zlib_constants_1">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v7.0.0</span>
</div>
<p>Provides an object enumerating Zlib-related constants.</p>
<h2><code>zlib.createBrotliCompress([options])</code><span><a class="mark" href="#zlib_zlib_createbrotlicompress_options" id="zlib_zlib_createbrotlicompress_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.7.0</span>
</div>
<ul>
<li><code>options</code> <a href="#zlib_class_brotlioptions" class="type">&#x3C;brotli options></a></li>
</ul>
<p>Creates and returns a new <a href="#zlib_class_zlib_brotlicompress"><code>BrotliCompress</code></a> object.</p>
<h2><code>zlib.createBrotliDecompress([options])</code><span><a class="mark" href="#zlib_zlib_createbrotlidecompress_options" id="zlib_zlib_createbrotlidecompress_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v11.7.0</span>
</div>
<ul>
<li><code>options</code> <a href="#zlib_class_brotlioptions" class="type">&#x3C;brotli options></a></li>
</ul>
<p>Creates and returns a new <a href="#zlib_class_zlib_brotlidecompress"><code>BrotliDecompress</code></a> object.</p>
<h2><code>zlib.createDeflate([options])</code><span><a class="mark" href="#zlib_zlib_createdeflate_options" id="zlib_zlib_createdeflate_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#zlib_class_zlib_deflate"><code>Deflate</code></a> object.</p>
<h2><code>zlib.createDeflateRaw([options])</code><span><a class="mark" href="#zlib_zlib_createdeflateraw_options" id="zlib_zlib_createdeflateraw_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#zlib_class_zlib_deflateraw"><code>DeflateRaw</code></a> object.</p>
<p>An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when <code>windowBits</code>
is set to 8 for raw deflate streams. zlib would automatically set <code>windowBits</code>
to 9 if was initially set to 8. Newer versions of zlib will throw an exception,
so Node.js restored the original behavior of upgrading a value of 8 to 9,
since passing <code>windowBits = 9</code> to zlib actually results in a compressed stream
that effectively uses an 8-bit window only.</p>
<h2><code>zlib.createGunzip([options])</code><span><a class="mark" href="#zlib_zlib_creategunzip_options" id="zlib_zlib_creategunzip_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#zlib_class_zlib_gunzip"><code>Gunzip</code></a> object.</p>
<h2><code>zlib.createGzip([options])</code><span><a class="mark" href="#zlib_zlib_creategzip_options" id="zlib_zlib_creategzip_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#zlib_class_zlib_gzip"><code>Gzip</code></a> object.
See <a href="#zlib_zlib">example</a>.</p>
<h2><code>zlib.createInflate([options])</code><span><a class="mark" href="#zlib_zlib_createinflate_options" id="zlib_zlib_createinflate_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#zlib_class_zlib_inflate"><code>Inflate</code></a> object.</p>
<h2><code>zlib.createInflateRaw([options])</code><span><a class="mark" href="#zlib_zlib_createinflateraw_options" id="zlib_zlib_createinflateraw_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#zlib_class_zlib_inflateraw"><code>InflateRaw</code></a> object.</p>
<h2><code>zlib.createUnzip([options])</code><span><a class="mark" href="#zlib_zlib_createunzip_options" id="zlib_zlib_createunzip_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#zlib_class_zlib_unzip"><code>Unzip</code></a> object.</p>
<h2>Convenience methods<span><a class="mark" href="#zlib_convenience_methods" id="zlib_convenience_methods">#</a></span></h2>

<p>All of these take a <a href="#buffer_class_buffer"><code>Buffer</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><code>DataView</code></a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> or string as the first argument, an optional second argument
to supply options to the <code>zlib</code> classes and will call the supplied callback
with <code>callback(error, result)</code>.</p>
<p>Every method has a <code>*Sync</code> counterpart, which accept the same arguments, but
without a callback.</p>
<h3><code>zlib.brotliCompress(buffer[, options], callback)</code><span><a class="mark" href="#zlib_zlib_brotlicompress_buffer_options_callback" id="zlib_zlib_brotlicompress_buffer_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.7.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_brotlioptions" class="type">&#x3C;brotli options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<h3><code>zlib.brotliCompressSync(buffer[, options])</code><span><a class="mark" href="#zlib_zlib_brotlicompresssync_buffer_options" id="zlib_zlib_brotlicompresssync_buffer_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.7.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_brotlioptions" class="type">&#x3C;brotli options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#zlib_class_zlib_brotlicompress"><code>BrotliCompress</code></a>.</p>
<h3><code>zlib.brotliDecompress(buffer[, options], callback)</code><span><a class="mark" href="#zlib_zlib_brotlidecompress_buffer_options_callback" id="zlib_zlib_brotlidecompress_buffer_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.7.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_brotlioptions" class="type">&#x3C;brotli options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<h3><code>zlib.brotliDecompressSync(buffer[, options])</code><span><a class="mark" href="#zlib_zlib_brotlidecompresssync_buffer_options" id="zlib_zlib_brotlidecompresssync_buffer_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v11.7.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_brotlioptions" class="type">&#x3C;brotli options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#zlib_class_zlib_brotlidecompress"><code>BrotliDecompress</code></a>.</p>
<h3><code>zlib.deflate(buffer[, options], callback)</code><span><a class="mark" href="#zlib_zlib_deflate_buffer_options_callback" id="zlib_zlib_deflate_buffer_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<h3><code>zlib.deflateSync(buffer[, options])</code><span><a class="mark" href="#zlib_zlib_deflatesync_buffer_options" id="zlib_zlib_deflatesync_buffer_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#zlib_class_zlib_deflate"><code>Deflate</code></a>.</p>
<h3><code>zlib.deflateRaw(buffer[, options], callback)</code><span><a class="mark" href="#zlib_zlib_deflateraw_buffer_options_callback" id="zlib_zlib_deflateraw_buffer_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<h3><code>zlib.deflateRawSync(buffer[, options])</code><span><a class="mark" href="#zlib_zlib_deflaterawsync_buffer_options" id="zlib_zlib_deflaterawsync_buffer_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#zlib_class_zlib_deflateraw"><code>DeflateRaw</code></a>.</p>
<h3><code>zlib.gunzip(buffer[, options], callback)</code><span><a class="mark" href="#zlib_zlib_gunzip_buffer_options_callback" id="zlib_zlib_gunzip_buffer_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<h3><code>zlib.gunzipSync(buffer[, options])</code><span><a class="mark" href="#zlib_zlib_gunzipsync_buffer_options" id="zlib_zlib_gunzipsync_buffer_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#zlib_class_zlib_gunzip"><code>Gunzip</code></a>.</p>
<h3><code>zlib.gzip(buffer[, options], callback)</code><span><a class="mark" href="#zlib_zlib_gzip_buffer_options_callback" id="zlib_zlib_gzip_buffer_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<h3><code>zlib.gzipSync(buffer[, options])</code><span><a class="mark" href="#zlib_zlib_gzipsync_buffer_options" id="zlib_zlib_gzipsync_buffer_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#zlib_class_zlib_gzip"><code>Gzip</code></a>.</p>
<h3><code>zlib.inflate(buffer[, options], callback)</code><span><a class="mark" href="#zlib_zlib_inflate_buffer_options_callback" id="zlib_zlib_inflate_buffer_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<h3><code>zlib.inflateSync(buffer[, options])</code><span><a class="mark" href="#zlib_zlib_inflatesync_buffer_options" id="zlib_zlib_inflatesync_buffer_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#zlib_class_zlib_inflate"><code>Inflate</code></a>.</p>
<h3><code>zlib.inflateRaw(buffer[, options], callback)</code><span><a class="mark" href="#zlib_zlib_inflateraw_buffer_options_callback" id="zlib_zlib_inflateraw_buffer_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<h3><code>zlib.inflateRawSync(buffer[, options])</code><span><a class="mark" href="#zlib_zlib_inflaterawsync_buffer_options" id="zlib_zlib_inflaterawsync_buffer_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#zlib_class_zlib_inflateraw"><code>InflateRaw</code></a>.</p>
<h3><code>zlib.unzip(buffer[, options], callback)</code><span><a class="mark" href="#zlib_zlib_unzip_buffer_options_callback" id="zlib_zlib_unzip_buffer_options_callback">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.6.0</td>
<td><p><span>Added in: v0.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<h3><code>zlib.unzipSync(buffer[, options])</code><span><a class="mark" href="#zlib_zlib_unzipsync_buffer_options" id="zlib_zlib_unzipsync_buffer_options">#</a></span></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v9.4.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>ArrayBuffer</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be any <code>TypedArray</code> or <code>DataView</code>.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>buffer</code> parameter can be an <code>Uint8Array</code> now.</p></td></tr>
<tr><td>v0.11.12</td>
<td><p><span>Added in: v0.11.12</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>buffer</code> <a href="#buffer_class_buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>options</code> <a href="#zlib_class_options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#zlib_class_zlib_unzip"><code>Unzip</code></a>.</p>

      </div>
    </div>
  </div>
  <script src="assets/highlight.pack.js"></script>
  <script>document.addEventListener('DOMContentLoaded', () => { hljs.initHighlightingOnLoad(); });</script>
</body>
</html>